Web Application Security Guide/Cross-site scripting (XSS)
Persistent XSS vulnerabilities store the user input and include it later outputs (e.g. a posting in a forum). This means that the users do not need to visit a malicious/compromised site.
To prevent this type of attack
- Escape anything that is not a constant before including it in a response as close to the output as possible (i.e. right in the line containing the “echo” or “print” call)
- If not possible (e.g. when building a larger HTML block), escape when building and indicate the fact that the variable content is pre-escaped and the expected context in the name
- Explicitly set the correct character set at the beginning of the document (i.e. as early as possible) and/or in the header.
- don’t forget URLs in redirector scripts
Escaping data directly at the output location makes it easier to check that all outputs are escaped – each and every variable used as a parameter for an output method must either be marked as pre-escaped or be wrapped in a corresponding escape command.
Different contexts require completely different escaping rules. A “)” character with no dangerous meaning in HTML and HTML attributes can signify the end of an URL path in CSS.
Not setting the character set may lead to guessing by the browser. Such guessing can be exploited to pass a string that seems harmless in your intended encoding, but is interpreted as a script tag in the encoding assumed by the browser. For HTML5, use
<meta charset="utf-8" /> as the first element in the head section.