<?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 Amir Mohamadi on Medium]]></title>
        <description><![CDATA[Stories by Amir Mohamadi on Medium]]></description>
        <link>https://medium.com/@amiremohamadi?source=rss-8117873f78f6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*m6_rqzao_gvBgXXa-KH5YA.png</url>
            <title>Stories by Amir Mohamadi on Medium</title>
            <link>https://medium.com/@amiremohamadi?source=rss-8117873f78f6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 18:51:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@amiremohamadi/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[CyberSpace CTF 2024 — sole]]></title>
            <link>https://medium.com/@amiremohamadi/cyberspace-ctf-2024-sole-fc58c0566576?source=rss-8117873f78f6------2</link>
            <guid isPermaLink="false">https://medium.com/p/fc58c0566576</guid>
            <category><![CDATA[hacking]]></category>
            <category><![CDATA[ctf]]></category>
            <category><![CDATA[ctf-writeup]]></category>
            <category><![CDATA[reverse-engineering]]></category>
            <dc:creator><![CDATA[Amir Mohamadi]]></dc:creator>
            <pubDate>Sun, 01 Sep 2024 22:29:10 GMT</pubDate>
            <atom:updated>2024-09-02T10:42:01.831Z</atom:updated>
            <content:encoded><![CDATA[<h3>CyberSpace CTF 2024 — sole</h3><p>Let’s take a look at the problem:</p><blockquote>Math professors struggled with this System of linear equations for years, can you solve it?</blockquote><p>It involves a binary file that appears to be a compiled rust code (<a href="https://github.com/sajjadium/ctf-archives/tree/main/ctfs/CyberSpace/2024/rev/sole">link</a>). We started by testing different inputs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/1*tAU34dBHScEXSgzPR22KfQ.png" /></figure><p>Nice progress! now we know that the flag should be 26 characters.</p><h4>Initial Exploration</h4><p>Upon receiving the binary, the first approach was to use <strong>GDB</strong> for disassembly and debugging. However, GDB did not yield useful insights, likely due to the complexity and obfuscation in the Rust-compiled binary.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/821/1*LNIpbcMbkKqiEpUz__9jtQ.png" /></figure><h4>When GDB Fails, Ghidra Prevails</h4><p>Ghidra provided a clearer view of the algorithms by outputting a pseudo-rust code. But it was still confusing:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/947/1*yhwJaW2yOlLiARX4FPP8Pg.png" /><figcaption>515 Lines of spaghetti codes</figcaption></figure><p>As you can see, we have variables named <strong><em>iVar1 … iVar28</em></strong><em> </em>which are pointing to the indices of our input string. There are many conditions in the source, validating our input string, resembling math equations:</p><pre>if (iVar24 + iVar13 != 0x1308) {<br>  local_8c = 1;<br>}<br>if (iVar24 != 0x5f76c) {<br>  local_8c = 1;<br>}<br>...</pre><p>At this point, we began cleaning up the source, collecting these equations and re-writing them in a python script. The result was a bit cleaner:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/839/1*20eJOV5r0SJJcX-JufEymw.png" /><figcaption>re-written in python</figcaption></figure><p>We could now solve the equations by modifying values and solving them one by one, but this approach was too time-consuming. We needed a more hacker-friendly solution.</p><p>First of all, we know that the flag starts with “<strong><em>CSCTF{“</em></strong> and ends with “<strong><em>}”</em></strong>. which means, based on our ghidra output the following variables should be filled with these values:</p><pre>iVar27 = ord(&#39;C&#39;)<br>iVar1 = ord(&#39;S&#39;)<br>iVar2 = ord(&#39;C&#39;)<br>iVar26 = ord(&#39;T&#39;)<br>iVar3 = ord(&#39;F&#39;)<br>iVar4 = ord(&#39;{&#39;)<br>iVar23 = ord(&#39;}&#39;)</pre><p>With these hints, we automated the process of solving the equations. We defined a dictionary containing the variable-value pairs, which allowed us to introduce two helper functions.</p><p>As expected, each equation should have at most one unknown variable. with this function, we can identify such equations:</p><pre>def var_to_solve(*args):<br>    unsolved_vars = []<br>    for arg in args:<br>        if not var.get(arg):<br>            unsolved_vars.append(arg)<br>    if len(unsolved_vars) == 1:<br>        return unsolved_vars[0]<br>    return None</pre><p>In the next step, we introduced another function which tries to iterate over all ascii characters and find the desired value for the variable:</p><pre>def solve(var_name, callback):<br>    for c in string.printable:<br>        var[var_name] = ord(c)<br>        if callback():<br>            return True<br>    return False</pre><p>Now let’s re-write the conditions (based on ghidra’s output) this way:</p><pre>while True:<br>    if v := var_to_solve(&#39;10&#39;, &#39;17&#39;, &#39;3&#39;):<br>        solve(v, lambda: var[&#39;10&#39;] + var[&#39;17&#39;] + var[&#39;3&#39;] == 0x5f76c)<br>    if v := var_to_solve(&#39;7&#39;, &#39;25&#39;, &#39;20&#39;):<br>        solve(v, lambda: var[&#39;7&#39;] * var[&#39;25&#39;] * var[&#39;20&#39;] == 0x8a9a8)<br>    if v := var_to_solve(&#39;27&#39;, &#39;20&#39;, &#39;13&#39;):<br>        solve(v, lambda: var[&#39;27&#39;] * var[&#39;20&#39;] + var[&#39;13&#39;] == 0x1308)<br>    if v := var_to_solve(&#39;7&#39;, &#39;27&#39;, &#39;10&#39;):<br>        solve(v, lambda: var[&#39;7&#39;] + var[&#39;27&#39;] + var[&#39;10&#39;] == 199)<br>    if v := var_to_solve(&#39;11&#39;, &#39;20&#39;, &#39;25&#39;):<br>        solve(v, lambda: var[&#39;25&#39;] - (var[&#39;11&#39;] + var[&#39;20&#39;]) == -0xe89)<br>...<br><br>    if len(var) == 26:<br>        break</pre><p>it repeats the process until finding all the 26 characters of our input and gives us the flag:</p><pre>CSCTF{ruSt_15_c00l_r1gHt?}</pre><p>Check out the full solution code here:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a0e79df4e88eae64751c4551f52a0f86/href">https://medium.com/media/a0e79df4e88eae64751c4551f52a0f86/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fc58c0566576" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[We removed Shared-Memory by building an eBPF Load-Balancer!]]></title>
            <link>https://medium.com/@amiremohamadi/we-removed-shared-memory-by-building-an-ebpf-load-balancer-394f9f1b344?source=rss-8117873f78f6------2</link>
            <guid isPermaLink="false">https://medium.com/p/394f9f1b344</guid>
            <category><![CDATA[cdn]]></category>
            <category><![CDATA[nginx]]></category>
            <category><![CDATA[ebpf]]></category>
            <category><![CDATA[linux]]></category>
            <dc:creator><![CDATA[Amir Mohamadi]]></dc:creator>
            <pubDate>Tue, 21 Feb 2023 10:53:34 GMT</pubDate>
            <atom:updated>2023-02-21T10:53:34.072Z</atom:updated>
            <content:encoded><![CDATA[<p>As a leading content delivery network (CDN) service, <a href="https://www.arvancloud.ir/en">ArvanCloud</a> processes hundreds of thousands of requests per second for tens of thousands of unique domains. Every request is handled through a range of modules, based on the configuration of the domain. Managing such a high volume of information is no small feat, and ArvanCloud has responded by using a suitable architecture and efficient solutions to ensure maximum processing efficiency.</p><p>In order to optimize resource usage and achieve high levels of performance, nginx is configured in a way to have a worker process per every logical CPU core. and these workers are designed to work independently of each other. Each worker has its own independent accept queue, and is responsible for processing a request from start to finish, including establishing a connection, sending the response, and closing the connection. This approach ensures that websites and web services stay fast, efficient, and able to handle high volumes of traffic.</p><p>Nginx workers open separate sockets with the <em>SO_REUSEPORT</em> option, so every packet is directed to one of the workers based on a hash which by default is calculated in the linux kernel from ip addresses and ports of source and destination of that packet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/819/1*ds8MONk_y4FcIQA_Tt_StA.png" /></figure><p>Every module requires specific data to process each request, and this data needs to be shared between all or some of the workers. Much of this data, such as configurations, is read-intensive and can be shared between workers without blocking the system using the Read-Copy-Update (<a href="https://www.kernel.org/doc/html/latest/RCU/whatisRCU.html">RCU</a>) mechanism. However, other types of data, such as <a href="https://www.arvancloud.ir/en/products/cdn/rate-limit">Rate Limit</a> counter, may change frequently over short periods of time, making it difficult to be shared efficiently.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*Vb1lKiQrL9KfxaRFhHRccg.png" /><figcaption>Shared Memory and Frequently Changed Data</figcaption></figure><p>Suppose a client with the IP address 192.51.100.1 sends a request. Requests with different ports (browser behavior), have different hashes and therefore are directed to a different worker. Also each worker is a separate and independent process that includes all necessary modules. However, because each request is directed to a separate worker, we need a mechanism to share data between them. For instance, in the Rate Limit module, we have to share counters<em> — which hold the number of requests to a specific ip in a period of time —</em> .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/827/1*IZXt2WYUJ5nr884P0RFbig.png" /></figure><p>Initially, we tried to use Redis and other similar tools to store this data, but the performance was not satisfying. To address this issue, we used shared memory, which improved the performance, but it still wasn’t optimal. In fact, during the early stages of a DDoS attack, the mutable data changed very rapidly. At this time, using a lock on a part of the Shared Memory also would affect every request, regardless of the Shared Memory design (blocking/lock-free), which would reduce efficiency.</p><p>As mentioned earlier, the kernel’s default load balance strategy <em>— which involves calculating the hash of IP addresses and ports of source and target —</em> results in malicious requests being directed to different workers during a DDoS attack therefore shared memory will be locked.</p><p>The next idea was to change the Load Balancing mechanism in order to optimize hardware utilization and eliminate the need for Shared Memory. This could be achieved by writing an eBPF program for UDP (from kernel version 4.5) and <a href="https://lwn.net/Articles/675043/">TCP (from kernel version 4.6)</a>, which allowed us to change kernel’s default Load Balancing approach.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/562/1*XETP-s9aCkWB3N0sJXke3A.png" /></figure><p>We decided to distribute the packets among workers based on a unique fingerprint, so that clients with the same IP address would always connect to the same worker. We also eliminated Shared Memory from all security modules and to optimize hardware utilization, we separated processing tasks from logical ones.</p><p>We modified Nginx source code and wrote a patch to connect our eBPF program.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/548/1*QNrT1W3ZXvTOHa35ZF3Iiw.png" /><figcaption>A simple eBPF program to change the kernel’s default load balancing mechanism</figcaption></figure><p>We keep an array of listened sockets in <em>reuse_sockmap</em> which is initialized every time nginx runs; Each request in the <em>socket lookup</em> phase reaches this eBPF program and is directed to one of the sockets based on our hash function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*6u_bgmwFysDYy2QStGBpQQ.png" /><figcaption>Benchmark: 1. Shared Memory 2. eBPF Load Balancer</figcaption></figure><p>According to the benchmark which compares two cases:</p><ul><li>Using a Shared Memory</li><li>Using our eBPF Load Balancer, and changing the load distribution method</li></ul><p>In the second case, there is no noticeable difference in response time with an increase in the number of requests.</p><h3>Conclusion</h3><p>In general, if you are a service provider in scale of a CDN, you should have strategies to evenly distribute the load on CPU cores and monitor the issues constantly. Long-Lived TCP sessions can cause a lot of load imbalance, and if you modify the load balancing mechanism or kernel’s polling behavior, you should be doubly concerned about the uniformity of this distribution and have solutions for different scenarios. Additionally, these changes should not disrupt other protocols like QUIC and etc. in the future.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=394f9f1b344" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TMUCTF 2021 — Flag Printer [Reverse Engineering]]]></title>
            <link>https://medium.com/@amiremohamadi/tmuctf-2021-flag-printer-reverse-engineering-512269ffc3bf?source=rss-8117873f78f6------2</link>
            <guid isPermaLink="false">https://medium.com/p/512269ffc3bf</guid>
            <category><![CDATA[ctf]]></category>
            <category><![CDATA[reverse-engineering]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Amir Mohamadi]]></dc:creator>
            <pubDate>Wed, 15 Sep 2021 19:10:05 GMT</pubDate>
            <atom:updated>2021-09-19T19:39:38.435Z</atom:updated>
            <content:encoded><![CDATA[<h3>TMUCTF 2021 — Flag Printer [Reverse Engineering]</h3><p>The challenge came with a binary file that you can download from <a href="https://github.com/amiremohamadi/ctf-writeups/raw/master/tmuctf-2021/flagprinter/flagprinter">here</a>. What are we gonna do? Let’s take a look at it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UTu29n6bZRRW9Pbm5-okTQ.png" /><figcaption>1. file type</figcaption></figure><p>So yep! it’s an ELF64, we can run it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-NzQHU6RpKhzQuPVenhQCA.png" /><figcaption>2. first run</figcaption></figure><p>Oops! takes a lot of time, sounds like it contains some sort of sleep/wait commands there. It’s a CTF Challenge, obviously waiting for the flag to be printed is not the solution :)</p><p>We’re gonna use <a href="https://ghidra-sre.org/">r</a>adare2 (r2ghidra plugin) to decompile it:</p><pre>[0x000010a0]&gt; aaa<br>[0x000010a0]&gt; s main<br>[0x00001272]&gt; pdg</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/887/1*MxirTZ3KGiZL9E_1CnOn7w.png" /><figcaption>3. main function</figcaption></figure><p>Hmm, there’s bunch of sleep commands there:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/887/1*ICb_sOcm10t2XMURxj9qnQ.png" /><figcaption>4. sleep commands</figcaption></figure><p>And It’s like first 4 characters are printed by these instructions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/887/1*W8mbAwjjCVg45utu2TYubA.png" /><figcaption>5. main function — prints “TMUC”</figcaption></figure><p>So for example We can produce character “T” by XORing the data located at 0x4020 with the return value of fcn.00001189() function then add 0x26.</p><p>We can remove all sleep() commands, is there any of them in fcn.00001189()? let’s see:</p><pre>[0x000010a0]&gt; s fcn.00001189<br>[0x00001189]&gt; pdg</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w-ud9pPwlgJnU59iwqXsUw.png" /><figcaption>6. fcn.00001189(undefined8 arg1)</figcaption></figure><p>No there’s not and maybe removing them is not gonna help us (Actually I tried it before). We should go deeper:</p><p>As you see it takes a parameter (arg1) and returns different values depending on the conditions. So to produce the first character, we can dump memory:</p><pre>[0x00001189]&gt; x/32x <a href="http://twitter.com/0x4020">@0x4020</a></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/847/1*U79Ir2GSOy3AgKNpaa5PGQ.png" /><figcaption>7. data located at 0x4020</figcaption></figure><p>For the first instruction uVar1 is 0x2e and uVar2 is fcn.00001189(0) which actually is 0 based on what we saw before (picture 6). So:</p><pre>&gt;&gt;&gt; uVar1 = 0x2e<br>&gt;&gt;&gt; uVar2 = 0<br>&gt;&gt;&gt; (uVar1 ^ uVar2) + 0x26<br>84</pre><pre>&gt;&gt;&gt; chr(84)<br>&#39;T&#39;</pre><pre>&gt;&gt;&gt;</pre><p>Very well, We already know that “TMUC” is printed by the first part of the code, and the for-loop is responsible for the remaining part of flag:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/887/1*bFz04mxqK52Gmx-vZbUe2w.png" /><figcaption>8. print the other part of the flag</figcaption></figure><p>If we look at fcn.00001189() more carefully, We see it’s implemented recursively. Maybe that’s the problem, most of the time recursive functions calculate same values multiple times and that’s heavy. Do You remember fibonacci function recursive implementation? It was like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cBY8wI-0eXdq_ZMOVYyw3Q.png" /><figcaption>9. fibonacci function</figcaption></figure><p>And the recursion tree:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/753/1*P6QNgkFiXlcOz9IjRf--zw.jpeg" /><figcaption>10. fibonacci recursion tree</figcaption></figure><p>You can see how many times it is called with same values.</p><p>We can improve our recursive function performance by using memoization. memoization means storing results of previous function calls to speed up future calculations.</p><p>Ok, we’ll re-implement the code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*7XUc0eEvEeHdFzz9JjBy-Q.png" /><figcaption>11. re-implementation of the code</figcaption></figure><p>Run and test:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/956/1*twIsybAPBCaEicHsHv-UPg.png" /><figcaption>12. running the code</figcaption></figure><p>Seems works fine. let’s call it with greater values:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/572/1*6B7EpakC_OZZ5_-cnvheYg.png" /><figcaption>13. bigger values</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/953/1*R_-qN6debmH6O2LEThStHA.png" /><figcaption>14. running with bigger values</figcaption></figure><p>As we guessed, it’s getting stuck. gonna try it another time, but this time we change it to store and use pre-computed values:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/763/1*GbZGHo8lW_HQfMsdOnwZ7A.png" /><figcaption>15. memoization</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*Ko-hQVsk25xOaeTG9q-Raw.png" /><figcaption>16. fcn.00001189() with memoization</figcaption></figure><p>let’s call the function and see if We get the other part of the flag:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*MNCWIyCG-EzY3Qad-Or98g.png" /><figcaption>17. other part of the code (remember? we dumped memory before)</figcaption></figure><p>Just try it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/901/1*cUtKgmwSCQn8sjkpe6v1xQ.png" /><figcaption>18. flag</figcaption></figure><p>Woah! We got the flag, actually the flag is:</p><pre>&gt;&gt;&gt; &#39;TMUC&#39; + &#39;TF{7h15_l4zy_f1l3_5l33p5_700_much}&#39;<br>TMUCTF{7h15_l4zy_f1l3_5l33p5_700_much}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=512269ffc3bf" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>