14 Cross-site scripting attacks

 

This chapter covers

  • Validating input with forms and models
  • Escaping special characters with a template engine
  • Restricting browser capabilities with response headers

In the preceding chapter, I introduced you to a handful of little injection attacks. In this chapter, I continue with a big family of them known as cross-site scripting (XSS). XSS attacks come in three flavors: persistent, reflected, and DOM-based. These attacks are both common and powerful.

Note

At the time of this writing, XSS is number 7 on the OWASP Top Ten (https://owasp.org/www-project-top-ten/).

XSS resistance is an excellent example of defense in depth; one line of protection is not enough. You’ll learn how to resist XSS in this chapter by validating input, escaping output, and managing response headers.

14.1 What is XSS?

XSS attacks come in many shapes and sizes, but they all have one thing in common: the attacker injects malicious code into the browser of another user. Malicious code can take many forms, including JavaScript, HTML, and Cascading Style Sheets (CSS). Malicious code can arrive via many vectors, including the body, URL, or header of an HTTP request.

XSS has three subcategories. Each is defined by the mechanism used to inject malicious code:

  • Persistent XSS
  • Reflected XSS
  • DOM-based XSS

In this section, Mallory carries out all three forms of attack. Alice, Bob, and Charlie each have it coming. In subsequent sections, I discuss how to resist these attacks.

14.1.1 Persistent XSS

14.1.2 Reflected XSS

14.1.3 DOM-based XSS

14.2 Input validation

14.4.3 The X-XSS-Protection header