How to Prevent Cross-Site Scripting (XSS) Attacks

XSS Attack is the principle of the attacker will be malicious code implanted into the page, resulting in the user browsing the page will be in the trick!

XSS can:

  • Steal user, administrator session to get all permissions
  • Control User Action (CSRF)
  • Initiated DDOS attacks
  • Tamper with the page
  • and many more


First, filter the data

Most defense methods will talk about this, filtering data as the most effective way highly respected. But can not just do this, and this has to do the whole!

* Full filtering rules *

Blacklist filtering for keywords is very tricky and must be used in conjunction with a whitelist and a blacklist. And filtration rules must be complete and reliable, can not have any omission! Complete rules of the venue XSS Filter

* Global filtering of all input data *

Filter the input data is not just filter GPC ($ the GET / $ the POST / $ _ COOKIE), all points related to the inputs are likely to be forged, such AGENT / IP / URL, and specific venue PHP risk function in the input function!

Filtration should follow a principle: * * not trust any external data .

In addition the concept of the overall situation was clear: many times the vulnerability is caused by the developer’s negligence, so the framework layer and the bottom should be the overall filter data. Such as access to data in PHP using $ the GET, ** frame floor entrance should be rewritten or newly built $ the GET ** such functions, ensure their safety!

* Global filtering of all display data *

Most people know that filtering input data, but missed the output data, the output data as a final show to the user filter should be better protection!

* Editor filter *

The rich text editor uses the scene to be more and more many, because its particularity causes its security question frequently. If the business allows the proposed use of Markdown or forums commonly used to replace the UBB, if you do not use the editor before the customization of streamlining features and timely upgrade!

Second, HttpOnly

XSS great purpose is to steal a user session information (SESSION), and to steal SESSION need to read the client Cookie, so use HttpOnly can effectively prevent such a session to steal attacks! HttpOnly on how to set the venue HttpOnly

Third, CSP rules

XSS want to take advantage of the need to implement JS, and most of the attackers in order to obtain more information, and in order to more easily modify the injection script is often dynamically loaded remote JS files, and CSP (Content Security Policy) is mainly used to limit the specified load resource file , Through the CSP we can restrict not the same domain under the IMG / JS / CSS / FONT and other resources to load the file. Setting rules for the specific venue and CSP

Suggest reading: A careful steps should be followed when dealing with a cross site scripting to avoid link errors in your system.