Cross-site Scripting and how to fix it
Tags: javascript, frontend, security, development
Published: 2023-10-19 20:31:14





## Cross-site Scripting and how to fix it.

![](https://cdn-images-1.medium.com/max/3200/1*rzYYxgOx9J3G1pyWpEauDA.png)

Cross-site scripting (XSS) is the most common form of web application vulnerability.

Cross-site scripting (XSS) is a type of vulnerability that allows attackers to inject malicious code into web applications. XSS attacks present a variety of challenges for both developers and security professionals but they can be prevented by taking steps to prevent attackers from inserting malicious scripts into web applications.

(I would be using Nodejs on the side of the codes, This shouldn’t discourage you if you are using any other backend framework, it still applies to you (not necessarily the terms).

XSS can occur due to many reasons including placing special characters in URLs and HTML forms, sending user input through email or messengers, and even fully injecting malicious code into an existing website.

This can happen on any kind of website that doesn’t control user input. The most common form of XSS exploits can be viewed in different ways: by passing through HTML forms, via email, or by simply visiting compromised websites. XSS is a leading cause of security issues for web applications and servers across internet platforms.

### An Instance of XSS flaws

I created a simple form with just Html and CSS that displays what happens in a web application that is prone to cross-site scripting. An attacker attaches a script tag to the text area of the form.

**An Instance of XSS flaws**

I created a simple form with just Html and CSS that displays what happens in a web application that is prone to cross-site scripting. An attacker attaches a script tag to the text area of the form.

![](https://cdn-images-1.medium.com/max/2000/1*6yk9iXpgFPTS5wIyik1zOQ.gif)

I created a simple form with just Html and CSS that displays what happens in a web application that is prone to cross-site scripting. An attacker attaches a script tag to the text area of the form.

Looking at this form, you see I inputted an event listener (`onmouseover`) which gets triggered once the user hovers over the HTML tag. It triggers the alert function with the text “Wuff”. This is just a simple code that runs on a web browser on a site that’s prone to cross-site scripting. In some cases where there is authentication in play, an attacker can input codes that can extract the cookies of the user where the session is stored which keeps the user authenticated and could use the user’s cookies to impersonate the user.

## How to Prevent XSS

To keep yourself safe from XSS, you must sanitize your input. As you know All XSS attacks affect your website through some form of client-side user input, Your application code should never output data received as input directly to the browser without checking it for malicious code. I will outline how you could fix this:

**Filtering for XSS (Sanitization):**

Filtering for XSS is a security feature that allows you to block malicious content from being displayed on your site. This blocks code from running on the server, preventing website attacks and making it impossible for an attacker to execute malicious code remotely. This filter would remove dangerous keywords, for example, the infamous `<script>` tag, JavaScript commands, CSS styles, and other dangerous HTML markups (such as those that contain event handlers.) You could do that using some server-side (in PHP, ASP, or some other web-enabled development language) codes but I would suggest you use a library to be on the safe side.

If you are using Java, then a good place to go is the [OWASP Java Encoder Project](https://www.owasp.org/index.php/OWASP_Java_Encoder_Project). 
For PHP, there is a comprehensive library called [HTML Purifier](http://htmlpurifier.org/), which boasts strict standards compliance and better features than other filters.

* For Nodejs developers, You could use a [validator](https://www.npmjs.com/package//validator) package. Once you have installed the npm package, You need to require it.

```
const validator = require('validator')

```
Using the `escape()` will replace certain characters (i.e. <, >, /, &, ‘, “) with the corresponding HTML entity.

For instance

```
let userInput = `A XSS hack<**script** onmouseover="alert('Xss');"></**script**>`;

**let** sanitizedInput = validator.escape(userInput);
```

The output is treated by replacing each of the syntaxes with their corresponding HTML entity tag.

XSS flows 

```
&lt;scriptonmouseover=&quot;alert(&#x27;XSShack&#x27;);&quot;&gt;&lt;&#x2F;script&gt;
```

**Restrict User Input:**

Restrict the type of input a user can submit in your form through validation. For instance, if you have an input field for an email, only allow input with the email format. This way, you minimize the chances of attackers submitting bad data. You can also use the validator package for this. This can be done on the backend still using the validator package.

```
check('username', 'Username must be an email address').isEmail()
```

The above code makes it paramount that the username the user is submitting is an email, else it displays an error message(“Username must be an email address”).

**Implement httpOnly and Secure cookie**

Cookies typically store session identifiers that may offer full access to an account, therefore if a cookie is intercepted, a session can be hijacked by someone who is not the real user but pretending as that user. With this cookie, the attacker can impersonate you on your account and have access to everything you do the user should have.

For this reason, it’s very important to set up the required settings to make cookies more secure and this can be achieved by paying attention to the below two things; The **httpOnly **flag and the **secure **flag.

Here’s an example of an httpOnly implementation in Nodejs using express.

```
**app**.use(**express**.session({

secret: "secret",

cookie: {

httpOnly: true,

secure: true

}

}))
```

(You must have installed the session package and “required” it)

Setting the httpOnly and secure object to true makes the attacker try to access the cookie with the **httpOnly** tag set to true as shown above, they would receive an empty string.

While creating a robust application, You can have a lot of security challenges, so it is necessary to pay attention to all of them since attackers can take advantage of vulnerabilities in your application to inject malicious code into your server, always ensure you sanitize user input.