Hi guys,
One of the first things I learned as a web developer was to never ever accept any HTML from the client. (Perhaps only if I HTML encode it.)
I use a WYSIWYG editor (TinyMCE) that outputs HTML. So far I have only used it on an admin page, but now I'd like to also use it on a forum. It has a BBCode module, but that seems to be incomplete. (It is possible that BBCode itself doesn't support everything I want it to.)
So, here's my idea:
I allow the client to directly POST some HTML code. Then, I check the code for sanity (well-formedness) and remove all tags, attributes, and CSS rules that are not allowed based on a pre-defined set of allowed tags and styles.
Obviously I would allow the stuff that can be outputted by the subset of TinyMCE functionality I use.
I would allow the following tags:
span
, sub
, sup
, a
, p
, ul
, ol
, li
, img
, strong
, em
, br
With the following attributes:
style
(for everything), href
and title
(for a
), alt
and src
(for img
)
And the following CSS rules:
color
, font
, font-size
, font-weight
, font-style
, text-decoration
These cover everything that I need for formatting, and (as far as I know) don't present any security risk. Basically, the enforcement of well-formedness and the lack of any layouting styles prevent anyone to hurt the layout of the site. The disallow of the script tag and the likes prevent XSS.
(One exception: maybe I should allow width
/height
in a predefined range for images.)
Other advantage: this stuff would save me from the need to write / look for a BBCode-Html converter.
What do you think?
Is this a secure thing to do?
(As I see, StackOverflow also allows some basic HTML in the "About Me" field, so I think I'm not the first one to implement this.)
EDIT:
I found this answer which explains how to do this fairly easily.
And of course, noone should think about using regex for this.
The question itself is not related to any language or technology, but if you are wondering, I write this application in ASP.NET.