<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>idapython &#8211; PT ESC</title>
	<atom:link href="https://ptesc.tech/en/tag/idapython/feed/" rel="self" type="application/rss+xml" />
	<link>https://ptesc.tech/en/</link>
	<description></description>
	<lastBuildDate>Wed, 30 Sep 2026 19:21:10 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=7.1.4</generator>

<image>
	<url>https://ptesc.tech/wp-content/uploads/2026/09/cropped-cropped-large_icon-32x32.png</url>
	<title>idapython &#8211; PT ESC</title>
	<link>https://ptesc.tech/en/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>How to fix CFG. Part two</title>
		<link>https://ptesc.tech/en/how-to-fix-cfg-part-two/</link>
		
		<dc:creator><![CDATA[global_author]]></dc:creator>
		<pubDate>Mon, 24 Mar 2025 17:59:29 +0000</pubDate>
				<category><![CDATA[Misc]]></category>
		<category><![CDATA[idapython]]></category>
		<category><![CDATA[reverse]]></category>
		<category><![CDATA[tips]]></category>
		<guid isPermaLink="false">http://localhost:8080/%d0%ba%d0%b0%d0%ba-%d0%bf%d0%be%d1%87%d0%b8%d0%bd%d0%b8%d1%82%d1%8c-cfg-%d1%87%d0%b0%d1%81%d1%82%d1%8c-%d0%b2%d1%82%d0%be%d1%80%d0%b0%d1%8f/</guid>

					<description><![CDATA[How to Fix CFG. Part Two 🛠 Earlier we described how to restore a Control Flow Graph (CFG) when it has been obfuscated. However, often during analysis, even of non-obfuscated malware, one can encounter cases where the CFG of certain function…]]></description>
										<content:encoded><![CDATA[<strong>How to Fix CFG. Part Two</strong> 🛠<br />
<br />
Earlier <a href="https://t.me/ptescalator/134" rel="noopener" target="_blank">we described</a> how to restore a Control Flow Graph (CFG) when it has been obfuscated. However, often during analysis, even of non-obfuscated malware, one can encounter cases where the CFG of certain functions is generated with errors. One such example is malware written in Delphi, where due to the specifics of exception handling, one can often see a picture <em>like in screenshot 1</em>.<br />
<br />
🤔 If you look more closely (<em>screenshot 2</em>), you can notice that in block (1), the address of one of the subsequent blocks (3) is saved onto the stack, after which some logic is executed (often — releasing resources or objects) and a jump occurs to the previously saved address (2).<br />
<br />
Because block 2 contains an additional reference, IDA cannot unambiguously determine the address to which the jump in <code>jmp eax</code> will be made. To fix this problem, we will write a small hook that will check and automatically patch such places in the code.<br />
<br />
Let&#8217;s create a hook class that will wait for the <code>ev_ana_insn</code> event. First, we need to make sure that this is indeed the sequence we are interested in, after which we go &#8220;upward&#8221; and try to find the address saved onto the stack. Then patch <code>jmp eax</code> to <code>jmp short address</code>.<br />
<br />
<pre class="wp-block-code"><span><code lang="x86asm" class="hljs language-x86asm language-x86asm">class DelphiJmpEaxFixer(idaapi<span class="hljs-number">.</span>IDP_Hooks):
    def lookup_push_insn(self, start: <span class="hljs-keyword">int</span>, limit: <span class="hljs-keyword">int</span> = <span class="hljs-number">30</span>) -&gt; <span class="hljs-keyword">int</span> | None:
        ...
 
    def ev_ana_insn(self, insn: idaapi<span class="hljs-number">.</span>insn_t) -&gt; bool:
        #
        b = bytes(idaapi<span class="hljs-number">.</span>get_bytes(insn<span class="hljs-number">.</span>ea - <span class="hljs-number">1</span>, <span class="hljs-number">3</span>))
        if idaapi<span class="hljs-number">.</span>is_tail(idaapi<span class="hljs-number">.</span>get_flags(insn<span class="hljs-number">.</span>ea)):
            return True
        # <span class="hljs-keyword">pop</span> <span class="hljs-built_in">eax</span> | <span class="hljs-number">58</span>
        # <span class="hljs-keyword">jmp</span> <span class="hljs-built_in">eax</span> | ff e0
        # ensure all <span class="hljs-keyword">pop</span> &amp; <span class="hljs-keyword">jmp</span> seq
        if b&#91;<span class="hljs-number">0</span>] != <span class="hljs-number">0x58</span> <span class="hljs-keyword">or</span> b&#91;<span class="hljs-number">1</span>] != <span class="hljs-number">0xFF</span> <span class="hljs-keyword">or</span> b&#91;<span class="hljs-number">2</span>] != <span class="hljs-number">0xE0</span>:
            return False
 
        print(f<span class="hljs-string">"Got jmp short eax at {insn.ea:x}"</span>)
        pushed_address = self<span class="hljs-number">.</span>lookup_push_insn(insn<span class="hljs-number">.</span>ea)
        if pushed_address is None:
            return False
        delta = pushed_address - insn<span class="hljs-number">.</span>ea
        if delta &lt; <span class="hljs-number">0</span> <span class="hljs-keyword">or</span> delta &gt; <span class="hljs-number">128</span>:
            return False
        print(f<span class="hljs-string">"{delta=}"</span>)
 
        asm_call = f<span class="hljs-string">"jmp short {delta}"</span>
        assembled = idaapi<span class="hljs-number">.</span>AssembleLine(insn<span class="hljs-number">.</span>ea, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, True, asm_call)
        if assembled is None:
            return False
        return idaapi<span class="hljs-number">.</span>patch_bytes(insn<span class="hljs-number">.</span>ea, assembled)
</code></span></pre><br />
<br />
Let&#8217;s write the function for finding the address saved onto the stack, <code>lookup_push_insn</code>. In it, we will find the presumed upper boundary of block 2 and check that the block has a single reference. Additionally, we will limit the search range for optimization purposes.<br />
<br />
<pre class="wp-block-code"><span><code lang="python" class="hljs language-python language-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">lookup_push_insn</span><span class="hljs-params">(self, start: int, limit: int = <span class="hljs-number">30</span>)</span> -&gt; int | <span class="hljs-keyword">None</span>:</span>
    ptr: int = start
    insn = idaapi.insn_t()
    jmp_ref = idaapi.BADADDR
    <span class="hljs-keyword">for</span> _ <span class="hljs-keyword">in</span> range(limit, <span class="hljs-number">0</span>, <span class="hljs-number">-1</span>):
        prev_addr = idaapi.decode_prev_insn(insn, ptr)
        <span class="hljs-keyword">if</span> prev_addr == idaapi.BADADDR:
            <span class="hljs-keyword">break</span>
        ptr = prev_addr
        _refs = &#91;xref <span class="hljs-keyword">for</span> xref <span class="hljs-keyword">in</span> idautils.CodeRefsTo(ptr, <span class="hljs-literal">False</span>)]
        <span class="hljs-comment"># If we found refs it's likely an upper basic block address</span>
        <span class="hljs-comment"># it must be a single jmp ref</span>
        <span class="hljs-keyword">if</span> _refs:
            <span class="hljs-keyword">if</span> len(_refs) != <span class="hljs-number">1</span>:
                <span class="hljs-keyword">return</span> <span class="hljs-literal">None</span>
            jmp_ref = next(iter(_refs))
            <span class="hljs-keyword">break</span>
 
    <span class="hljs-keyword">if</span> jmp_ref == idaapi.BADADDR:
        <span class="hljs-keyword">return</span> <span class="hljs-literal">None</span>
 
    ref_insn_sz = idaapi.decode_insn(insn, jmp_ref)
    <span class="hljs-keyword">if</span> ref_insn_sz == <span class="hljs-number">0</span> <span class="hljs-keyword">or</span> insn.itype != idaapi.NN_jmp:
        <span class="hljs-keyword">return</span> <span class="hljs-literal">None</span>
 
    addr = idaapi.decode_prev_insn(insn, ptr)
    <span class="hljs-keyword">if</span> addr == idaapi.BADADDR <span class="hljs-keyword">or</span> insn.itype != idaapi.NN_push:
        <span class="hljs-keyword">return</span> <span class="hljs-literal">None</span>
 
    <span class="hljs-keyword">return</span> insn.Op1.value
</code></span></pre><br />
<br />
Let&#8217;s add the hook initialization when the script starts and load it into IDA. Let&#8217;s run the binary file analysis again. As a result, we get the fixed graph (<em>screenshot 3</em>).<br />
<br />
The remaining single blocks are exception handler calls; in this case, they do not affect the program&#8217;s execution flow. It is worth remembering that while the hook is active, it will be automatically invoked even when marking up new code that was not previously marked up.<br />
<br />
<pre class="wp-block-code"><span><code lang="plaintext" class="hljs language-plaintext language-plaintext">hook_instance = DelphiJmpEaxFixer()
hook_instance.hook()
</code></span></pre><br />
<br />
<strong>Happy reversing!</strong> 💫

<figure class="wp-block-image"><img width="748" height="1024" src="https://ptesc.tech/wp-content/uploads/2025/03/photo_248@24-03-2025_17-59-30-748x1024.jpg" class="attachment-large size-large" alt="" decoding="async" loading="lazy" srcset="https://ptesc.tech/wp-content/uploads/2025/03/photo_248@24-03-2025_17-59-30-748x1024.jpg 748w, https://ptesc.tech/wp-content/uploads/2025/03/photo_248@24-03-2025_17-59-30-219x300.jpg 219w, https://ptesc.tech/wp-content/uploads/2025/03/photo_248@24-03-2025_17-59-30-768x1051.jpg 768w, https://ptesc.tech/wp-content/uploads/2025/03/photo_248@24-03-2025_17-59-30.jpg 935w" sizes="auto, (max-width: 748px) 100vw, 748px" /></figure>
<figure class="wp-block-image"><img width="516" height="1024" src="https://ptesc.tech/wp-content/uploads/2025/03/photo_249@24-03-2025_17-59-30-516x1024.jpg" class="attachment-large size-large" alt="" decoding="async" loading="lazy" srcset="https://ptesc.tech/wp-content/uploads/2025/03/photo_249@24-03-2025_17-59-30-516x1024.jpg 516w, https://ptesc.tech/wp-content/uploads/2025/03/photo_249@24-03-2025_17-59-30-151x300.jpg 151w, https://ptesc.tech/wp-content/uploads/2025/03/photo_249@24-03-2025_17-59-30.jpg 645w" sizes="auto, (max-width: 516px) 100vw, 516px" /></figure>

<br />
<br />
<span class="hashtag">#tip</span> <span class="hashtag">#reverse</span> <span class="hashtag">#idapython</span><br />
<a href="https://t.me/ptescalator" rel="noopener" target="_blank">@ptescalator</a>]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Static resolution of imports</title>
		<link>https://ptesc.tech/en/static-import-resolution/</link>
		
		<dc:creator><![CDATA[global_author]]></dc:creator>
		<pubDate>Thu, 23 Jan 2025 10:45:34 +0000</pubDate>
				<category><![CDATA[Misc]]></category>
		<category><![CDATA[idapython]]></category>
		<category><![CDATA[reverse]]></category>
		<category><![CDATA[tips]]></category>
		<guid isPermaLink="false">http://localhost:8080/%d1%81%d1%82%d0%b0%d1%82%d0%b8%d1%87%d0%b5%d1%81%d0%ba%d0%b8%d0%b9-%d1%80%d0%b5%d0%b7%d0%be%d0%bb%d0%b2-%d0%b8%d0%bc%d0%bf%d0%be%d1%80%d1%82%d0%be%d0%b2/</guid>

					<description><![CDATA[Static resolution of imports 👨‍💻 Dynamic resolution of imports by hash sums in malware is a well-worn topic, but to perform static analysis it is necessary to label API names and prototypes. To get from what is shown in screenshot 1 to what…]]></description>
										<content:encoded><![CDATA[<strong>Static resolution of imports</strong> 👨‍💻<br />
<br />
Dynamic resolution of imports by hash sums in malware is a well-worn topic, but to perform static analysis it is necessary to label API names and prototypes. To get from what is shown <em>in screenshot 1</em> to what is <em>in screenshot 2</em>, without struggling with manual labeling, you can write an IDAPython script.<br />
<br />
😠 Using <a href="https://www.zscaler.com/blogs/security-research/dodgebox-deep-dive-updated-arsenal-apt41-part-1" rel="noopener" target="_blank">DodgeBox</a> as an example, let&#8217;s look at resolution that consists of computing the address of an API function and placing it into a global structure. The implementation is <em>in screenshot 3</em>.<br />
<br />
We&#8217;ll skip the hashing algorithm, since it isn&#8217;t that important here. Before starting, it&#8217;s necessary to prepare a dictionary with WinAPI function names and their hash sums. To do this, we&#8217;ll select the libraries used in the binary. Here the DLL names are in plaintext, but sometimes there are only hash sums — in that case you can build a dictionary from all system DLLs. Our dictionary is <em>in screenshot 4</em>.<br />
<br />
Next, we make sure that the members in the structure are filled in sequentially, so that we can automatically extract the hash sums and module names from the code. Note — the first member of the structure is skipped. We create a structure of the required size (<em>screenshot 5</em>) so that it can hold all the functions.<br />
<br />
To extract the hash sums and library names, we write a function that will iterate over all calls to <code>get_proc_by_hash</code> and extract its arguments.<br />
<br />
<pre class="wp-block-code"><span><code lang="python" class="hljs language-python language-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">get_hashes</span><span class="hljs-params">(resolve_API_addr, get_proc_by_hash_addr)</span>:</span>
  result = &#91;]
  func: ida_funcs.func_t
  func = ida_funcs.get_func(resolve_API_addr)

  cur = func.start_ea
  <span class="hljs-keyword">while</span> cur &lt; func.end_ea:
    <span class="hljs-keyword">if</span> get_operand_value(cur, <span class="hljs-number">0</span>) == get_proc_by_hash_addr:
      result.append(get_args(cur))
    cur = ida_search.find_code(cur, SEARCH_DOWN)

  <span class="hljs-keyword">return</span> result</code></span></pre><br />
<br />
The <code>get_args</code> function goes up several steps from the <code>call</code> instruction and extracts the arguments.<br />
<br />
<pre class="wp-block-code"><span><code lang="x86asm" class="hljs language-x86asm language-x86asm">def get_args(call_addr):
  func_name_hash = None
  lib_name = None

  cur = call_addr
<span class="hljs-symbol">  True:</span>
    if print_insn_mnem(cur) == <span class="hljs-string">"mov"</span> <span class="hljs-keyword">and</span> print_operand(cur, <span class="hljs-number">0</span>) == <span class="hljs-string">"r8d"</span>:
      func_name_hash = get_operand_value(cur, <span class="hljs-number">1</span>) &amp; <span class="hljs-number">0xFFFFFFFF</span>
    elif print_insn_mnem(cur) == <span class="hljs-string">"lea"</span> <span class="hljs-keyword">and</span> print_operand(cur, <span class="hljs-number">0</span>) == <span class="hljs-string">"rcx"</span>:
      lib_name = ida_bytes<span class="hljs-number">.</span>get_strlit_contents(get_operand_value(cur, <span class="hljs-number">1</span>), -<span class="hljs-number">1</span>, STRTYPE_C_16).decode()

    if func_name_hash <span class="hljs-keyword">and</span> lib_name:
      return lib_name, func_name_hash
        
    cur = ida_search<span class="hljs-number">.</span>find_code(cur, SEARCH_UP)</code></span></pre><br />
<br />
The output of <code>get_hashes</code> will be a list that we use to fill in the API structure. The main function will look like this:<br />
<br />
<pre class="wp-block-code"><span><code lang="yaml" class="hljs language-yaml language-yaml"><span class="hljs-attr">struc:</span> <span class="hljs-string">ida_struct.struc_t</span> <span class="hljs-string">=</span> <span class="hljs-string">ida_struct.get_struc(ida_struct.get_struc_id("API"))</span>

<span class="hljs-string">funcs</span> <span class="hljs-string">=</span> <span class="hljs-string">get_hashes(0x180007A90,</span> <span class="hljs-number">0x1800078E0</span><span class="hljs-string">)</span>
<span class="hljs-string">for</span> <span class="hljs-string">i</span> <span class="hljs-string">in</span> <span class="hljs-string">range(1,</span> <span class="hljs-string">len(funcs)</span> <span class="hljs-string">+</span> <span class="hljs-number">1</span><span class="hljs-string">):</span>

  <span class="hljs-string">lib_name,</span> <span class="hljs-string">func_name_hash</span> <span class="hljs-string">=</span> <span class="hljs-string">funcs&#91;i</span> <span class="hljs-bullet">-</span> <span class="hljs-number">1</span><span class="hljs-string">]</span>
  <span class="hljs-attr">member:</span> <span class="hljs-string">ida_struct.member_t</span> <span class="hljs-string">=</span> <span class="hljs-string">struc.members&#91;i]</span>

  <span class="hljs-string">func_name</span> <span class="hljs-string">=</span> <span class="hljs-string">get_func_name(lib_name,</span> <span class="hljs-string">func_name_hash,</span> <span class="hljs-string">winapi_hashes_dict)</span>
  <span class="hljs-attr">if func_name:</span>
    <span class="hljs-string">ida_struct.set_member_name(struc,</span> <span class="hljs-string">member.soff,</span> <span class="hljs-string">func_name)</span>
  <span class="hljs-string">func_tinfo</span> <span class="hljs-string">=</span> <span class="hljs-string">get_func_tinfo(func_name)</span>
  <span class="hljs-attr">if func_tinfo:</span>
    <span class="hljs-string">ida_struct.set_member_tinfo(struc,</span> <span class="hljs-string">member,</span> <span class="hljs-number">0</span><span class="hljs-string">,</span> <span class="hljs-string">func_tinfo,</span> <span class="hljs-number">0</span><span class="hljs-string">)</span></code></span></pre><br />
<br />
The <code>get_func_name</code> function is simple to implement — it finds the API name in the dictionary by hash sum. But <code>get_func_tinfo</code> is more interesting: it creates an object containing the function prototype, which we also apply to the structure member.<br />
<br />
<pre class="wp-block-code"><span><code lang="python" class="hljs language-python language-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">get_func_tinfo</span><span class="hljs-params">(func_name)</span>:</span>
  tinfo = ida_typeinf.get_named_type(<span class="hljs-literal">None</span>, func_name, <span class="hljs-number">0</span>)
  <span class="hljs-keyword">if</span> tinfo:
    type_s = tinfo&#91;<span class="hljs-number">1</span>]
    field_s = tinfo&#91;<span class="hljs-number">2</span>]
    t = ida_typeinf.tinfo_t()
    t.deserialize(<span class="hljs-literal">None</span>, type_s, field_s)
    t.create_ptr(t)
    <span class="hljs-keyword">return</span> t
  <span class="hljs-keyword">else</span>:
    <span class="hljs-keyword">return</span> <span class="hljs-literal">None</span></code></span></pre><br />
<br />
The <code>ida_typeinf.get_named_type</code> function retrieves information about a type contained in the <code>Type Library (*.til)</code>. The call looks like this:<br />
<br />
<pre class="wp-block-code"><span><code lang="plaintext" class="hljs language-plaintext language-plaintext">Python&gt;get_func_tinfo("GetWindowsDirectoryW")
UINT (__stdcall *)(LPWSTR lpBuffer, UINT uSize)</code></span></pre><br />
<br />
However, the function actually returns an object of type <code>ida_typeinf.tinfo_t</code>.<br />
<br />
The API structure after running the script is shown <em>in screenshot 6</em>. If you apply it to a global variable, the resolution turns into what is visible <em>in screenshot 7</em>, and you can conveniently analyze the binary statically without launching a debugger.<br />
<br />
There is, of course, a temptation to write a <code>make_beautifully</code> function that itself subtracts the offsets, creates the structure and the members inside it, but that&#8217;s for another time.

<figure class="wp-block-image"><img width="1024" height="683" src="https://ptesc.tech/wp-content/uploads/2025/01/photo_180@23-01-2025_10-45-34-1024x683.jpg" class="attachment-large size-large" alt="" decoding="async" loading="lazy" srcset="https://ptesc.tech/wp-content/uploads/2025/01/photo_180@23-01-2025_10-45-34-1024x683.jpg 1024w, https://ptesc.tech/wp-content/uploads/2025/01/photo_180@23-01-2025_10-45-34-300x200.jpg 300w, https://ptesc.tech/wp-content/uploads/2025/01/photo_180@23-01-2025_10-45-34-768x512.jpg 768w, https://ptesc.tech/wp-content/uploads/2025/01/photo_180@23-01-2025_10-45-34.jpg 1200w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
<figure class="wp-block-image"><img width="1024" height="1024" src="https://ptesc.tech/wp-content/uploads/2025/01/photo_181@23-01-2025_10-45-34-1024x1024.jpg" class="attachment-large size-large" alt="" decoding="async" loading="lazy" srcset="https://ptesc.tech/wp-content/uploads/2025/01/photo_181@23-01-2025_10-45-34-1024x1024.jpg 1024w, https://ptesc.tech/wp-content/uploads/2025/01/photo_181@23-01-2025_10-45-34-300x300.jpg 300w, https://ptesc.tech/wp-content/uploads/2025/01/photo_181@23-01-2025_10-45-34-150x150.jpg 150w, https://ptesc.tech/wp-content/uploads/2025/01/photo_181@23-01-2025_10-45-34-768x768.jpg 768w, https://ptesc.tech/wp-content/uploads/2025/01/photo_181@23-01-2025_10-45-34.jpg 1200w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
<figure class="wp-block-image"><img width="1024" height="1024" src="https://ptesc.tech/wp-content/uploads/2025/01/photo_182@23-01-2025_10-45-34-1024x1024.jpg" class="attachment-large size-large" alt="" decoding="async" loading="lazy" srcset="https://ptesc.tech/wp-content/uploads/2025/01/photo_182@23-01-2025_10-45-34-1024x1024.jpg 1024w, https://ptesc.tech/wp-content/uploads/2025/01/photo_182@23-01-2025_10-45-34-300x300.jpg 300w, https://ptesc.tech/wp-content/uploads/2025/01/photo_182@23-01-2025_10-45-34-150x150.jpg 150w, https://ptesc.tech/wp-content/uploads/2025/01/photo_182@23-01-2025_10-45-34-768x768.jpg 768w, https://ptesc.tech/wp-content/uploads/2025/01/photo_182@23-01-2025_10-45-34.jpg 1200w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
<figure class="wp-block-image"><img width="1024" height="683" src="https://ptesc.tech/wp-content/uploads/2025/01/photo_183@23-01-2025_10-45-34-1024x683.jpg" class="attachment-large size-large" alt="" decoding="async" loading="lazy" srcset="https://ptesc.tech/wp-content/uploads/2025/01/photo_183@23-01-2025_10-45-34-1024x683.jpg 1024w, https://ptesc.tech/wp-content/uploads/2025/01/photo_183@23-01-2025_10-45-34-300x200.jpg 300w, https://ptesc.tech/wp-content/uploads/2025/01/photo_183@23-01-2025_10-45-34-768x512.jpg 768w, https://ptesc.tech/wp-content/uploads/2025/01/photo_183@23-01-2025_10-45-34.jpg 1200w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
<figure class="wp-block-image"><img width="1024" height="683" src="https://ptesc.tech/wp-content/uploads/2025/01/photo_184@23-01-2025_10-45-34-1024x683.jpg" class="attachment-large size-large" alt="" decoding="async" loading="lazy" srcset="https://ptesc.tech/wp-content/uploads/2025/01/photo_184@23-01-2025_10-45-34-1024x683.jpg 1024w, https://ptesc.tech/wp-content/uploads/2025/01/photo_184@23-01-2025_10-45-34-300x200.jpg 300w, https://ptesc.tech/wp-content/uploads/2025/01/photo_184@23-01-2025_10-45-34-768x512.jpg 768w, https://ptesc.tech/wp-content/uploads/2025/01/photo_184@23-01-2025_10-45-34.jpg 1200w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
<figure class="wp-block-image"><img width="1024" height="683" src="https://ptesc.tech/wp-content/uploads/2025/01/photo_185@23-01-2025_10-45-34-1024x683.jpg" class="attachment-large size-large" alt="" decoding="async" loading="lazy" srcset="https://ptesc.tech/wp-content/uploads/2025/01/photo_185@23-01-2025_10-45-34-1024x683.jpg 1024w, https://ptesc.tech/wp-content/uploads/2025/01/photo_185@23-01-2025_10-45-34-300x200.jpg 300w, https://ptesc.tech/wp-content/uploads/2025/01/photo_185@23-01-2025_10-45-34-768x512.jpg 768w, https://ptesc.tech/wp-content/uploads/2025/01/photo_185@23-01-2025_10-45-34.jpg 1200w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>

<br />
<br />
<span class="hashtag">#tip</span> <span class="hashtag">#reverse</span> <span class="hashtag">#idapython</span><br />
<a href="https://t.me/ptescalator" rel="noopener" target="_blank">@ptescalator</a>]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>How to fix CFG</title>
		<link>https://ptesc.tech/en/how-to-fix-cfg/</link>
		
		<dc:creator><![CDATA[global_author]]></dc:creator>
		<pubDate>Tue, 22 Oct 2024 17:18:28 +0000</pubDate>
				<category><![CDATA[Misc]]></category>
		<category><![CDATA[idapython]]></category>
		<category><![CDATA[reverse]]></category>
		<category><![CDATA[tips]]></category>
		<guid isPermaLink="false">http://localhost:8080/%d0%ba%d0%b0%d0%ba-%d0%bf%d0%be%d1%87%d0%b8%d0%bd%d0%b8%d1%82%d1%8c-cfg/</guid>

					<description><![CDATA[How to fix CFG 🔧 In the process of reverse engineering malware, we encounter cases where obfuscation hinders understanding the overall algorithm. One example is the creation of two consecutive opposite conditional jumps to a single point. S…]]></description>
										<content:encoded><![CDATA[<strong>How to fix CFG</strong> 🔧<br />
<br />
In the process of reverse engineering malware, we encounter cases where obfuscation hinders understanding the overall algorithm. One example is the creation of two consecutive opposite conditional jumps to a single point.<br />
<br />
<strong>Schematically it looks like this:</strong><br />
<br />
<pre class="wp-block-code"><span><code lang="yaml" class="hljs language-yaml language-yaml">
<span class="hljs-attr">start:</span>
    <span class="hljs-string">jnX</span> <span class="hljs-string">labelA</span>
    <span class="hljs-string">jX</span> <span class="hljs-string">labelA</span>
<span class="hljs-attr">labelA:</span>
    <span class="hljs-string">&lt;bytes&gt;</span>
</code></span></pre><br />
<br />
That is, when analyzing code, IDA first follows the <code>False</code> branch and creates code there, deferring the <code>True</code> branch for later. Upon encountering the <code>jnX</code> instruction, IDA creates code immediately after the current one.<br />
<br />
Next, upon encountering the opposite conditional jump, it again follows the <code>False</code> branch and creates code at the next address, building a garbage instruction after which disassembly is no longer possible. Then IDA returns to the deferred queue and takes the address from there, but the trouble is that code has already been created there, which means analysis terminates (<em>clearly visible in screenshot 1</em>).<br />
<br />
During live execution, regardless of the flag state, the jump to the operand will be taken, meaning execution will proceed <em>as in screenshot 2</em> if we correct the control flow.<br />
<br />
The difficulty in researching such shellcodes is that there can be many jumps and each time the analysis will stumble on them. You can try to fix it manually, but what if there are hundreds of such blocks?<br />
<br />
✍️ To handle this, let&#8217;s write a simple <code>IDAPython</code> script that will fix the problem automatically. The task is to find these blocks and patch them.<br />
<br />
First, let&#8217;s compile a list of opposite conditional jumps and put it into a function that will compare two consecutive instructions against the list:<br />
<br />
<pre class="wp-block-code"><span><code lang="python" class="hljs language-python language-python">
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">c_jumps</span><span class="hljs-params">(addr, n_addr)</span>:</span>
    ops = &#91;
        (<span class="hljs-string">"jz"</span>, <span class="hljs-string">"jnz"</span>),
        (<span class="hljs-string">"jnz"</span>, <span class="hljs-string">"jz"</span>),
        (<span class="hljs-string">"je"</span>, <span class="hljs-string">"jne"</span>),
        (<span class="hljs-string">"jne"</span>, <span class="hljs-string">"je"</span>),
        ...
    ]
    <span class="hljs-keyword">if</span> (ida_ua.print_insn_mnem(addr), ida_ua.print_insn_mnem(n_addr)) <span class="hljs-keyword">in</span> ops:
        <span class="hljs-keyword">return</span> <span class="hljs-literal">True</span>
    <span class="hljs-keyword">return</span> <span class="hljs-literal">False</span>
</code></span></pre><br />
<br />
We will sequentially iterate through each instruction until we find the ones we need or hit the limit.<br />
<br />
<pre class="wp-block-code"><span><code lang="python" class="hljs language-python language-python">
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">deobf</span><span class="hljs-params">(start, limit=BADADDR)</span>:</span>
    <span class="hljs-keyword">while</span> addr != BADADDR:
        n_addr = ida_search.find_code(addr, ida_search.SEARCH_DOWN)
        <span class="hljs-keyword">if</span> n_addr == BADADDR:
            <span class="hljs-keyword">break</span>
 
        <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> c_jumps(addr, n_addr):
            addr = n_addr
            <span class="hljs-keyword">continue</span>
</code></span></pre><br />
<br />
🧐 Using the <code>find_code</code> method from the <code>ida_search</code> module, we find the next address where code exists, and using the <code>c_jumps</code> function, we check whether the instructions at this and the next address are opposite jumps. Having found them, we need to check whether these jumps point to a single point (that is, whether their operands are equal):<br />
<br />
<pre class="wp-block-code"><span><code lang="plaintext" class="hljs language-plaintext language-plaintext">
o1 = get_operand_value(addr, 0)
o2 = get_operand_value(n_addr, 0)
 
if o1 != o2:
    addr = n_addr
    continue
 
insn = ida_ua.insn_t()
l1 = ida_ua.decode_insn(insn, addr)
l2 = ida_ua.decode_insn(insn, n_addr)
</code></span></pre><br />
<br />
Using <code>get_operand_value</code>, we obtain the operand values (for jX and jXX it is one) and check their equality. To determine the length of the segment that needs to be patched, using <code>decode_insn</code> from <code>ida_ua</code>, we find the instruction lengths.<br />
<br />
Then we fix the conditional jumps and ask IDA to analyze the new code. This is necessary so that further obfuscation blocks can be found:<br />
<br />
<pre class="wp-block-code"><span><code lang="plaintext" class="hljs language-plaintext language-plaintext">
after_addr = n_addr + l2
ida_bytes.patch_bytes(addr, bytes(&#91;0x90] * (l1 + l2 + 1)))

ida_auto.auto_wait()
ida_bytes.del_items(after_addr, ida_bytes.DELIT_EXPAND)
ida_auto.auto_wait()

ida_ua.create_insn(o1)
addr = o1
ida_auto.auto_wait()
</code></span></pre><br />
<br />
🗂 Using the <code>patch_bytes</code> method from <code>ida_bytes</code>, we patch the instructions, with <code>auto_wait from ida_auto</code> we ask IDA to analyze the new code, then, using <code>del_items</code>, we delete the garbage instructions created during the initial analysis and analyze again. Using <code>create_insn</code>, we create a valid instruction where the conditional jumps pointed, and re-analyze one last time.<br />
<br />
Thus, this script allows obtaining normal ASM code from obfuscated code, <em>as in screenshot 3</em>.<br />
<br />
Sometimes after running it, isolated unrecognized bytes remain, but they are easy to fix. From this code, you can create a function, decompile it, and analyze it (<em>as in screenshot 4</em>).<br />
<br />
Study IDAPython, write scripts. Happy reversing!

<figure class="wp-block-image"><img width="1024" height="1024" src="https://ptesc.tech/wp-content/uploads/2024/10/photo_98@22-10-2024_17-18-28-1024x1024.jpg" class="attachment-large size-large" alt="" decoding="async" loading="lazy" srcset="https://ptesc.tech/wp-content/uploads/2024/10/photo_98@22-10-2024_17-18-28-1024x1024.jpg 1024w, https://ptesc.tech/wp-content/uploads/2024/10/photo_98@22-10-2024_17-18-28-300x300.jpg 300w, https://ptesc.tech/wp-content/uploads/2024/10/photo_98@22-10-2024_17-18-28-150x150.jpg 150w, https://ptesc.tech/wp-content/uploads/2024/10/photo_98@22-10-2024_17-18-28-768x768.jpg 768w, https://ptesc.tech/wp-content/uploads/2024/10/photo_98@22-10-2024_17-18-28.jpg 1280w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
<figure class="wp-block-image"><img width="1024" height="1024" src="https://ptesc.tech/wp-content/uploads/2024/10/photo_99@22-10-2024_17-18-28-1024x1024.jpg" class="attachment-large size-large" alt="" decoding="async" loading="lazy" srcset="https://ptesc.tech/wp-content/uploads/2024/10/photo_99@22-10-2024_17-18-28-1024x1024.jpg 1024w, https://ptesc.tech/wp-content/uploads/2024/10/photo_99@22-10-2024_17-18-28-300x300.jpg 300w, https://ptesc.tech/wp-content/uploads/2024/10/photo_99@22-10-2024_17-18-28-150x150.jpg 150w, https://ptesc.tech/wp-content/uploads/2024/10/photo_99@22-10-2024_17-18-28-768x768.jpg 768w, https://ptesc.tech/wp-content/uploads/2024/10/photo_99@22-10-2024_17-18-28.jpg 1280w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
<figure class="wp-block-image"><img width="1024" height="1024" src="https://ptesc.tech/wp-content/uploads/2024/10/photo_100@22-10-2024_17-18-28-1024x1024.jpg" class="attachment-large size-large" alt="" decoding="async" loading="lazy" srcset="https://ptesc.tech/wp-content/uploads/2024/10/photo_100@22-10-2024_17-18-28-1024x1024.jpg 1024w, https://ptesc.tech/wp-content/uploads/2024/10/photo_100@22-10-2024_17-18-28-300x300.jpg 300w, https://ptesc.tech/wp-content/uploads/2024/10/photo_100@22-10-2024_17-18-28-150x150.jpg 150w, https://ptesc.tech/wp-content/uploads/2024/10/photo_100@22-10-2024_17-18-28-768x768.jpg 768w, https://ptesc.tech/wp-content/uploads/2024/10/photo_100@22-10-2024_17-18-28.jpg 1280w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>

<br />
<br />
<span class="hashtag">#tip</span> <span class="hashtag">#reverse</span> <span class="hashtag">#idapython</span><br />
<a href="https://t.me/ptescalator" rel="noopener" target="_blank">@ptescalator</a>]]></content:encoded>
					
		
		
			</item>
	</channel>
</rss>
