Leaking File Contents with a Blind File Oracle in Flarum
The avatar upload endpoint passed user-controlled file data into the Intervention Image library, which decides how to load an image based on the content of the string. Because a URL or a local file path was accepted as image source, an attacker with a basic account could make the server fetch remote resources or read local files through a blind oracle.
Flarum is a free, open source PHP-based forum software used for everything from gaming hobbyist sites to cryptocurrency discussion. A quick survey on Shodan suggests there are over 1200 installs exposed to the internet.
The full write-up lives on its author's site
It belongs to its author, so we link to it rather than copy it. The other two tabs are our own rewrites, checked against it.
Context
Flarum is a free, open source PHP-based forum software used for everything from gaming hobbyist sites to cryptocurrency discussion. A quick survey on Shodan suggests there are over 1200 installs exposed to the internet. Because Flarum is forum software, the majority of installations typically permit users to create their own accounts, so authenticated routes are interesting too, as long as they do not require administrative permissions.
The feature at the centre of this write-up is the avatar upload: an authenticated user can send a file to the API and have it stored as their forum avatar. The endpoint is defined in framework/core/src/Api/routes.php:
// Upload avatar
$map->post(
'/users/{id}/avatar',
'users.avatar.upload',
$route->toController(Controller\UploadAvatarController::class)
);
The same routes file also exposes other endpoints, including an admin-only one that was ruled out early:
// Send test mail post
$map->post(
'/mail/test',
'mailTest',
$route->toController(Controller\SendTestMailController::class)
);
Setup
No special tooling is described. The research started from the open source code: the vast majority of a Flarum installation comes from the flarum/framework repository on GitHub, so no reverse engineering was needed. The first step was to work out which routes were accessible, using the routes.php files in different directories, and in particular framework/core/src/Api/routes.php.
The precondition for the attack is only a basic user account: the avatar route is reachable by any authenticated user, and the only authorisation check is that the actor may edit the target user. No administrative permissions are required.
Finding it
The UploadAvatarController is straightforward:
protected function data(ServerRequestInterface $request, Document $document)
{
$id = Arr::get($request->getQueryParams(), 'id');
$actor = RequestUtil::getActor($request);
$file = Arr::get($request->getUploadedFiles(), 'avatar');
return $this->bus->dispatch(
new UploadAvatar($id, $file, $actor)
);
}
The route takes a user id in the query parameter and a file upload named avatar, then dispatches an UploadAvatar action to the bus. The action is handled in framework/core/src/User/Command/UploadAvatarHandler.php:
class UploadAvatarHandler
{
use DispatchEventsTrait;
...
/**
* @var ImageManager
*/
protected $imageManager;
...
public function handle(UploadAvatar $command)
{
$actor = $command->actor;
$user = $this->users->findOrFail($command->userId);
if ($actor->id !== $user->id) {
$actor->assertCan('edit', $user);
}
$this->validator->assertValid(['avatar' => $command->file]);
$image = $this->imageManager->make($command->file->getStream());
$this->events->dispatch(
new AvatarSaving($user, $actor, $image)
);
$this->uploader->upload($user, $image);
$user->save();
$this->dispatchEventsFor($user, $actor);
return $user;
}
}
The handler checks that the actor has access to change the avatar of the user with that ID, which prevents a trivial IDOR. The interesting part is the behaviour of imageManager->make. The ImageManager comes from the Intervention Image library.
Intervention Image is a PHP image handling and manipulation library that provides a simple interface to load, store and edit images. Its documentation for make describes it as a universal factory method to create a new image instance from source, highly variable to read all the input types listed below. The library lists these accepted sources:
string - Path of the image in filesystem.
string - URL of an image (allow_url_fopen must be enabled).
string - Binary image data.
string - Data-URL encoded image data.
string - Base64 encoded image data.
resource - PHP resource of type gd. (when using GD driver)
object - Imagick instance (when using Imagick driver)
object - Intervention\Image\Image instance
object - SplFileInfo instance (To handle Laravel file uploads via Symfony\Component\HttpFoundation\File\UploadedFile)
That list raised alarm bells: the application passes a string to this method (not exactly a string, but an object with a __toString() magic method) and the user has full control over it. On the happy path it just works, since one of the accepted options is binary image data. The question was what happens if the uploaded file contains a URL.
Exploitation
Step 1: understand how the decoder dispatches on input type
The library's AbstractDecoder::init decides how to interpret the data:
namespace Intervention\Image;
abstract class AbstractDecoder
{
// ...
public function init($data)
{
$this->data = $data;
switch (true) {
case $this->isGdResource():
return $this->initFromGdResource($this->data);
case $this->isImagick():
return $this->initFromImagick($this->data);
case $this->isInterventionImage():
return $this->initFromInterventionImage($this->data);
case $this->isSplFileInfo():
return $this->initFromPath($this->data->getRealPath());
case $this->isBinary():
return $this->initFromBinary($this->data);
case $this->isUrl():
return $this->initFromUrl($this->data);
case $this->isStream():
return $this->initFromStream($this->data);
case $this->isDataUrl():
return $this->initFromBinary($this->decodeDataUrl($this->data));
case $this->isFilePath():
return $this->initFromPath($this->data);
// isBase64 has to be after isFilePath to prevent false positives
case $this->isBase64():
return $this->initFromBinary(base64_decode($this->data));
default:
throw new NotReadableException("Image source not readable");
}
}
}
The URL branch is the one of interest. Its check and its fetch look like this:
public function isUrl()
{
return (bool) filter_var($this->data, FILTER_VALIDATE_URL);
}
// ...
public function initFromUrl($url)
{
$options = [
'http' => [
'method'=>"GET",
'protocol_version'=>1.1, // force use HTTP 1.1 for service mesh environment with envoy
'header'=>"Accept-language: en\r\n".
"User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36\r\n"
]
];
$context = stream_context_create($options);
if ($data = @file_get_contents($url, false, $context)) {
return $this->initFromBinary($data);
}
throw new NotReadableException(
"Unable to init from given url (".$url.")."
);
}
User input reaches file_get_contents without any validation except that it must look like a URL. The one limitation is that the content to leak must be a valid image, otherwise an error is thrown when the library parses the contents.
Step 2: enumerate the abuse cases
The researcher brainstormed three ways to abuse the fetch:
- Pass an internal URL such as
http://localhost:8100/favicon.icoand possibly leak that image if it exists. - Pass an internal URL such as
http://localhost:9001/do/evil/action?param=fooand conduct a blind SSRF attack. - Despite the stream context, PHP is happy to accept a
fileURI, so an input likefile:///home/foo/secret.pngcould possibly reveal the contents of an image on the local filesystem.
These are real vulnerabilities, but they are context-dependent and not so impactful. The blind file oracle makes the impact much larger.
Step 3: turn the fetch into a blind file oracle
First revealed in the DownUnderCTF 2022, there is a technique for leaking the contents of arbitrary files using the php:// wrapper even if the output of the file read is not given to the user. In this case the files of interest are most likely not going to form valid images, so the technique applies perfectly. The attack hinges on two features of the php://filter wrapper.
The first is that the filter wrapper supports converting between two different charsets using the convert.iconv function. For instance, the request php://filter/convert.iconv.latin1.UTF-32/resource=/etc/passwd would take the contents of /etc/passwd and convert it from the latin1 charset to UTF-32. The file content gets mapped like this:
latin1: root:x:
UTF-32: r\0\0\0o\0\0\0o\0\0\0t\0\0\0:\0\0\0x\0\0\0:\0\0\0
The output blows up 4x in size, because each latin1 char is encoded in a fixed 4 bytes of UTF-32. Repeating the process blows the string up to 16x, 64x, 256x size, and so on, until it exceeds the memory limit and causes the PHP process to stop and return 500. If the file pointed to is empty or does not exist, no 500 error is generated. That forms an oracle to test for emptiness.
On its own this is not so useful, but PHP has another interesting feature, the dechunk filter. It was intended for parsing HTTP chunks, but on arbitrary strings its behaviour is:
- If the string is a single line and begins with one of
0-9a-fA-F, the whole line is removed; - Otherwise, the string remains untouched.
Information can then be leaked from a file as follows:
- Base64 encode the file using the
convert.base64-encodefunction; - Apply the
dechunkfilter; - Blow up the string multiple times using a latin1 to UTF-32 conversion.
If there is no 500, the file contents in base64 must have started with one of 0-9a-fA-F. If there is a 500, it cannot have started with those characters, so it must be in g-zG-Z+/.
The full file leak is more complicated and uses multiple iconv conversions to swap other characters to the front and precisely determine which character is at the front. The details are explained in the original challenge's solution script and in a blog post by Synacktiv. With a simple modification to that script, the technique can be used to leak the contents of any file on the server.
Root cause
The mistake is in how the application uses the library: user-controlled upload data is passed directly into ImageManager::make, and the library treats a string that validates as a URL as something to fetch with file_get_contents. The only validation is filter_var($this->data, FILTER_VALIDATE_URL), which does not restrict the scheme or destination, so http and file inputs are accepted, and the php://filter wrapper can be used for the blind oracle. The authorisation check in UploadAvatarHandler (assertCan('edit', $user)) correctly prevents changing another user's avatar, but it does nothing about what the image library does with the file contents. The library's own error handling (throwing NotReadableException when the fetched data is not a valid image) is what the blind oracle turns into a signal.
Impact
With only a basic user account, an attacker can leak the contents of arbitrary local files in Flarum through a blind oracle, and conduct blind SSRF attacks. The file read is blind: the attacker learns file contents through the 500 versus non-500 oracle rather than seeing the data directly. The SSRF is likewise blind. The simpler variants (fetching an internal image such as a favicon, or a file:// path to an image) depend on the target existing and being a valid image.
Fix
Flarum fixed the vulnerability promptly and versions >= 1.8.0 are no longer vulnerable. The advisory is GHSA-67c6-q4j4-hccg and the vulnerability was assigned CVE-2023-40033.
The researchers also tried reaching out to the developers of Intervention Image several times with suggestions to make the library less vulnerable by default, but got no response. Their recommendation for anyone using the library is to never pass user data directly into the constructor; to turn an upload into an image, pass the file path to the uploaded tempfile instead.
Variants to test
- Upload a file whose contents are an internal URL such as
http://localhost:8100/favicon.ico. A positive result is the internal image being leaked if it exists, which confirms server-side fetching. - Upload a file whose contents are an internal URL with a side effect, such as
http://localhost:9001/do/evil/action?param=foo. A positive result is the internal service receiving the request, confirming blind SSRF. - Upload a file whose contents are a
file://path to an image, such asfile:///home/foo/secret.png. A positive result is the local image's contents being revealed. - Upload a file whose contents are a
php://filterchain combiningconvert.base64-encode,dechunkand repeatedconvert.iconv.latin1.UTF-32conversions against a known file. A positive result is no 500 when the base64 output starts with0-9a-fA-Fand a 500 otherwise, which confirms the blind file oracle. - Anywhere else user-supplied data reaches an image library constructor (avatars, attachments, thumbnails), try the same URL and
php://filterinputs. A positive result is a fetch, an SSRF, or an error-based difference that reveals file contents.
What happened, in plain words
Flarum is a piece of software that lets people run an online discussion forum, the kind of site where members post threads and reply to each other. It is free, its source code is public, and it is written in a programming language called PHP. The researchers behind this write-up found that anyone with an ordinary forum account, no special powers needed, could make the forum server read files stored on its own disk and reveal their contents a little at a time. They could also make the server send requests to other machines on the same internal network, which is called SSRF.
The trick lives in a small feature every forum member knows: uploading a picture to use as your avatar, the little image shown next to your name. The forum hands the uploaded file to a third-party image library, and that library is far too trusting about what it is given. If the uploaded file contains a web address instead of a picture, the library goes and fetches that address. If it contains a special PHP address that points at a file on the server, the library can be made to read that file through the blind oracle. The result is not shown to the user directly, but the difference between the server crashing and not crashing leaks the file's contents one character at a time. The researchers call this a blind file oracle.
Flarum fixed the problem in version 1.8.0. The issue was given the identifier CVE-2023-40033.
Background: what Flarum is and why it matters
Flarum is open source forum software. "Open source" means the code that runs it is published for anyone to read, so the researchers did not have to guess how it worked or reverse engineer a compiled program: they could simply read the source on GitHub. A quick search on Shodan, a website that indexes devices and services connected to the internet, suggested there were over 1200 Flarum installations reachable from the internet at the time.
Because Flarum is forum software, most installations let visitors create their own accounts. That matters for security research: a feature that only works once you are logged in is still reachable by an attacker, as long as it does not also require administrator rights. So the researchers were interested in two kinds of pages and endpoints: the public ones, and the ones available to any logged-in member.
What an API endpoint is
An API is the part of a website that programs talk to, rather than people. When you click a button in a browser, the page often sends a small request behind the scenes to the server, and the server answers with data. Each such address the server listens on is called an endpoint or a route. You can think of a restaurant: the dining room is the website you see, the kitchen is the server, and the API is the serving hatch where orders are passed in and dishes come out. Each dish on the menu is a route.
The feature at the centre of this write-up is the avatar upload. A logged-in user sends a file to the API and the server stores it as that user's avatar. The route is defined in a file called framework/core/src/Api/routes.php:
// Upload avatar
$map->post(
'/users/{id}/avatar',
'users.avatar.upload',
$route->toController(Controller\UploadAvatarController::class)
);
Line by line:
// Upload avataris a comment, a note for humans that the computer ignores. It says what the next lines do.$map->post(starts the definition of a route that answers HTTP POST requests. POST is the method a browser uses when it sends data to a server, for example when you submit a form or upload a file. The$mapobject is the list of all routes the application knows about.'/users/{id}/avatar'is the address pattern. The{id}part is a placeholder: it will be replaced by a number identifying a particular user. So the real address might be/users/5/avatar.'users.avatar.upload'is an internal name for this route, used elsewhere in the code to refer to it.$route->toController(Controller\UploadAvatarController::class)says which piece of code handles requests to this address. A controller is simply the class, a bundle of code, that does the work when the route is hit. Here it isUploadAvatarController.);closes the call.
The same routes file also defines other endpoints, including one that only administrators can use, which the researchers ruled out early because they did not have admin rights:
// Send test mail post
$map->post(
'/mail/test',
'mailTest',
$route->toController(Controller\SendTestMailController::class)
);
Line by line:
// Send test mail postis a comment saying this route sends a test email.$map->post(defines another POST route.'/mail/test'is the address.'mailTest'is its internal name.$route->toController(Controller\SendTestMailController::class)points at the code that handles it,SendTestMailController.);closes the call.
This route is interesting in principle, because sending email can be abused, but it requires administrator permissions, so it was set aside.
Setting up the research
No special tools are described. The work started from the public source code. Almost all of a Flarum installation comes from one repository on GitHub called flarum/framework, so the researchers could read the whole application. The first step was to work out which routes were reachable. They did this by reading files called routes.php in different directories, and in particular framework/core/src/Api/routes.php, which lists many of the interesting ones.
The only precondition for the attack is a basic user account. The avatar route can be reached by any logged-in user, and the only permission check is that the person making the request is allowed to edit the target user. No administrator rights are needed.
Finding the problem
The code that handles the avatar upload, the UploadAvatarController, is short:
protected function data(ServerRequestInterface $request, Document $document)
{
$id = Arr::get($request->getQueryParams(), 'id');
$actor = RequestUtil::getActor($request);
$file = Arr::get($request->getUploadedFiles(), 'avatar');
return $this->bus->dispatch(
new UploadAvatar($id, $file, $actor)
);
}
Line by line:
protected function data(...)declares a function calleddata.protectedis a visibility keyword meaning only this class and related classes can call it. The parameters are the incoming request and a document object.$id = Arr::get($request->getQueryParams(), 'id');reads theidvalue from the query string, the part of a URL after the?. So if the address is/users/5/avatar?id=5, this picks up5. It is stored in a variable called$id.$actor = RequestUtil::getActor($request);works out who is making the request, the logged-in user. That user is called the actor.$file = Arr::get($request->getUploadedFiles(), 'avatar');picks the uploaded file that was sent under the form field nameavatar.return $this->bus->dispatch(sends a command off to be handled. A command bus is a common pattern: instead of doing the work right here, the controller packages up a request and hands it to a central dispatcher, which finds the right handler. Think of it as a waiter writing your order on a ticket and passing it to the kitchen.new UploadAvatar($id, $file, $actor)is the command: upload an avatar for user$id, using$file, on behalf of$actor.);closes the dispatch call.}closes the function.
The command is then handled in framework/core/src/User/Command/UploadAvatarHandler.php:
class UploadAvatarHandler
{
use DispatchEventsTrait;
...
/**
* @var ImageManager
*/
protected $imageManager;
...
public function handle(UploadAvatar $command)
{
$actor = $command->actor;
$user = $this->users->findOrFail($command->userId);
if ($actor->id !== $user->id) {
$actor->assertCan('edit', $user);
}
$this->validator->assertValid(['avatar' => $command->file]);
$image = $this->imageManager->make($command->file->getStream());
$this->events->dispatch(
new AvatarSaving($user, $actor, $image)
);
$this->uploader->upload($user, $image);
$user->save();
$this->dispatchEventsFor($user, $actor);
return $user;
}
}
Line by line:
class UploadAvatarHandlerdeclares the class that does the work.use DispatchEventsTrait;pulls in a reusable bundle of code, called a trait, that lets the class fire events. Events are announcements that something happened, which other parts of the application can listen for....marks code left out of the excerpt./** * @var ImageManager */is a documentation comment saying the next property holds anImageManager.protected $imageManager;declares that property. It is the object that will process the uploaded image.public function handle(UploadAvatar $command)is the function that runs when the command arrives.$actor = $command->actor;gets the user who made the request.$user = $this->users->findOrFail($command->userId);looks up the target user by id. If no such user exists, it throws an error, which is whatfindOrFailmeans.if ($actor->id !== $user->id) {checks whether the person making the request is someone other than the target user.!==means "is not identical to".$actor->assertCan('edit', $user);if they are different people, it checks that the actor has permission to edit that user. If not, it stops with an error. This is the permission check that prevents a trivial IDOR, which stands for Insecure Direct Object Reference: a bug where you can simply change a number in a request to act on someone else's data. Here, changing the id to another user's number does not let you change their avatar.}closes the if.$this->validator->assertValid(['avatar' => $command->file]);runs validation rules on the uploaded file, for example size or type checks.$image = $this->imageManager->make($command->file->getStream());is the interesting line. It takes the uploaded file's contents as a stream, a way of reading data piece by piece, and asks the image manager to turn it into an image object. The result is stored in$image.$this->events->dispatch(new AvatarSaving($user, $actor, $image));announces that an avatar is being saved.$this->uploader->upload($user, $image);stores the image.$user->save();saves the user record.$this->dispatchEventsFor($user, $actor);fires any further events tied to the user.return $user;returns the updated user.}closes the function.}closes the class.
The permission check is correct: it stops you changing someone else's avatar. The interesting part is what imageManager->make does with the file. The ImageManager comes from a separate library called Intervention Image.
What a library is, and what Intervention Image does
A library is a bundle of code written by someone else that your program uses instead of writing everything itself. If your program needs to handle images, you can either write all the code to read, resize and save pictures, or you can use a library that already does it. Intervention Image is a PHP library for exactly that: loading, storing and editing images through a simple interface.
Its documentation for the make method describes it as a universal factory method to create a new image instance from source, highly variable to read all the input types listed below. In plain words: make accepts many different kinds of input and works out for itself what it has been given. The library lists these accepted sources:
string - Path of the image in filesystem.
string - URL of an image (allow_url_fopen must be enabled).
string - Binary image data.
string - Data-URL encoded image data.
string - Base64 encoded image data.
resource - PHP resource of type gd. (when using GD driver)
object - Imagick instance (when using Imagick driver)
object - Intervention\Image\Image instance
object - SplFileInfo instance (To handle Laravel file uploads via Symfony\Component\HttpFoundation\File\UploadedFile)
Line by line, this is a list of things you can hand to make:
string - Path of the image in filesystem.A piece of text giving the location of an image file on disk, such as/var/www/logo.png.string - URL of an image (allow_url_fopen must be enabled).A web address. The note in brackets refers to a PHP setting that must be switched on for PHP to fetch remote addresses; it commonly is.string - Binary image data.The raw bytes of an image, exactly as they appear inside a file.string - Data-URL encoded image data.An image embedded inside a text string in the data-URL format, which browsers also use for small inline images.string - Base64 encoded image data.An image encoded as base64, a way of writing raw bytes using only ordinary text characters.resource - PHP resource of type gd. (when using GD driver)An already-open image held in memory by PHP's GD graphics extension.object - Imagick instance (when using Imagick driver)An image object from a different graphics library, ImageMagick.object - Intervention\Image\Image instanceAn image object from this library itself.object - SplFileInfo instance (...)A PHP object that describes a file, used here to handle uploads coming through the Laravel framework.
That list raised alarm bells. The application passes a string to this method, or more precisely an object that can turn itself into a string when needed, and the user has full control over its contents. On the normal path everything works, because one of the accepted inputs is raw image data. The question the researchers asked was: what happens if the uploaded file contains a URL instead of a picture?
Exploitation
Step 1: understand how the decoder decides what it has been given
The library's AbstractDecoder::init decides how to interpret the data:
namespace Intervention\Image;
abstract class AbstractDecoder
{
// ...
public function init($data)
{
$this->data = $data;
switch (true) {
case $this->isGdResource():
return $this->initFromGdResource($this->data);
case $this->isImagick():
return $this->initFromImagick($this->data);
case $this->isInterventionImage():
return $this->initFromInterventionImage($this->data);
case $this->isSplFileInfo():
return $this->initFromPath($this->data->getRealPath());
case $this->isBinary():
return $this->initFromBinary($this->data);
case $this->isUrl():
return $this->initFromUrl($this->data);
case $this->isStream():
return $this->initFromStream($this->data);
case $this->isDataUrl():
return $this->initFromBinary($this->decodeDataUrl($this->data));
case $this->isFilePath():
return $this->initFromPath($this->data);
// isBase64 has to be after isFilePath to prevent false positives
case $this->isBase64():
return $this->initFromBinary(base64_decode($this->data));
default:
throw new NotReadableException("Image source not readable");
}
}
}
Line by line:
namespace Intervention\Image;says which package this code belongs to, a way of keeping names from different libraries apart.abstract class AbstractDecoderdeclares a class that is not used directly but is the base for other classes. A decoder is the part that turns raw input into an image.// ...marks code left out.public function init($data)is the function that receives the input.$this->data = $data;stores the input on the object.switch (true) {starts a chain of tests. Eachcaseis a condition; the first one that is true wins, and itsreturnruns.case $this->isGdResource():if the input is a GD image resource, thenreturn $this->initFromGdResource($this->data);handles it that way.case $this->isImagick():if it is an ImageMagick object,return $this->initFromImagick($this->data);handles it.case $this->isInterventionImage():if it is one of the library's own image objects,return $this->initFromInterventionImage($this->data);handles it.case $this->isSplFileInfo():if it is a file-describing object,return $this->initFromPath($this->data->getRealPath());reads the file at its real path.case $this->isBinary():if it looks like raw image bytes,return $this->initFromBinary($this->data);uses them directly.case $this->isUrl():if it looks like a web address,return $this->initFromUrl($this->data);fetches it. This is the branch that matters here.case $this->isStream():if it is a stream,return $this->initFromStream($this->data);reads from it.case $this->isDataUrl():if it is a data-URL,return $this->initFromBinary($this->decodeDataUrl($this->data));decodes it and uses the bytes.case $this->isFilePath():if it is a file path,return $this->initFromPath($this->data);reads that file.// isBase64 has to be after isFilePath to prevent false positivesis a comment explaining the order: base64 is checked after file paths because some file paths could accidentally look like base64.case $this->isBase64():if it is base64 text,return $this->initFromBinary(base64_decode($this->data));decodes it.default:if none of the above matched,throw new NotReadableException("Image source not readable");stops with an error saying the input could not be read.}closes the switch,}closes the function,}closes the class.
The URL branch is the one of interest. Its check and its fetch look like this:
public function isUrl()
{
return (bool) filter_var($this->data, FILTER_VALIDATE_URL);
}
// ...
public function initFromUrl($url)
{
$options = [
'http' => [
'method'=>"GET",
'protocol_version'=>1.1, // force use HTTP 1.1 for service mesh environment with envoy
'header'=>"Accept-language: en\r\n".
"User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36\r\n"
]
];
$context = stream_context_create($options);
if ($data = @file_get_contents($url, false, $context)) {
return $this->initFromBinary($data);
}
throw new NotReadableException(
"Unable to init from given url (".$url.")."
);
}
Line by line:
public function isUrl()declares the test for whether the input is a URL.return (bool) filter_var($this->data, FILTER_VALIDATE_URL);uses a built-in PHP function,filter_var, with theFILTER_VALIDATE_URLrule, which checks whether a piece of text has the shape of a URL. The(bool)turns the result into true or false. Note what this does not do: it does not check where the URL points, or which scheme it uses. A scheme is the part before the colon, such ashttp,httpsorfile.}closes the function.// ...marks code left out.public function initFromUrl($url)declares the function that fetches a URL.$options = [starts an array of settings for the fetch.'http' => [groups the settings for HTTP, the protocol browsers use to talk to web servers.'method'=>"GET",says to use the GET method, the ordinary way of asking for a page.'protocol_version'=>1.1, // force use HTTP 1.1 for service mesh environment with envoysets the HTTP version to 1.1. The comment says this was done for service mesh environments using Envoy, a piece of networking software.'header'=>"Accept-language: en\r\n".starts the request headers, the extra lines sent with a request. This one says the preferred language is English.\r\nis the line break that separates headers."User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36\r\n"adds a User-Agent header, which tells the server what browser is asking. Here it pretends to be Chrome on Windows. The.joins the two strings together.]closes the HTTP settings,];closes the options array.$context = stream_context_create($options);turns those settings into a context, a bundle of options that PHP's file functions accept.if ($data = @file_get_contents($url, false, $context)) {fetches the URL.file_get_contentsis a PHP function that reads the contents of a file or URL into a string. The@suppresses warnings. The result is stored in$data, and theifchecks that it is not empty.return $this->initFromBinary($data);if something came back, it is treated as raw image bytes.}closes the if.throw new NotReadableException("Unable to init from given url (".$url.").");if nothing came back, it stops with an error that includes the URL.}closes the function.
User input reaches file_get_contents with no validation beyond looking like a URL. The one limitation is that whatever is fetched must be a valid image, otherwise an error is thrown when the library tries to parse it.
Step 2: list the ways this can be abused
The researchers thought of three ways to abuse the fetch:
- Pass an internal URL such as
http://localhost:8100/favicon.icoand possibly leak that image if it exists.localhostmeans the server itself, and8100is a port, a numbered door on a machine where a particular service listens. - Pass an internal URL such as
http://localhost:9001/do/evil/action?param=fooand conduct a blind SSRF attack. SSRF stands for Server-Side Request Forgery: the attacker makes the server send a request the attacker cannot send directly, for example to a service that is only reachable from inside the network. It is called blind when the attacker cannot see the response, only infer what happened. - Despite the stream context, PHP is happy to accept a
fileURI, so an input likefile:///home/foo/secret.pngcould possibly reveal the contents of an image on the local filesystem. A URI is a general form of address;file://means a file on the local disk rather than something on the network.
These are real vulnerabilities, but they depend on circumstances: the file has to exist, or the internal service has to do something useful, and the result has to be a valid image. The blind file oracle makes the impact much larger.
Step 3: turn the fetch into a blind file oracle
What an oracle is
In security, an oracle is any behaviour that answers a yes or no question. You cannot see the secret, but you can ask the server questions and watch how it reacts. A simple everyday comparison: you cannot see inside a locked room, but you can slide a note under the door and listen for a reply. Each reply tells you something.
First revealed in the DownUnderCTF 2022, a capture-the-flag competition, there is a technique for leaking the contents of arbitrary files using the php:// wrapper even when the output of the file read is not shown to the user. A wrapper is a special address prefix that tells PHP to read from somewhere other than an ordinary file, for example from a network stream or through a filter. In this case the files of interest are unlikely to be valid images, so the technique fits perfectly. It relies on two features of the php://filter wrapper.
Feature one: charset conversion blows data up
The first feature is that the filter wrapper can convert between two character sets using convert.iconv. A character set, or charset, is a way of mapping bytes to characters. For example, php://filter/convert.iconv.latin1.UTF-32/resource=/etc/passwd would take the contents of /etc/passwd, a standard file on Unix-like systems that lists user accounts, and convert it from latin1 to UTF-32. The content gets mapped like this:
latin1: root:x:
UTF-32: r\0\0\0o\0\0\0o\0\0\0t\0\0\0:\0\0\0x\0\0\0:\0\0\0
Line by line:
- The text is the start of a line in the password file.
UTF-32: r\0\0\0o\0\0\0o\0\0\0t\0\0\0:\0\0\0x\0\0\0:\0\0\0shows the same text after conversion to UTF-32, where every character takes four bytes. The\0marks are zero bytes, padding. Sorbecomesrfollowed by three zero bytes,obecomesofollowed by three zero bytes, and so on.
The output is four times larger, because each latin1 character is now stored in a fixed four bytes. Repeat the conversion and the string grows to 16 times, 64 times, 256 times, and so on. Eventually it grows so large that it exceeds the memory limit set for the PHP process, and the process stops and returns a 500 error. A 500 is the standard HTTP status code for a server-side failure. If the file pointed to is empty or does not exist, no 500 is produced. That gives an oracle to test whether a file has content.
Feature two: the dechunk filter
On its own, that is not very useful. But PHP has another interesting feature, the dechunk filter. It was written to parse HTTP chunked transfer encoding, a way of sending a response in pieces, but on arbitrary strings its behaviour is:
- If the string is a single line and begins with one of
0-9a-fA-F, the whole line is removed; - Otherwise, the string remains untouched.
In other words, dechunk looks at the first character. If it is a digit or a letter from a to f, in either case, the line disappears. If it is anything else, nothing happens. That is a yes or no answer about the first character.
Putting the two together
Information can then be leaked from a file as follows:
- Base64 encode the file using
convert.base64-encode. Base64 turns raw bytes into ordinary text characters, so the file becomes a long string of letters, digits,+and/. - Apply the
dechunkfilter. If the first character of the base64 text is in0-9a-fA-F, the line is removed and the string becomes empty. - Blow the string up many times using a latin1 to UTF-32 conversion. If the string is empty, nothing grows and no 500 happens. If the string is not empty, it grows until memory runs out and a 500 is returned.
So if there is no 500, the file contents in base64 must have started with one of 0-9a-fA-F. If there is a 500, it cannot have started with those characters, so it must be in g-zG-Z+/. Either way, the attacker learns something about the first character.
The full file leak is more complicated. It uses multiple iconv conversions to swap other characters to the front, so that each character in turn can be tested and the exact character at the front determined. The details are explained in the original challenge's solution script and in a blog post by Synacktiv. With a simple modification to that script, the technique can be used to leak the contents of any file on the server.
Root cause
The mistake is in how the application uses the library. User-controlled upload data is passed directly into ImageManager::make, and the library treats a string that passes the URL check as something to fetch with file_get_contents. The only validation is filter_var($this->data, FILTER_VALIDATE_URL), which does not restrict the scheme or the destination, so http, file and php://filter inputs are all accepted. The permission check in UploadAvatarHandler (assertCan('edit', $user)) correctly prevents changing another user's avatar, but it does nothing about what the image library does with the file contents. The library's own error handling, throwing NotReadableException when the fetched data is not a valid image, is exactly what the blind oracle turns into a signal.
Impact
With only a basic user account, an attacker can leak the contents of arbitrary local files in Flarum through a blind oracle, and conduct blind SSRF attacks. The file read is blind: the attacker learns file contents through the 500 versus non-500 oracle rather than seeing the data directly. The SSRF is likewise blind. The simpler variants, fetching an internal image such as a favicon or a file:// path to an image, depend on the target existing and being a valid image.
Fix
Flarum fixed the vulnerability promptly, and versions >= 1.8.0 are no longer vulnerable. The advisory is GHSA-67c6-q4j4-hccg and the vulnerability was assigned CVE-2023-40033. An advisory is a public notice describing a security problem and its fix; a CVE is a standard identifier given to a publicly known vulnerability so people can refer to it unambiguously.
The researchers also tried reaching out to the developers of Intervention Image several times with suggestions to make the library less vulnerable by default, but got no response. Their recommendation for anyone using the library is to never pass user data directly into the constructor; to turn an upload into an image, pass the file path to the uploaded tempfile instead. A constructor is the function that creates an object; a tempfile is the temporary file the server writes an upload to before processing it.
Variants to test
- Upload a file whose contents are an internal URL such as
http://localhost:8100/favicon.ico. A positive result is the internal image being leaked if it exists, which confirms server-side fetching. - Upload a file whose contents are an internal URL with a side effect, such as
http://localhost:9001/do/evil/action?param=foo. A positive result is the internal service receiving the request, confirming blind SSRF. - Upload a file whose contents are a
file://path to an image, such asfile:///home/foo/secret.png. A positive result is the local image's contents being revealed. - Upload a file whose contents are a
php://filterchain combiningconvert.base64-encode,dechunkand repeatedconvert.iconv.latin1.UTF-32conversions against a known file. A positive result is no 500 when the base64 output starts with0-9a-fA-Fand a 500 otherwise, which confirms the blind file oracle. - Anywhere else user-supplied data reaches an image library constructor, for example avatars, attachments or thumbnails, try the same URL and
php://filterinputs. A positive result is a fetch, an SSRF, or an error-based difference that reveals file contents.
Glossary
- API: the part of a website that programs talk to, rather than people, made up of endpoints that accept requests and return data.
- Endpoint (route): a specific address on a server that accepts a particular kind of request and runs particular code.
- HTTP POST: the method a browser uses to send data to a server, for example a form submission or a file upload.
- Controller: the piece of code that handles a request to a particular route.
- Command bus: a pattern where a controller packages a request into a command and hands it to a central dispatcher, which finds the handler.
- Trait: a reusable bundle of code that a class can pull in.
- Event: an announcement inside an application that something happened, which other code can listen for.
- IDOR: Insecure Direct Object Reference, a bug where changing an identifier in a request lets you act on someone else's data.
- Library: a bundle of code written by someone else that your program uses.
- ImageManager / Intervention Image: a PHP library for loading, storing and editing images.
- Factory method: a function that creates an object, often accepting several different kinds of input and working out what it has been given.
- String: a piece of text in a program.
- Binary data: raw bytes, exactly as stored in a file.
- Base64: a way of writing raw bytes using only ordinary text characters.
- Data-URL: a way of embedding data, such as an image, inside a text string.
- Resource: a special value in PHP that refers to something open, such as an image held in memory.
- GD / Imagick: PHP extensions for handling images.
- Namespace: a way of grouping names in code so that different libraries do not clash.
- Abstract class: a class that is not used directly but is the base for other classes.
- Decoder: the part of a library that turns raw input into an image.
- Switch: a programming construct that tests a series of conditions and runs the first one that matches.
- URL: a web address, such as
https://example.com/page. - Scheme: the part of a URL before the colon, such as
http,httpsorfile, which says how to reach the target. - Header: an extra line sent with an HTTP request or response, such as the User-Agent.
- User-Agent: a header that says what browser or program is making a request.
- Stream context: a bundle of options that PHP's file functions accept when reading from a URL or stream.
file_get_contents: a PHP function that reads the contents of a file or URL into a string.- localhost: the name a machine uses to refer to itself.
- Port: a numbered door on a machine where a particular service listens.
- SSRF: Server-Side Request Forgery, making the server send a request the attacker cannot send directly, often to an internal service.
- Blind: a vulnerability where the attacker cannot see the response, only infer what happened.
- URI: a general form of address;
file://means a file on the local disk. - Oracle: any behaviour that answers a yes or no question, letting an attacker learn a secret indirectly.
- CTF: capture the flag, a security competition where participants solve challenges.
- Wrapper: a special address prefix in PHP that tells it to read from somewhere other than an ordinary file.
- Charset: a way of mapping bytes to characters, such as latin1 or UTF-32.
- iconv: a function for converting text between character sets.
- UTF-32: a character set where every character takes four bytes.
- 500 error: the standard HTTP status code for a server-side failure.
- Memory limit: the maximum amount of memory a PHP process is allowed to use before it stops.
- dechunk: a PHP filter written to parse HTTP chunked transfer encoding, which removes a line that begins with a digit or a letter from a to f.
- Chunked transfer encoding: a way of sending an HTTP response in pieces.
- Root cause: the underlying mistake that makes a vulnerability possible.
- Advisory: a public notice describing a security problem and its fix.
- CVE: a standard identifier given to a publicly known vulnerability.
- Constructor: the function that creates an object.
- Tempfile: the temporary file a server writes an upload to before processing it.