3
votes

I have read in my places that to prevent XSS attacks, the best practice is to do first a stripslashes and then a htmlspecialchars on the user input. However, in some cases that is not possible, for example when allowing the user some basic markup with a WYSIWYG editor.

Does PHP offer any methods for this, that allow a certain whitelist of basic tags (b, i, u, a, img, ...) but strips them of all their potentially dangerous arguments, as well as escaping all html special chars except for the <,> and " belonging to the set of whitelisted tags & tag arguments?

Or should I just forget about doing that and switch to a different approach like using BBcode for user input with markup?

1
Wait, TinyMCE automatically protects from XSSYang
@bad_boy The editor itself is client side and can therefore never offer any reasonable protection.user1111929
The choices are use a library like HTMLPurifier as suggested, or switch to a markdown format, or roll your own.bishop
I came here to find out how to protect TinyMCE against XSS attacks, so people telling OP that TinyMCE protects against XSS I can confirm to be falsely informed because it doesn't, at least not the version I'm using. If TinyMCE protects against this, A) this has not always been the case and B) I don't want to trust a user not to forge POST requests.toon81

1 Answers

3
votes

You should implement a Content Security Policy on any pages where you output the rich text in addition to making the text safe for HTML output by using a sanitizer such as HTML Purifier. This should be effective in preventing injected script commands from running.

The CSP allows you to effectively stop inline script from being executed by the browser. It is currently supported by modern browsers such as Chrome and Firefox (although IE only currently has partial support).

This is done by a HTTP response header from your page.

e.g.

Content-Security-Policy: script-src 'self' https://apis.google.com

will stop inline JavaScript from being executed if a user managed to inject it into your page (it will be ignored with a warning), but will allow script tags referencing either your own server or https://apis.google.com. This can be customised to your needs as required. The HTML sanitizer is still needed for browsers that do not support CSP so you should still run all user supplied input through that first.