This website uses cookies

Our website, platform and/or any sub domains use cookies to understand how you use our services, and to improve both your experience and our marketing relevance.

Prevent Laravel XSS Exploits Using Validation and User Input Sanitization

June 22, 2021

4 Min Read

While the security of web applications has remained an important aspect in software development, the issue has attained paramount significance because of higher business stakes and investments into the applications, and a security vulnerability can really put a dent on the reputation of the company and its ability to do business.

In this article, I will talk about Laravel validation and how you can sanitize form inputs to prevent Laravel XSS exploits from harming your Laravel applications.

Why do we need Input Sanitization?

Hackers use RFI (Remote File Inclusion) and injection attacks like Cross-Site Script (XSS) and SQL Injection (SQLi) to exploit the connection between websites and servers. They can execute unauthorized actions that can compromise security. However, with sanitization in place, these attacks can be prevented.

Input sanitization is a security protocol for checking, filtering, and cleaning data inputs from app users. Input data travels via GET requests, POST requests, and cookies, which hackers can modify, manipulate, and edit to gain access to the server that the web app is hosted on.

Image Ref: imperva.com

Input sanitization is not perfect and the only option to fight different malicious attacks. But it has advantages such as:

  • Providing a perimeter defense against common cyberattacks
  • Preventing remote file inclusion and injection attacks
  • Protecting the system from malicious code
  • Safeguarding the web server, database, and other digital assets

Scalable, Fast & Secure Managed Laravel Hosting

Our clients love us because we never compromise on features.

Possible XSS Exploitation Points

There are different ways a hacker can attack your Laravel web application. The following are a few examples to look out for:

Script in Attributes

XSS attacks may be conducted without using the <script>…</script> tags. Other tags will do exactly the same thing, such as <body onload=alert(‘test1’)> or other attributes including onmouseover or onerror.

onmouseover
<b onmouseover=alert('Wufff!')>click me!</b>

onerror
<img src="https://url.to.file.which/not.exist" onerror=alert(document.cookie);>

Script Via Encoded URI Schemes

If we need to hide against web application filters, we may try to encode string characters, e.g.: a=&\#X41 (UTF-8) and use it in IMG tags:

<IMG SRC=j&#X41vascript:alert('test2')>

Many different UTF-8 encoding notations give us even more possibilities.

Code Encoding

We can encode our scripts in base64 and place them in the Meta Tag. This way we get rid of alert() completely.

<META HTTP-EQUIV="refresh"
CONTENT="0;url=data:text/html;base64,PHNjcmlwdD5hbGVydCgndGVzdDMnKTwvc2NyaXB0Pg">

Laravel Validation Rules Provided by Default

  • required: Only accept if the value is not null. Laravel nulls the input if the field is left empty.
  • email: Only accept if the input is in email format, [email protected]
  • sometimes: A web-form field that might be there because of a selected option in the form. In that case, you can specify sometimes | required

Laravel Sanitization

Sanitization of input includes the techniques to identify and remove the possible input entries of strings that can be harmful to your application.

Example:
Here’s how you can sanitize the input by stripping away the script tags using the PHP strip_tags function.

Route::post('/task', function (Request $request) {
$cleaned_name = strip_tags($request->input('name'));
$task = new Task;
$task->names = $cleaned_name;
$task->save();

return redirect('/');

How to Add Middleware for Validation Checks on User Input

Let’s have a look at adding the authorization and validation at the same time on web forms. Laravel offers a Request class for this purpose.

You can create a form with this Request class using the following command:

Php artisan make:middleware XssSanitization

This command will by default generate the following class in app/Http/Middleware/XssSanitization.php

namespace App\Http\Middleware;

use Closure;

use Illuminate\Http\Request;

class XssSanitizer

{

public function handle(Request $request, Closure $next)

{

$input = $request->all();

array_walk_recursive($input, function(&$input) {

$input = strip_tags($input);

});

$request->merge($input);

return $next($request);

}

}

Next, register this middleware in our app/Http/Kernel.php file and add the following line in the $routeMiddleware array.

class Kernel extends HttpKernel

{

....

protected $routeMiddleware = [

'auth' => \App\Http\Middleware\Authenticate::class,

....

'XssSanitizer' => \App\Http\Middleware\XssSanitizer::class,

];

}


You can now use the XssSanitization middleware in the routes.

Route::group(['middleware' => ['XssSanitizer']], function () {

Route::get('view-register', '[email protected]');

Route::post('register', '[email protected]);

});

Best Practices for XSS Protection in a Laravel Application

Here are some key takeaways for the best application of this procedure.

  • Add layers of protection. Redundancy improves security. By adding more layers, you give yourself more chances to catch malicious input that might slip through initial security.
  • Do not overlook client-side validation. This tutorial was focused on backend validation, but you could easily add a new layer of front-end protection using HTML/JavaScript. For example, I can limit the input length through HTML:
    <input type=”text” name=”task” maxlength=”10″>
  • Alternatively, I could have used a JS function to validate/sanitize the input.
    function validateForm() {
    var x = document.forms[“myTasksForm”][“task”].value;
    if (x == null || x == “” || x.length > 10) {
    alert(“Task must not be empty and must be shorter than 10 characters”);
    return false;
    }
    }
  • Encoding URLs to deny access to the Get parameters.
  • By using an Auto-Escaping Template System such as Laravel Blade Templates.
  • By using libraries that are specifically designed to sanitize HTML input:
  • For an in-depth and updated list of practices, check out The Open Web Application Security Project (OWASP).
  • Standardization at the header level of Content-Type and make sure that the response type of the server isn’t “text / html” and prevent the browser from auto-detecting the data type ‘nosniff’.
  • Implement a Content Security Policy (CSP) to limit the negative consequences when malicious code is inserted.

Keep it Safe and Sanitized

Web dev frameworks fix and upgrade their coding standards which overcome many possible vulnerabilities. Not every vulnerability can be fixed on a tool or framework level. On a day-to-day basis, the responsibility of web developers or the admin is to ensure that their application doesn’t allow hackers to exploit any known vulnerability.

Let me know in the comments section below if you know a tip that can help prevent Laravel XSS attacks, and I’ll review and add it to the article.

Share your opinion in the comment section. COMMENT NOW

Share This Article

Customer Review at

“Cloudways hosting has one of the best customer service and hosting speed”

Sanjit C [Website Developer]

Salman Siddique

Salman is a content marketer with a CS background, so he is (very) good at creating and marketing technical content. When not working as a Digital Content Producer at Cloudways, he enjoys reading interesting stuff and learning new skills.

×

Get Our Newsletter
Be the first to get the latest updates and tutorials.

Thankyou for Subscribing Us!

×

Webinar: How to Get 100% Scores on Core Web Vitals

Join Joe Williams & Aleksandar Savkovic on 29th of March, 2021.

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!