How to prevent XSS

First tutorial on the forum! Yay!

First of all, what is Cross Site Scripting (XSS)? XSS is when JavaScript code is run by a client on a website in an unauthorized manor via a textbox or other method. For example:

https://worried-chestnut-meat.glitch.me/?text=Hello

Notice how the text hello is rendered onto the screen. Now try using the textbox to render some HTML code. You will notice that this also renders to the screen.
image

Now try typing <script>alert("Hello");</script>

What happens? (reply to this thread with the answer)

While it may be a bit funny to write bold text to the page and run alerts in JavaScript, hackers can write code that can give them access to your account (if you had an account and were signed in on the given website).

Not convinced? Check out this demo where I use JavaScript to “hack” myself:

Now, I will teach you how to prevent this:

PHP

Do not do this:

<?php
    echo $_GET['text'];
?>

Do this:

<?php
    echo htmlspecialchars($_GET['text']);
?>

NodeJS

Try a package:

Django

Try a package:

Try running XSS on my new and improved project:
https://ringed-bold-look.glitch.me/

11 Likes

Thank you for the tutorial!

6 Likes

It’s worth noting that XSS should be prevented on client side before rendered on the page, not server side!

5 Likes

DOMPurify is what I would recommend, it also sanitises SVGs and MathML.

6 Likes

still not convinced :sweat_smile:

about the chrome extensions

2 Likes

Still not convinced of what? That XSS is a problem? Because let me tell you rn, it is a problem, a major one.

6 Likes

one of the biggest issues facing web developers every day is XSS, it’s horrible

4 Likes

XSS is the 7th top issue web developers are facing. Have s look at OWASP’s top ten :

6 Likes

you can prevent it though

Most developers dont notice until it’s too late.

1 Like

Of course they don’t.

It’s actually one of the reasons I like react, you can pass in dirty data into your components


3 Likes

I think something you should’ve mentioned was EditMyCookie. It is safe and can be used for good and bad.

Thanks for the useful tutorial!

I wrote a post about a little-known but dangerous form of XSS once: on dev.to

I think you may want to add a colon to the link!

2 Likes

yea fixed that lol

1 Like

How would you go about this? Block inputs containing “<” ? My school site automatically removes tags - maybe that’s one way.

I suppose that could do the trick, but I may be wrong.

Using a module like String.prototype.safe.

require("string.prototype.safe");

const htmlString = "<script>alert('XSS')</script>".safe();
5 Likes

I see you there :laughing:
image

2 Likes