Reputation: 7905
How should I prevent a malicious user from performing a XSS attack when he/she is allowed to use HTML tags, i.e. in a textarea element? I'm not going to strip all tags or escape them so I can't use {{ }}
.
By the way: there is another dangerous situation where even {{ }}
is not a good idea. Please consider this link. Is there any way to let user use html tags but prevent him from performing a XSS attack?
Upvotes: 0
Views: 2126
Reputation: 15599
Client side html editors are probably the biggest challenges when trying to prevent XSS. Many 3rd party editor components fail to do so, actually.
One approach that can actually work reasonably well for many scenarios is sanitization. You can take a sanitizer library that has html as its input and has almost the same html as its output, except it (is supposed to) remove all javascript. One example is HTML Purifier, which does this on the server side.
Many would probably argue that the only correct place to do this is server-side. However, there is sometimes one caveat in that, which may or may no apply to your usecase. If the client-side html editor has a preview, that must also be sanitized to prevent DOM XSS, and preview is often not sent to the server (the edited content is just displayed right away on the client without a server roundtrip). While this is a lower risk XSS, it definitely is one that you need to prevent, and server-side sanitization does little good here.
So you might want to use a client-side sanitizer either besides or instead of the server-side one. One example to that is the client-side sanitizer in Google Caja (it's a much bigger project, I'm only talking about their sanitizer in Javascript), or there is also DOMPurify for another example on the client. These could be hooked into any client-side html editor component to sanitize any code before actually displaying it, thus effectively eliminating XSS.
The risk in any sanitization is that the sanitizer misses something and an attack vector for XSS is allowed through. This is basically a trust thing, lots of people use Caja for instance, it was developed by Google, so you may have some assurance that it's reasonably good. Whether that's good enough for you depends on your exact scenario, risk appetite, etc.
There may be other approaches (serving HTML content from a different origin and accepting the risk of XSS on that origin, or using a custom markup carefully converting it to XSS-free html, etc.), but sanitization probably works best for most usecases.
Upvotes: 1