Reputation: 6097
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?
Upvotes: 3
Views: 2244
Reputation: 33538
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.
Upvotes: 3