<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by CrackMyLife on Medium]]></title>
        <description><![CDATA[Stories by CrackMyLife on Medium]]></description>
        <link>https://medium.com/@crackmylife?source=rss-4150b5bc5761------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*IMe7hQSds6j_CXmn6V6npg.jpeg</url>
            <title>Stories by CrackMyLife on Medium</title>
            <link>https://medium.com/@crackmylife?source=rss-4150b5bc5761------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 05:28:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@crackmylife/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Reversing Android Init Array Section]]></title>
            <link>https://crackmylife.medium.com/reversing-android-init-array-section-3a8fe4e6df37?source=rss-4150b5bc5761------2</link>
            <guid isPermaLink="false">https://medium.com/p/3a8fe4e6df37</guid>
            <category><![CDATA[android-security]]></category>
            <category><![CDATA[malware]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[reverse-engineering]]></category>
            <category><![CDATA[malware-analysis]]></category>
            <dc:creator><![CDATA[CrackMyLife]]></dc:creator>
            <pubDate>Sat, 11 Apr 2026 13:42:40 GMT</pubDate>
            <atom:updated>2026-04-11T13:42:40.743Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*BH-McCuw6LzdfeCKeWV7RA.png" /></figure><h3>What is init_array</h3><p>The name INIT_0 might sound familiar if you are a casual Ghidra reverser and analyze .so binaries frequently. You might also have encountered FINI_0 which is more commonly seen in binaries.</p><p>INIT_0 or the common name .init_array is a section that contains an array of function pointers in ELF structure. These functions are designed to be executed automatically by the system when a shared library .so is loaded into memory. Rather than being called directly from Java, they are invoked by the dynamic linker as part of the loading process.</p><h4>Init &amp; Init Array Differences</h4><p>init and init array are not exactly the same as you can see in the <a href="https://android.googlesource.com/platform/bionic/+/android-4.2_r1/linker/README.TXT">documentation</a>, which is a <strong>low-level internal documentation file</strong> from Android’s core system. <strong>DT_INIT</strong> specifies a single function address that should be executed when the binary is loaded. In contrast, <strong>DT_INIT_ARRAY</strong> refers to a list of function pointers that are invoked sequentially to handle initialization. Some implementations may include null entries, which are skipped. and are skipped. This array is typically located in the .init_array section.</p><p>The following table summarizes their key differences and practical behavior:</p><pre>Feature           | DT_INIT                | DT_INIT_ARRAY<br>-------------------------------------------------------------<br>Execution order   | Runs first             | Runs after DT_INIT, in order<br>Function capacity | Single function        | Multiple functions<br>C++ constructor   | Weak                   | Full support<br>Modernity         | Legacy                 | Modern standard<br>Practical behavior| Defined by _init()     | Multiple __attribute__((constructor)) functions</pre><h4>Preinit Array Section</h4><p>Besides .init and .init_array, it is also important to mention .preinit_array. The .preinit_array section (DT_PREINIT_ARRAY) is meant for functions that run before all other initialization routines. However, on Android, it <strong>is ignored for shared libraries on Android (</strong><strong>.so)</strong>. Although the section may exist in the compiled library, the linker ignores it, so the functions are never called. This is because preinit arrays are only valid for main executables, not dynamically loaded libraries.</p><h4>Fini &amp; Fini Array Sections</h4><p>Eventually, there are .fini and .fini_array sections that handle finalization which is the opposite of the initialization process. <strong>DT_FINI</strong> holds the address of a single cleanup function that is executed when the binary is unloaded or the process exits. In comparison, <strong>DT_FINI_ARRAY</strong> points to a sequence of function addresses used for finalization. These functions are called in reverse order, and the array is typically located in the .fini_array section.</p><h3>Where it Sits in the Loading Lifecycle</h3><p>In the Android native loading process, execution begins when the Zygote forks a new application process, inheriting the initialized ART runtime. Once a native library is requested, the Bionic linker loads the .so file into memory, resolves relocations, and performs thread-local storage (TLS) setup.</p><p>At this stage, before any developer-controlled entry points such as JNI_OnLoad are reached, the linker executes initialization routines. First, DT_INIT (if present) is invoked, followed by each function pointer in .init_array. This means .init_array runs <em>very early</em> in the lifecycle—before most application logic and before typical instrumentation hooks are established.</p><h3>How it Works (Execution Flow)</h3><p>To better understand how these components interact at runtime, the following diagram illustrates the initialization flow in an Android native context:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*FanJpl-t2So76ozjW4QW7Q.png" /></figure><p>After the Zygote spawns a new process and the ART runtime is initialized, the Bionic linker loads the target shared library. It then resolves relocations and prepares the execution environment. Although .preinit_array may exist, it is ignored for shared libraries on Android. The linker proceeds to execute .init_array, iterating through each function pointer sequentially. Each referenced function is called, typically initializing global objects or internal states, before execution continues to higher-level entry points such as JNI_OnLoad.</p><h3>Why Malware Developers Prefer Init Array Section</h3><p>First, it enables <strong>pre-JNI execution</strong>, meaning malicious code can run before JNI_OnLoad or any Java-layer logic is triggered. This allows malware to perform anti-analysis checks, unpack payloads, or establish persistence before analysts typically set breakpoints.</p><p>Second, execution through .init_array is <strong>implicit and linker-driven</strong>. There are no explicit function calls in the code referencing these routines, making them less visible during static analysis. Many beginner-level analyses overlook these sections entirely.</p><p>Finally, .init_array aids in <strong>static analysis evasion</strong>. Since the functions are stored as raw pointers in ELF metadata rather than clearly labeled symbols, they can host small, obfuscated routines that are harder to detect. Combined with techniques like encryption or control-flow obfuscation, this makes early-stage behavior significantly more difficult to trace.</p><h3>How to Detect</h3><p>Detecting suspicious use of .init_array requires both static and dynamic analysis awareness.</p><p>Tools like Ghidra or IDA can reveal .init_array entries as an array of function pointers. These entries should be inspected carefully, especially if they point to small, non-trivial functions that do not resemble standard constructors. In IDA, symbols such as __init_array_start and __init_array_end can help locate the region.</p><p>During dynamic analysis, setting breakpoints before JNI_OnLoad may help identify anti-analysis behavior. If execution reaches unexpected code prior to this function, it is highly likely that .init_array is being used. Tracing execution from the moment the library is loaded can reveal hidden initialization routines.</p><h3>Reversing the .init_array — A Practical Demo</h3><p>To learn more about it and practice, <a href="https://github.com/eemreTurkyilmaz/Android-Reverse-Lab-">here</a> is a demo of an init_array implementation that secures the application with anti-analysis techniques such as frida, root, and emulator detection. It is a bit different from a typical native hooking, but we still have to analyze .so file and find the <strong>.init_array</strong> section which hold the techniques.</p><p>The App does not allow user to open it in a lab environment and if tried, <strong>raise(SIGSEGV)</strong> causes crash of application. Does not matter clicked or called by frida.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/267/1*waPZ5s_f2TniT8blXm6I1A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/542/1*6OjncEJivbihn76ZpHJdHg.png" /></figure><p>Logcat output also shows detection performed by program for root authority and Frida-related information by scanning memory maps <strong>/proc/self/maps</strong>. This hints the application inspects its runtime environment and aimed to prevent dynamic debugging and reverse engineering.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/778/1*oLX29YCUbOIWDD5jlsgFbg.png" /></figure><p>From <strong>JADX</strong> view, Main activity is simple; Program loads innit library which is <strong>libinnit</strong> the name always takes the lib prefix, and returns a string from JNI named <strong>stringFromJNI()</strong> to print it on screen when Java layer came to run. That is actually important because there is no other function than <strong>stringFromJNI()</strong> specified at MainActivity, which means .init_array functions do not need to be called to be called from Java layer.</p><pre>/* loaded from: classes.dex */<br>public class MainActivity extends AppCompatActivity {<br>    public native String stringFromJNI();<br>    static {<br>        System.loadLibrary(&quot;innit&quot;);<br>    }<br>    /* JADX INFO: Access modifiers changed from: protected */<br>    @Override // androidx.fragment.app.FragmentActivity, androidx.activity.ComponentActivity, androidx.core.app.ComponentActivity, android.app.Activity<br>    public void onCreate(Bundle bundle) {<br>        super.onCreate(bundle);<br>        setContentView(R.layout.activity_main);<br>        TextView textView = (TextView) findViewById(R.id.textView);<br>        String stringFromJNI = stringFromJNI();<br>        Log.d(&quot;INIT&quot;, stringFromJNI);<br>        textView.setText(stringFromJNI);<br>    }<br>}</pre><p>Ghidra’s memory map tool shows sections of file, using it, finding where <strong>.init_array</strong> section is located is much easier. <strong>0x0001217c</strong> is the exact location of first function initialized and can be copied by current column from memory map.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/263/1*EIt5MDCxe_OfXdA5Hlj6GQ.png" /></figure><p>Finally get on .init_array and first thing to see is address of <strong>init_anti_analysis</strong> function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*A3Ntmb1UTLwDjtWjrY8fAA.png" /></figure><p><strong>init_anti_analysis</strong> function is actually a function that uses several internal functions but the Android native optimizer built it as a single function, still it is better to go one by one.</p><p>This snippet scans the process memory map (/proc/self/maps) to detect signs of dynamic instrumentation such as Frida. It reads each mapped memory region line by line and searches for keywords like &quot;memfd&quot;, &quot;jit-cache&quot;, &quot;tmp&quot;, or &quot;deleted&quot;, which are related to Frida&#39;s injected artifacts. If these patterns are found, it logs a detection message and deliberately crashes the process using raise() to disrupt runtime hooking and analysis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/1*FYSiU_tkO1x3SwKeFsTh6A.png" /></figure><p>To bypass this kind of detection, a <strong>Frida script</strong> can hook the same function used by the target. In this situation, it is fgets and sanitize its output before the application inspects it. Using Interceptor.attach, the script intercepts every call to fgets and inspects the returned line from /proc/self/maps. If the line contains suspicious keywords such as &quot;memfd&quot;, &quot;jit&quot;, or &quot;deleted&quot;, it overwrites the buffer with an empty string. As a result, the anti-analysis check never sees the indicators it is looking for, effectively hiding Frida’s presence. Only side effect of this approach is <strong>mass data output and interception</strong>. Since fgets is called repeatedly while reading the entire memory map, the hook processes a large number of lines in real time.</p><pre>Interceptor.attach(Module.findExportByName(null, &quot;fgets&quot;), {<br>    onLeave: function (retval) {<br><br>        if (retval.isNull()) return;<br><br>        var line = Memory.readUtf8String(retval);<br><br>        if (line.includes(&quot;memfd&quot;) ||<br>            line.includes(&quot;jit&quot;) ||<br>            line.includes(&quot;deleted&quot;)) {<br><br>            console.log(&quot;[BYPASS] Cleaning suspicious maps entry&quot;);<br><br>            Memory.writeUtf8String(retval, &quot;&quot;);<br>        }<br>    }<br>});</pre><p>The next part focuses on rooted or emulated devices in addition to checks related to runtime debugging. It typically inspects system properties, file paths, or binaries associated with rooted environments (such as su, busybox, or modified system directories). By querying these artifacts, the application attempts to determine whether it is running on a compromised or emulated device. If any indicator is found, the application may alter its behavior or terminate execution, making it harder to observe its full functionality.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/505/1*7bJpjQ2jLY6eEYMIs1n8hw.png" /></figure><p>To bypass these root detection checks, a <strong>Frida script</strong> hooks the underlying libc functions used by the application namely (access &amp; system) and manipulates their behavior at runtime. Instead of letting the app query the real filesystem or execute shell commands, the hook inspects the arguments passed to these functions and selectively fakes the results.</p><p>In the access hook, the script reads the file path being checked and looks for indicators such as &quot;su&quot; or &quot;magisk&quot;. If a match is found, it flags the call and forces the return value to -1, which simulates a “file not found” condition. This effectively hides the presence of root-related binaries from the application.</p><p>Similarly, the system hook targets command execution, specifically patterns like &quot;which su&quot; that are commonly used to locate the su binary. When such a command is detected, the script overrides the return value with a non-zero result, indicating failure. As a result, the application believes the command did not succeed and assumes the device is not rooted.</p><p>Together, these hooks demonstrate how intercepting low-level libc APIs provides a powerful and generic bypass strategy. Rather than patching each individual check, this allows root detection logic to be neutralized in a scalable and reusable way.</p><pre>Interceptor.attach(Module.findExportByName(null, &quot;access&quot;), {<br>    onEnter: function (args) {<br>        var path = Memory.readUtf8String(args[0]);<br><br>        if (path.includes(&quot;su&quot;) || path.includes(&quot;magisk&quot;)) {<br>            console.log(&quot;[BYPASS] Hiding:&quot;, path);<br>            this.shouldFake = true;<br>        }<br>    },<br>    onLeave: function (retval) {<br>        if (this.shouldFake) {<br>            retval.replace(-1);<br>        }<br>    }<br>});<br><br><br>Interceptor.attach(Module.findExportByName(null, &quot;system&quot;), {<br>    onEnter: function (args) {<br>        var cmd = Memory.readUtf8String(args[0]);<br><br>        if (cmd.includes(&quot;which su&quot;)) {<br>            console.log(&quot;[BYPASS] Blocking command:&quot;, cmd);<br>            this.shouldFake = true;<br>        }<br>    },<br>    onLeave: function (retval) {<br>        if (this.shouldFake) {<br>            retval.replace(1); // non-zero → command failed<br>        }<br>    }<br>});</pre><p>The last part is so messy, it is better to simplify pseudo-C code to understand better. This final part shows a more <strong>aggressive emulator detection routine</strong> implemented at the native level. The function repeatedly builds a command (via FUN_00011000) and executes it using popen, then reads the output with fgets. Each result is scanned for emulator-related strings such as &quot;Genymotion&quot;, &quot;generic&quot;, &quot;vbox86&quot;, and even specific characters, which are commonly found in system properties of virtual devices.</p><p>The repeated pattern is intentional, it performs multiple checks against different system properties or commands, making the detection more resilient and harder to bypass with a single patch. If any of these indicators are found, execution jumps to a detection block that logs a message and immediately terminates the process using raise(0xb) (SIGSEGV), acting as a deliberate crash to stop analysis.</p><pre>cmd = build_command();   // FUN_00011000(local_94)<br><br>output = run_command(cmd);   // popen + fgets + pclose<br><br>if (output contains &quot;Genymotion&quot;)<br>    detect_emulator();<br><br>repeat {<br>    cmd = build_command();<br>    output = run_command(cmd);<br><br>    if (output contains &quot;Genymotion&quot;) detect_emulator();<br>    if (output contains &quot;generic&quot;)    detect_emulator();<br>    if (output contains &quot;vbox86&quot;)     detect_emulator();<br>    if (output contains &#39;1&#39;)          detect_emulator();<br>    if (output contains &quot;generic&quot;)    detect_emulator();<br>    if (output contains &quot;Android SDK&quot;)detect_emulator();<br><br>} until all checks done;<br><br>print(&quot;Clean environment&quot;);</pre><p>Finally, the Frida script hooks the popen function, which is responsible for executing system commands and returning their output. Instead of modifying the result after execution, this approach <strong>alters the command itself before it is run</strong>, giving full control over what the application will receive.</p><p>When popen is called, the script reads the command string and checks for specific system property queries such as &quot;ro.product.manufacturer&quot;, &quot;ro.hardware&quot;, and &quot;ro.kernel.qemu&quot;. These are commonly used to identify emulators like Genymotion or QEMU-based environments. If a match is found, the script replaces the original command with a harmless echo statement that returns realistic values (e.g., &quot;samsung&quot;, &quot;exynos&quot;, or &quot;0&quot;). As a result, when the application reads the output via fgets, it receives clean, non-suspicious data, effectively bypassing all subsequent string checks (strstr).</p><pre>Interceptor.attach(Module.findExportByName(null, &quot;popen&quot;), {<br>    onEnter: function (args) {<br><br>        var cmd = Memory.readUtf8String(args[0]);<br><br>        if (cmd.includes(&quot;ro.product.manufacturer&quot;)) {<br>            Memory.writeUtf8String(args[0], &quot;echo samsung&quot;);<br>        }<br>        else if (cmd.includes(&quot;ro.hardware&quot;)) {<br>            Memory.writeUtf8String(args[0], &quot;echo exynos&quot;);<br>        }<br>        else if (cmd.includes(&quot;ro.kernel.qemu&quot;)) {<br>            Memory.writeUtf8String(args[0], &quot;echo 0&quot;);<br>        }<br>    }<br>});</pre><p>As an alternative to all previous bypass techniques, a much simpler and more generic approach is to <strong>neutralize the crash mechanism itself</strong>. Instead of hiding artifacts or modifying checks, this method hooks the raise function, which is used by the application to deliberately terminate execution when a detection is triggered.</p><p>In this script, Interceptor.replace fully overrides the libc raise implementation. When the app attempts to call raise(SIGSEGV) (signal 11), the hook intercepts it, logs a bypass message, and simply returns 0 without actually sending the signal. This prevents the forced crash, allowing the application to continue running even after detection logic is triggered.</p><pre>function bypassRaise() {<br><br>    var raisePtr = Module.findExportByName(null, &quot;raise&quot;);<br><br>    if (raisePtr) {<br>        console.log(&quot;[+] raise found at&quot;, raisePtr);<br><br>        Interceptor.replace(raisePtr, new NativeCallback(function (sig) {<br>            if (sig === 11) { // SIGSEGV<br>                console.log(&quot;[BYPASS] raise(SIGSEGV) blocked&quot;);<br>                return 0;<br>            }<br>            return 0;<br>        }, &#39;int&#39;, [&#39;int&#39;]));<br><br>    } else {<br>        console.log(&quot;[-] raise not found&quot;);<br>    }<br>}<br>setImmediate(bypassRaise);</pre><p>Understanding .init_array changes how you approach native analysis. Instead of starting from JNI_OnLoad or exported functions, you begin from the actual first executed instructions.</p><p>Once this mindset is adopted, many “mysterious” behaviors, early crashes, anti-debugging triggers, or hidden checks become explainable. More importantly, they become bypassable.</p><p>In reverse engineering, knowing <em>where execution truly begins</em> is often more important than knowing <em>what the code does</em>. And .init_array is one of the places where that truth is revealed.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3a8fe4e6df37" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android Java Native Interface]]></title>
            <link>https://crackmylife.medium.com/android-java-native-interface-ae9c16ecfc31?source=rss-4150b5bc5761------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae9c16ecfc31</guid>
            <category><![CDATA[android-security]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[android-reversing]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[reverse-engineering]]></category>
            <dc:creator><![CDATA[CrackMyLife]]></dc:creator>
            <pubDate>Sat, 11 Apr 2026 13:37:48 GMT</pubDate>
            <atom:updated>2026-04-11T13:37:48.480Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*eFHh3cQrZ9x4UKxTAeqi2Q.jpeg" /></figure><p>Android applications run on layers, and understanding what lies beneath the Java surface is essential for security researchers. In this article, we will explore how JNI works, why malware developers prefer native code, and how to hook native functions using Frida through a hands-on demo.</p><h3>What is Android Native</h3><p>Android applications commonly are written in high-level languages such as Java or Kotlin, which can be a critical issue for performance and security. However, thanks to the <strong>Java Native Interface</strong>, developers can leverage the <strong>Android NDK</strong> for performance-critical sections using languages like C and C++.</p><p>Allowing native code provides developers <strong>a comprehensive area</strong> in situations such as games, multimedia applications, and other resource-intensive tasks where close-to-the-metal performance is crucial.</p><p>The diagram below illustrates how these layers interact at runtime:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*MIKXirx4DdH30k5L_Z4Jgw.jpeg" /></figure><h3>Why Malware Developers Prefer Native</h3><p>Despite its strong positive impact from a performance perspective, it dramatically complicates <strong>the analysis</strong> because bytecode and native code need different abstractions and analysis algorithms, and they thus pose different challenges and limitations. Consequently, these difficulties are often abused to hide malicious payloads.</p><p>Native components are often employed for obfuscation by dynamically loading and executing both <strong>Java code and native code</strong>. In particular, malware goes native to dynamically load and invoke methods of the Android framework that require <strong>dangerous permissions</strong> to get the user’s sensitive information <strong>indirectly</strong>. This creates leaps between these two different <strong>code environments</strong>, consequently making the analysis particularly difficult. Moreover, <strong>malware may exploit</strong> JNI mechanisms to load malicious or harmless code at will, depending on <strong>environment checks</strong>.</p><h3>What is .so file</h3><p>If you haven’t analysed a native binary, you might not know about a .so (Shared Object) file. Indeed, it is common in Unix-based operating systems like Ubuntu, Debian, and Android. A shared object file is a native library <strong>that serves as a dynamically linked library</strong> and <strong>is compiled from C or C++ code</strong>. This functionality <strong>is comparable to</strong> the Windows <strong>DLL (Dynamic Link Library)</strong> system. <strong>Shared object files are essential</strong> for running performance-intensive or low-level operations within an Android app.</p><p>Shared object files are not compiled directly into program binaries; instead, they are designed to be loaded at runtime. This benefits applications significantly by making them smaller, easier to maintain, and more efficient because they share common functionality.</p><p>At runtime, the program loads the library using functions such as System.loadLibrary(). In Android applications, native libraries are packaged inside the APK under the lib/ directory, separated by CPU architecture such as armeabi-v7a, arm64-v8a, or x86.</p><h3>Into the Native — A Practical Demo</h3><p><a href="https://github.com/eemreTurkyilmaz/Android-Reverse-Lab-">Here</a> I prepared a demo of android native hooking for who wants to learn or practice their skills. You can access demo from my github account and for first timers I solved the demo. Here it is;</p><p>First of all this is a login page-like application where you try to find correct password, basically it is a crackme. However, program is secured with root access control and a encrypted password.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/352/1*HuZqjrO9lbotMzP5Pa2Pmg.png" /></figure><p>Before hooking or diving native, you have to approach to the program like any other program and understand the logic behind it. So, first thing to do is checking static java codes to understand what program does and how it works.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/813/1*FoGquscy3jcgD15XGfSVTg.png" /></figure><p>As I mentioned before System.loadLibrary() helps program to load native-lib at runtime, so it can call above functions such isDeviceRooted. Also, you can see these functions specifically defined as native functions and some of them even taking parameters to use in native from java.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MEj9_Pv5NzW_YfcpAoV03A.png" /></figure><p>isDeviceRooted function is a boolean type function as we see, it returns true or false which is controlled in here and then compareStrings function takes two parameters, first our input and then generateSecret to check our answer. MainActivity finishes here, to go further native library must be analysed. Shared object file is located under /lib directory in APK so first decompile APK with apktool to extract .so file and use IDA or Ghidra to analyse. I prefer Ghidra.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/445/1*ux19m7Oecdn6ZrWV6fIVkg.png" /></figure><p>isDeviceRooted basically checks directories for /su or Superuser.apk, and returns true. To bypass root check, return value can be hooked and set false. To hook a native function, first you need to find address of that function which can be obtained with Module.findExportByName() and library name. Later you attach the function using Interceptor.attach().</p><pre>setTimeout(function() {<br><br>    var lib = &quot;libnative-lib.so&quot;;<br><br>    var addr = Module.findExportByName(lib,<br>        &quot;Java_com_example_innative_MainActivity_isDeviceRooted&quot;);<br><br>    console.log(&quot;[+] Root check address: &quot; + addr);<br><br>    Interceptor.attach(addr, {<br><br>        onEnter: function(args) {<br>            console.log(&quot;[+] Root check called&quot;);<br>        },<br><br>        onLeave: function(retval) {<br>            console.log(&quot;[+] Original return: &quot; + retval);<br><br>            retval.replace(0); // always false<br><br>            console.log(&quot;[+] Root bypassed&quot;);<br>        }<br>    });<br><br>}, 3000);</pre><p>Above there is an example of how to implement this frida script. I set 3 second delay to wait library load, it does not have to be long but guarantees the hook. retval means the return value so replacing it with zero sets function to false.</p><p>Root control is bypassed, and now to find password is up to your imagination. generateSecret functions return value can be hooked or compareStrings function can be manipulated. A few more solving script included in my github account, but for now I will continue with hooking arguments of compareStrings function.</p><p>As you remember, this function took two parameters and one of them includes password. These arguments can be hooked or manipulated by changing with each other, even a new password can be set. Let’s hook argument includes password.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*PTIIh2lmZv1M2E3YBe2Zlg.png" /></figure><p>If you are working with Android native code, the first parameter is always a pointer to the <strong>JNI environment</strong>, and the second parameter is a <strong>pointer to the current object</strong> on which the method was called. Only after these do we reach the actual function parameters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/359/1*Qdx49oFN18JP65lYkGkhLQ.png" /></figure><p>Also, if you look at pushed parameters EDI &amp; ESI most likely parameters we are looking for, and in java analysis we saw user input pushed before password, so ESI must be our password.</p><pre>        var cmpAddr = Module.findExportByName(lib,<br>        &quot;Java_com_example_innative_MainActivity_compareStrings&quot;<br>    );<br><br>    console.log(&quot;[+] compareStrings address: &quot; + cmpAddr);<br><br>    Interceptor.attach(cmpAddr, {<br><br>        onEnter: function(args) {<br><br>            var env = Java.vm.getEnv();<br><br>            var secretStr = env.getStringUtfChars(args[3], null).readCString();<br><br>            console.log(&quot;[+] Secret: &quot; + secretStr);<br>        }<br>    });</pre><p>var env = Java.vm.getEnv(); retrieves the <strong>JNI environment</strong>, we need this to call GetStringUTFChars. args[3] is a <strong>JNI </strong><strong>jstring object</strong>, not a normal string, and GetStringUTFChars converts it into a <strong>pointer to a UTF-8 C string</strong>. Using the same logic, password can be changed.</p><p>JNI is a powerful bridge — and like any bridge, it can be crossed in both directions. Understanding how native libraries are loaded and how arguments flow through the JNI environment gives you a solid foundation for analysing real-world Android malware. Native analysis is a deep rabbit hole, but once you understand the JNI layer, a lot of what malware tries to hide becomes visible.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae9c16ecfc31" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Droids WriteUp PicoCTF]]></title>
            <link>https://crackmylife.medium.com/droids-writeup-picoctf-40178e8fff54?source=rss-4150b5bc5761------2</link>
            <guid isPermaLink="false">https://medium.com/p/40178e8fff54</guid>
            <dc:creator><![CDATA[CrackMyLife]]></dc:creator>
            <pubDate>Wed, 12 Jul 2023 23:28:18 GMT</pubDate>
            <atom:updated>2023-07-12T23:39:07.021Z</atom:updated>
            <content:encoded><![CDATA[<p>I newly entered the anroid analysis world and I thought what can be better than ctf for practicing my frida scripts. I like picoCTF questions so I decided to solve droid android series from picoCTF. Let’s start.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*O1vuEcio4axgpD34nFZXbA.jpeg" /></figure><h3>Zero.apk</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/544/1*DBW-Ez-NMYpscc4sanAEzg.png" /></figure><p>First of all, a quick scan to app would be good. All we have a input and a button. Now we reverse the code on Jadx.</p><figure><img alt="Jadx screen in MainActivity" src="https://cdn-images-1.medium.com/max/900/1*5gTCiewJ-QRdAPQTK5xwww.png" /></figure><p>System.loadlibrary() method loads a library named <strong>“hellojni” </strong>which probably has flag method inside of it. There is a getFlag method called under buttonClick(). Probably we will get flag from it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/485/1*HTMNDLoYFyxHiDzbz9Cnfg.png" /></figure><p>There is a native method named paprika which is from<strong> “hellojni”. </strong>So, if we hook the paprika we find the flag. There is a frida script taken from jadx.</p><pre>Java.perform(function() {<br><br>    let FlagstaffHill = Java.use(&quot;com.hellocmu.picoctf.FlagstaffHill&quot;);<br>    FlagstaffHill[&quot;paprika&quot;].implementation = function (str) {<br>        console.log(`FlagstaffHill.paprika is called: str=${str}`);<br>        let result = this[&quot;paprika&quot;](str);<br>        console.log(`FlagstaffHill.paprika result=${result}`);<br>        return result;<br>    };<br>});</pre><p>This frida scirpt will hook paprika method to get flag.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oNOWfTy_fiOyDKmZ5lfeXw.png" /></figure><p>Here it is. Still “Not today” is prints, but we got the flag.</p><p>Flag : picoCTF{a.moose.once.bit.my.sister}</p><h3>One.apk</h3><p>Apps similar, so this time I will look jadx instantly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/468/1*7FZMgnMvPjI-DgS8BJWLMg.png" /></figure><p>I see a password value, maybe I can take password by breaking <em>“Context cxt”</em> value.</p><pre>Java.perform(function () {<br>    <br>    var FlagstaffHill = Java.use(&#39;com.hellocmu.picoctf.FlagstaffHill&#39;);<br>    FlagstaffHill.getFlag.implementation = function (input, ctx) {<br>        var passwordResId = ctx.getResources().getIdentifier(&#39;password&#39;, &#39;string&#39;, ctx.getPackageName());<br>        var password = ctx.getString(passwordResId);<br>        console.log(&#39;[*] Hooked FlagstaffHill.getFlag()&#39;);<br>        console.log(&#39;[*] Password:&#39;, password);<br>        // Call the original method<br>        var result = this.getFlag(input, ctx);<br>        return result;<br>    };<br>});</pre><p>Password value coming from cxt.getString() method, so I use it to hook password and print it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*f3DJChkBZuBbZxwxtVR4xg.png" /></figure><p>When I press button frida gave me the correct password. {opossum}</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/541/1*2xaHLrpuAESq5Ww3HFpi7Q.png" /></figure><p>picoCTF{pining.for.the.fjords} let’s move.</p><h3>Two.apk</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/704/1*3fvajwVVNC8rXkViTFnafQ.png" /></figure><p>Oh, this will be easier than others because as you know jadx is good at bringing source code back and here is a password calculation, so I just need to run this java code.</p><pre>public class CTF{<br>     public static void main(String []args){<br>        String[] witches = {&quot;weatherwax&quot;, &quot;ogg&quot;, &quot;garlick&quot;, &quot;nitt&quot;, &quot;aching&quot;, &quot;dismass&quot;};<br>        int second = 3 - 3;<br>        int third = (3 / 3) + second;<br>        int fourth = (third + third) - second;<br>        int fifth = 3 + fourth;<br>        int sixth = (fifth + second) - third;<br>        String password = &quot;&quot;.concat(witches[fifth]).concat(&quot;.&quot;).concat(witches[third]).concat(&quot;.&quot;).concat(witches[second]).concat(&quot;.&quot;).concat(witches[sixth]).concat(&quot;.&quot;).concat(witches[3]).concat(&quot;.&quot;).concat(witches[fourth]);<br><br>        System.out.println(password);<br>     }<br>}</pre><p>I copied all calculation code and added a print function to print password.</p><p>Password : dismass.ogg.weatherwax.aching.nitt.garlick</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/541/1*VT09sibPXKrD3KGxgY3kZw.png" /></figure><p>It is a weird password to choose, but hey it worked.</p><p>picoCTF{what.is.your.favourite.colour}</p><h3>Three.apk</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/454/1*vxoPiZDnfw1AurII8yMGxA.png" /></figure><p>My Flag is in “cilantro”. nope returns “don’t wanna”, but it would be good if it return cilantro :(</p><p>WAIT A MINUTE… it can return cilantro.</p><pre>Java.perform(function () {<br>    <br>    let FlagstaffHill = Java.use(&quot;com.hellocmu.picoctf.FlagstaffHill&quot;);<br>    FlagstaffHill[&quot;nope&quot;].implementation = function (str) {<br>        console.log(`FlagstaffHill.nope is called: input=${str}`);<br>        let result = this[&quot;cilantro&quot;](str);<br>        console.log(`FlagstaffHill.nope result=${result}`);<br>        return result;<br>    };<br>});</pre><p>This code is similer to first example, it change return value to flag and print it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/543/1*Xec-fRngDDY12ylsPzsteg.png" /></figure><p>And with this our flag is : picoCTF{tis.but.a.scratch}</p><h3>Four.apk</h3><p>This is our last app let’s finish it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/898/1*Fo3wbDrDNC1zdIA9LdGf3w.png" /></figure><p>As the third application it has a password algorithm I thought it would be harder. Anyway I will just run this code.</p><pre>public class CTF{<br>     public static void main(String []args){<br>        StringBuilder ace = new StringBuilder(&quot;aaa&quot;);<br>        StringBuilder jack = new StringBuilder(&quot;aaa&quot;);<br>        StringBuilder queen = new StringBuilder(&quot;aaa&quot;);<br>        StringBuilder king = new StringBuilder(&quot;aaa&quot;);<br>        ace.setCharAt(0, (char) (ace.charAt(0) + 4));<br>        ace.setCharAt(1, (char) (ace.charAt(1) + 19));<br>        ace.setCharAt(2, (char) (ace.charAt(2) + 18));<br>        jack.setCharAt(0, (char) (jack.charAt(0) + 7));<br>        jack.setCharAt(1, (char) (jack.charAt(1) + 0));<br>        jack.setCharAt(2, (char) (jack.charAt(2) + 1));<br>        queen.setCharAt(0, (char) (queen.charAt(0) + 0));<br>        queen.setCharAt(1, (char) (queen.charAt(1) + 11));<br>        queen.setCharAt(2, (char) (queen.charAt(2) + 15));<br>        king.setCharAt(0, (char) (king.charAt(0) + 14));<br>        king.setCharAt(1, (char) (king.charAt(1) + 20));<br>        king.setCharAt(2, (char) (king.charAt(2) + 15));<br>        String password = &quot;&quot;.concat(queen.toString()).concat(jack.toString()).concat(ace.toString()).concat(king.toString());<br><br>        System.out.println(password);<br>     }<br>}</pre><p>password : alphabetsoup</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*dk1T9Es68BYJcq668SGagA.png" /></figure><p>Oh wait, it didn’t give the flag. What should I call? Oh, I see…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/371/1*o6df33Vr8HnBciwXho9hdg.png" /></figure><p>it return “call it” when true not the flag method, so I have to change this string with cardamom().</p><pre>Java.perform(function() {<br>    let FlagstaffHill = Java.use(&quot;com.hellocmu.picoctf.FlagstaffHill&quot;);<br>    FlagstaffHill[&quot;getFlag&quot;].implementation = function (input, ctx) {<br>        console.log(`FlagstaffHill.getFlag is called: input=${input}, ctx=${ctx}`);<br>        let result = FlagstaffHill.cardamom(input);<br>        console.log(`FlagstaffHill.getFlag result=${result}`);<br>        return result;<br>    };<br>});</pre><p>With this frida script I changed return value from “call it” to flag method. Let’s chech if it works properly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/539/1*Oite3H0ygMHKhaKffmXqvg.png" /></figure><p>picoCTF{not.particularly.silly}</p><p>Yep it worked. This was the last. See you in the next subjects.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=40178e8fff54" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>