Is it possible to display HTML while maintaining XSS protection?

markmanwithlatte
Member | 3
+
0
-

I have some text string that is actually HTML that I am displaying in the suggested way {$myData['text_parsed']}

Now this contains a mix of HTML and text data in which I want the HTML to be correctly displayed (with CSS and everything). With standard latte I am seeing output as <div class=“blahblah”>div content</div>, etc.. like it is supposed to do

if I do {$myData['text_parsed']|noescape}, then the HTML displays but of course now I have XSS vulnerability with any JSthat is in user supplied content.

Is it possible to have the best of both worlds? I am using PHP 7.3 BTW so that some of the ways custom filters are described in the docs are not working for me because I assume I have older version of latte running

What I am ultimately trying to do is parse and display BBCode, so I have my parsing engine working fine which transforms the data into HTML, but that is where I am stuck between displaying HTML and XSS flaw.

I notice this very forum we are typing on seems to have solved the problem, as it seems to be able to parse correctly markdown/bbcode into html tags without worrying about XSS

Last edited by markmanwithlatte (2025-07-10 23:41)

mystik
Member | 320
+
0
-

You need to nesure that BBcode parser would never generate XSS in resulting HTML. It is entirely on parser how it generates code, how it escapes values and what it allows or not.

Instead of using noescaoe filter in Latte it is better to wrap HTML cod3 in Html object from Nette before passing it to Latte.

Second layer or protection should be CSP headers that would disallow running inline JS.

markmanwithlatte
Member | 3
+
0
-

Ok I have been thinking unfortuantly that was the only route I would be forced to go. I trust latte more than a BBCode parser for true XSS protection.

But you bring up an idea I didn't know about which is the Nette HTML object…

If I am understanding you correctly if I use the following (https://doc.nette.org/…elements/2.x) then could I have the BBCode parser return to me a bunch of Nette HTML elements:

$el = Html::el('div');
$el[] = '<b>hello</b>';

Here, Nette seems to say you would do an echo $el but could I just put the $el element as a variable for my Latte template to then handle? In that case does it still get the XSS protection from latte or I am back to the start where I still need to use |noescape with the $el element do you think?

For example if we had

$el = Html::el('div');
$el[] = '<b><script>alert(1)</script></b>';

...

$data = [
'mydata1'=> 'Hello!'
'myhtmlcode'=> $el
];

$latte->render($templateName, $data);

Template:

<div>Does this work or does it create XSS? {$myhtmlcode}<div>

Thank you!

Last edited by markmanwithlatte (2025-07-11 16:24)