Directly writing user input (for example, an HTTP request parameter) to a webpage, without properly sanitizing the input first, allows for a cross-site scripting vulnerability.

To guard against cross-site scripting, consider encoding/escaping the untrusted input before including it in the HTML.

The following example shows a simple web handler that writes a URL path parameter directly to an HTML response, leaving the website vulnerable to cross-site scripting:

To fix this vulnerability, the user input should be HTML-encoded before being included in the response. In the following example, encode_text from the html_escape crate is used to achieve this:

  • OWASP: Cross Site Scripting Prevention Cheat Sheet.
  • Wikipedia: Cross-site scripting.
  • OWASP: Cross Site Scripting (XSS).