What Are the Best Practices For Avoiding Xss Attacks in a PHP Site

What are the best practices for avoiding xss attacks in a PHP site

Escaping input is not the best you can do for successful XSS prevention. Also output must be escaped. If you use Smarty template engine, you may use |escape:'htmlall' modifier to convert all sensitive characters to HTML entities (I use own |e modifier which is alias to the above).

My approach to input/output security is:

  • store user input not modified (no HTML escaping on input, only DB-aware escaping done via PDO prepared statements)
  • escape on output, depending on what output format you use (e.g. HTML and JSON need different escaping rules)

Protect WYSIWYG input from XSS attacks in PHP?

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.

Should I use htmlentities() on all output? (preventing XSS attacks)

There are two benefits to using htmlentities():

  • XSS prevention
  • Converting special characters to proper HTML entities, for example it converts the copyright character to ©. In HTML content you should use the appropriate HTML entity instead of inserting a raw special character.

For XSS prevention, you could use htmlspecialchars() instead, but it will only convert some basic characters to HTML entities, namely quotes, ampersand and the less than/greater than characters.

In answer to your question, you should use htmlentities() when outputting any content that could contain user input or special characters.



Related Topics



Leave a reply



Submit