Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What precautions should I take to prevent XSS on user submitted HTML?

Tags:

javascript

xss

I'm planning on making a web app that will allow users to post entire web pages on my website. I'm thinking of using HTML Purifier but I'm not sure because HTML Purifier edits the HTLM and it's important that the HTML is maintained just how it was posted. So I was thinking making some regex to get rid of all script tags and all the javascript attributes like onload, onclick, etc.

I saw a Google video a while ago that had a solution for this. Their solution was to use another website to post javascript in so the original website cannot be accessed by it. But I don't wanna purchase a new domain just for this.

like image 527
fent Avatar asked Dec 08 '22 06:12

fent


2 Answers

be careful with homebrew regexes for this kind of thing

A regex like

s/(<.*?)onClick=['"].*?['"](.*?>)/$1 $3/

looks like it might get rid of onclick events, but you can circumvent it with

<a onClick<a onClick="malicious()">="malicious()">

running the regex on that will get you something like

<a onClick ="malicious()">

You can fix it by repeatedly running the regex on that string until it doesn't match, but that's just one example of how easy it is to get around simple regex sanitizers.

like image 197
Charles Ma Avatar answered Mar 18 '23 12:03

Charles Ma


The most critical error people make when doing this is validating things on input.

Instead, you should validate on display.

The context matters when determing what is XSS and what isn't. Therefore, you can happily accept any input, as long as you pass it through appropriate cleaning functions when displaying it.

Consider that something that constitutes 'XSS' will be different when the input is placed in a '&lt;a href="HERE"> as opposed to <a>here!</a>.

Thus, all you need to do, is make sure that any time you write user data, you consider, very carefully, where you are displaying it, and make sure that it can't escape the context you are writing it to.

like image 21
Noon Silk Avatar answered Mar 18 '23 12:03

Noon Silk