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.
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
Keep Your Apps Secure on Cloud
Cloudways offers 2FA, free SSL, and more advanced security features on managed servers that keep your application safe.
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=jAvascript: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', 'RegisterController@viewRegisterPage'); Route::post('register', 'RegisterController@registerAction); });
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:
- PHP Html Purifier
- .Net HTML sanitizer (“The library is unit tested with the OWASP XSS Filter Evasion Cheat Sheet“)
- OWASP Java HTML Sanitizer
- Python Bleach
- 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.
Shahzeb Ahmed
Shahzeb is a Digital Marketer with a Software Engineering background, works as a Community Manager — PHP Community at Cloudways. He is growth ambitious and aims to learn & share information about PHP & Laravel Development through practice and experimentation. He loves to travel and explore new ideas whenever he finds time. Get in touch with him at [email protected]