How and where can XSS protection be applied in Laravel? How and where can XSS protection be applied in Laravel? php php

How and where can XSS protection be applied in Laravel?


Makes much more sense to me not to let those sneaky bastards into the database in the first place.

Actually - that is not true.

The reason that XSS is only handled by blade is that XSS attacks are an output problem. There is no security risk if you store <script>alert('Hacking Sony in 3...2...')</script> in your database - it is just text - it doesnt mean anything.

But in the context of HTML output - then the text has a meaning, and therefore that is where the filtering should occur.

Also - it is possible that XSS attack could be a reflected attack, where the displayed data is not coming from the database, but from another source. i.e. an uploaded file, url etc. If you fail to filter all the various input locations - you run a risk of missing something.

Laravel encourages you to escape all output, regardless where it came from. You should only explicitly display non-filtered data due to a specific reason - and only if you are sure the data is from a trusted source (i.e. from your own code, never from user input).

p.s. In Laravel 5 the default {{ }} will escape all output - which highlights the importance of this.

Edit: here is a good discussion with further points on why you should filter output, not input: html/XSS escape on input vs output


As far as I know, the "official" Laravel position is that XSS prevention best practice is to escape output. Thus, {{{ }}}.

You can supplement output escaping through input sanitation with Input::all(), strip_tags(), and array_map():

$input = array_map('strip_tags', \Input::all());


I examined the Laravel's protection {{{...}}} against xss attack. It just uses the htmlentities() function in the way like this: htmlentities('javascript:alert("xss")', ENT_QUOTES, 'UTF-8', false); This protects you against xss only if you use it properly means dont use it in certain HTML tags because it will result in XSS attack possibility. For example:

$a = htmlentities('javascript:alert("xss")', ENT_QUOTES, 'UTF-8', false); echo '<a href="'.$a.'">link</a>';

In this case, it is vulnerable to xss.