PHP Session Poisoning (LFI to RCE)
Full command arsenal in the cheatsheetSession poisoning is the variant of log poisoning that needs no log. PHP stores each session in a file on disk, and that file is written by the server itself with data we often control. If there is also a file inclusion, including the session file executes whatever we put inside it.
The default path is /var/lib/php/sessions/sess_<PHPSESSID> on Debian and derivatives, and /tmp/sess_<PHPSESSID> on many other installs; session.save_path in php.ini decides. The file name is the value of our own cookie, so there is nothing to guess: we know it because the server handed it to us.
The flow has three steps and the order matters:
- Get a session and keep the cookie. If the application has registration and login, something we type (the username) usually ends up stored in the session.
- Poison it, putting PHP code in the field that gets stored.
- Include the file through the LFI in that same session, because the file only exists while the cookie is alive.
curl -s -c cookies.txt -X POST http://<host>/register.php --data 'user=<?php system($_GET["cmd"]); ?>&pass=<pass>'
curl -s -b cookies.txt 'http://<host>/index.php?lang=../../../../var/lib/php/sessions/sess_<PHPSESSID>&cmd=id' --path-as-isWhat makes it different from log poisoning, and better where it is available:
- No log needs to be readable. Server logs usually carry restrictive permissions and the PHP user cannot always read them; its own session directory, always.
- The file is small and entirely ours. A production
access.loghas megabytes of noise in front of the payload; asess_file has what we just wrote. - The file name is not guessed. The server just gave us the
PHPSESSID.
On Windows the same idea works against whatever session.save_path points to, usually C:\Windows\Temp or the tmp directory of the PHP install.
Requirements. That the LFI includes and executes PHP rather than just printing it; that the web process can read its own session directory (normal, since it is the one writing it); and that some value we control is serialised into the session. If the application sanitises the obvious field before storing it, poison a different one.
How to detect it. On the filesystem, a sess_* file containing <?php, system( or $_GET has no legitimate explanation: it is the cleanest signature there is, and a recursive grep over session.save_path finds it. In the access log, a request whose inclusion parameter points at /var/lib/php/sessions/ or /tmp/sess_. And on the host, the PHP process reading a session file and immediately spawning a shell as a child.
Defence. The same as for any LFI: an allowlist of includable files and never include $_GET. On top of that, keep session.save_path out of any path reachable by traversal, bound open_basedir, and sanitise what goes into the session the same way you sanitise what gets printed.
Machines where it's used
- SniperHackTheBox