Web Security Web Security

Challenge 2: Defend Against XSS Attacks

Check out a free preview of the full Web Security course:
The "Challenge 2: Defend Against XSS Attacks" Lesson is part of the full, Web Security course featured in this preview video. Here's what you'd learn in this lesson:

In this challenge, students address XSS bugs and add a CSP policy to course demo application.

Get Unlimited Access Now

Transcript from the "Challenge 2: Defend Against XSS Attacks" Lesson

>> Mike North: So what we're gonna do, you have a bunch of cross site scripting stuff that you've figured out. We've got our three little bugs. We're going to fix the bugs by editing some of that server side code. So we know the unsafe thing to check for, remember, it's less than percent dash.

[00:00:19] Eradicate that from the code base, with a couple exceptions. There are some places where, due to the layouts, like any time we've got like html wrapping other html, you should leave some of these intact. But anything that's user generated input, we should make sure that we sanitize appropriately.

[00:00:41] What we wanna do then is add a reasonable content security policy. And here is something that is pretty reasonable here. There's an additional twist I've added here. I didn't explain it in slides, so I wanna explain it now. Note that font source has a data colon as the source of that directive, right?

[00:01:04] That basically means we allow base64 encoded URLs to be font sources. So in this case the font is expressed as a base64 encoded URL. So content security policy like this should make the app work. You just have to figure out how to express that. There is a library already installed that is popular option for adding a CSP to an express app.

[00:01:25] It is called helmetjs/csp. helmetjs just deals with adding headers to requests, basically. So there are a couple of different libraries there. This is the file you'll be working with. It's in server/index.js, and reading the documentation here should give you a clue as to how you should proceed. I will say that it's best here to start relatively simple and to increment forward.

[00:01:53] And this is where your lvh.me domains might be useful because browsers might, depending on how, you may find that the content security policy sticks on a particular domain beyond one request. So you want to test this out, tighten things up. You'll basically like lock things down to the point where the CSS is not gonna work, the JavaScript's not gonna work, and piece by piece you kinda get back to where we don't have error messages anymore.

[00:02:24] But you should find that if you go and try to tamper with any of those static assets, like the script tag, for example, that's being inserted.
>> Mike North: It'll complain about it, and it'll say oops. Some unauthorized change has been made.