How to secure your website against Cookies theft and Cross Site Scripting
Tags: security, javascript, html, webdev
Published: 2021-04-10 03:56:28

> 30% of web applications are vulnerable to XSS.
>
> Source: [Acunetix vulnerability report 2019](https://www.acunetix.com/white-papers/acunetix-web-application-vulnerability-report-2019/)



Our dependency on the Internet has increased multifold over the last decade. Today we use internet for anything and everything from buying products off the e-commerce platforms to transferring money across boundaries and much more. 

Needless to say, as Developers, it becomes important to save customers from online frauds. One security breach incident can impact your website's brand and reputation.

In this article, we will learn about Cookies theft and Cross Site Scripting(XSS). Post that, we will learn how to secure our websites and user data against these attacks.

Now, before we find ways to prevent cookies theft, let's understand what Cookies are and how they are used.  

----

## What are Cookies?

Cookies are a small piece of data that your computer stores when you visit a website. It is used to store your interactions with the website that you are on. Some of the primary uses are listed below:

- Tracking your browsing history to serve targeted ads.
- Persistent login credentials
- Persistent shopping cart items in e-commerce sites
- Track unique visits on websites

By now you must have got an idea about the gravity of the situation in case someone steals them. At the same time, you must be thinking why to save the my personal data in cookies at all if it is prone to thefts?

## Why use Cookies?

Let's say you visit orderPizza.com to order a Pizza. The site asks you to login to your account and stores the login credentials in the cookies. 

When you navigate to another page on the website, for example, orderPizza.com/pineapple, the website will check the cookies to see if the user login information is stored in the computer. 
If it is, you will not have to re-authenticate yourself when you navigate to different parts of the website. Pretty convenient, right!


## What is Cookies theft?

As the name suggests, cookies theft is when a hacker gets hold of your personal cookies. 
 
In our example, you stored your login information for orderPizza.com website. 
Once they steal the cookies, they can load it in their browser and impersonate you. 

They can then login to orderPizza.com as you, use your credit card details to order as many pizza as they like to their address. 

While this example may look harmless, imagine if it was not orderPizza.com but your internet banking site! 

Cross Site scripting(XSS) is one of the most common way to steal cookies of your computer and yes, we are going to talk about it next.

----

# How Cross Site scripting(XSS) is used to steal cookies

**Cross site scripting(XSS)** is a web security vulnerability which allows the hackers to execute malicious code inside user's browser. 

It bypasses the "same origin policy" by injecting the code into the server through **user input fields**. Once the code is in the server and requested by the user, the browser is tricked into assuming that this malicious code is coming from the trusted web server of orderPizza.com when in reality, it is not.

According to The Open Web Application Security Project® ([OWASP](https://owasp.org/)) which is a non profit organization dedicated to web application security, XSS  is among the top 10 critical attacks on the internet. 

Let's see XSS in action to understand it better.

Say you can add reviews for each type of Pizza on orderPizza.com website. Here's how the attack will unfold:

- The attacker will slide a malicious code through the 'add reviews' input text field which would look something like this. 
```
Pizza is <script>alert("you are hacked!")</script> delicious
```
- The server assuming that it is a review, will save it in the database and will serve it upon request.
```
let latestReview = document.getElementById('latest-review')
latestReview.innerHTML = Pizza is <script>alert("you are hacked!")</script> delicious
```
- Another user when requests the reviews page, the web server will serve all the user reviews including the malicious one. This will activate the code inside the `script` tag
- Once the code is activated, it can do whatever it wants. Based on what's inside the `script` tags, it can steal cookies which may have your login credentials to the website.

Once the attacker obtains your cookies, they can load those cookies to their browser and pose themselves as you to carry out fraudulent activities.

**Note:** HTML5 doesn't allow to execute `<script>` tag inserted with innerHTML. However the hackers have found a way to bypass this. See the code below:

```
<img src='wrongLocation.jpg' onError='alert("You're hacked")'>
```
innerHTML will allow the above code to run and this way the hackers can infiltrate and steal data. 

----

## How to prevent cookies theft and XSS attacks


### 1. Use secure https connection

When a user opens a website, a web connection is established between user's browser and your web server. Data continues to flow to and from your web server for as long as the connection is open.

If you use the `http` connection for data transfer, the data is prone to theft because using http, data is transferred in plain text format. So if a hacker intercepts that data, they can read and use it for their advantage. This process of intercepting data is called **packet sniffing**.

On the other hand, `https` is a **secure http** connection which encrypts the data before sending it. So even if it is intercepted along the way, the hacker won't be able to decrypt it and make sense of the data. 

### 2. Implement Content Security Policy(CSP) 

According to MDN:

> Content Security Policy (CSP) is an added layer of security that helps to detect and mitigate certain types of attacks, including Cross Site Scripting (XSS) and data injection attacks. 

CSP allows you to create a set of rules that would control what browsers can do with your website. For example, you can direct the browser to run scripts from a specific location. 
This will block all the scripts with malicious intent and mitigate the XSS attacks to a great extent.

As a server administrator, you can configure the policy by adding the Content Security Policy HTTP header to your website. 

Let's see a few examples to understand the rules a little better:

- Allow all scripts from only the origin website

`Content-Security-Policy: script-src 'self' `

- Allow all scripts from the origin and trsutedSite.com domain

`Content-Security-Policy: script-src 'self' https://trsutedSite.com
`

There are other directives like `image-src` or `style-src` which specify permitted sources for loading images and css stylesheets respectively.

For an in-depth understanding of the CSP, you can visit the MDN page [here](https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP) which explains it in great detail.


### 3. Use textContent instead of innerHTML

Let's look at the malicious code again which was added as a review to 'orderPizza.com'
```
let latestReview = document.getElementById('latest-review')
latestReview.innerHTML = Pizza is <img src='wrongLocation.jpg' onError='alert("You're hacked")'> delicious!!
```
Once the hacker hits 'submit review' button, the review will be stored in the database and served on the screen as the new review. 
Now if you use `innerHTML` to output the review, the user input will be parsed as HTML and for the above example you will get an alert box. 

Instead if you use `textContent`, the user input will be parsed as a plain string and not HTML so the new review will be added with this content:

`"Pizza is <img src='wrongLocation.jpg' onError='alert("You're hacked")'> delicious!!"`

And that's how you secure your website! 💪💪💪

### 4. Invest in Web Security tools

Web security is a huge undertaking so if you do not feel very confident about managing it on your own, it is always a good idea to invest in a good web security tool that can protect your website against incoming attacks. 

### 5. Use modern frameworks and update them regularly

Using frameworks is an important part of development process now and rightly so. It offers an organized approach to writing and maintaining code, enhances application performance, gives out of the box functionality and the list goes on.

But it doesn't stop there. Modern frameworks like React, Angular for front end web development also offer rich security measures which prevents the websites from malicious attacks to a great extent. 

They come with a built in mechanism to detect XSS attacks for example and sanitize data before it is stored in server. The implementation and security features may differ between frameworks but they do the job just fine.

That's why it becomes important that you use well supported frameworks during the development process and make sure to update them on a periodic basis. The teams developing these frameworks update the packages on a regular basis to find loopholes or backdoor entries and build stronger security , among other things.

---

## Conclusion

Cross Site scripting(XSS) attacks are major web security vulnerabilities that bypasses the same origin policy rule to inject malicious code into your website. These attacks poses a major risk to user's personal information, authentication details which is generally stored in browser/computer cookies.

Using https secure connection, having a strong Content Security Policy in place alongside other measures can mitigate these risks and make your website more secure than ever.

---

And this brings me to the end of the article. 
 
I hope this article helps strengthen your website security further. As always my comment section is open for feedbacks. Keep them coming. 🤗🤗
I can be found on [LinkedIn](https://in.linkedin.com/in/nayak-rahul) or [Twitter](https://twitter.com/RhlNyk) if you want to connect. 🙂

Until next time! ✌️✌️

Photo credit goes to [FLY:D](https://unsplash.com/@flyd2069?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText) on [Unsplash](https://unsplash.com/s/photos/security?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText)