How to secure websites against vulnerabilities (Backend and Frontend)
Tags: security, angular, node
Published: 2020-08-09 07:50:38

With increase in hacker activities and vulnerabilities in websites. It is necessary to build websites with proper security standards. These security standards are very simple, easy to use and can avoid a host of vulnerabilities.

I was involved in a project where i had to pass a vulnerability test. That is where i learned, the hard way on how they work and how much these headers matter. Of-course you have many ways and i am discussing here only on the vulnerability section. Which is often simple yet many don't understand the importance.

# SSL

First **SSL certificate**. IF you have deployed your application anywhere you would know that a SSL certificate is a basic requirement now and all cloud services provide it by default. Both in **firebase** and in **cloudfront** while you are uploading your build it will ask if you have an SSL certificate or else will give one with **Lets Encrypt** certificate.

A [Lets Encrypt certificate](https://letsencrypt.org/) is an open source SSL and can be used for any website. Thus most of the cloud host providers provide this certificate by default. You can check you SSL certificate in the browser. Below is an image of [firepad](https://firepad.io/), an open source website hosted in firebase with default Lets Encrypt certificate.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/g64xfjibyml08rrmkihg.png)

# But
There are many other kinds of attacks that can occur even if you have SSL. [Man-in-the-middle](https://en.wikipedia.org/wiki/Man-in-the-middle_attack) attacks such as [protocol downgrade attacks](https://en.wikipedia.org/wiki/Protocol_downgrade_attack), [cookie hijacking](https://en.wikipedia.org/wiki/Session_hijacking) and [Click-jacking](https://developer.mozilla.org/en-US/docs/Web/Security/Types_of_attacks#Click-jacking). These are are not sophisticated attacks. They are now a days doing with just a security tool. Thus we will need below security headers in our website (Frontend & Backend) to avoid them.

# X-Frame-Options
[X-Frame-Options](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy) response header can be used to indicate whether or not a browser should be allowed to render a page in a &lt;frame>, &lt;iframe>, &lt;embed> or &lt;object>. Sites can use this to avoid click-jacking attacks, by ensuring that their content is not embedded into other sites.

> **res.setHeader('X-Frame-Options','allow-from url1,url');**

# Content-Security-Policy
[Content-Security-Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy) response header allows web site administrators to control resources the user agent is allowed to load for a given page. With a few exceptions, policies mostly involve specifying server origins and script endpoints. This helps guard against cross-site scripting attacks (XSS).

There are tons of conditions you can add in this headers like limiting iframe urls, image urls, etc... Check the link mentioned above for more details.

> **res.setHeader('Content-Security-Policy','frame-src url1, url2');**

# Strict-Transport-Security
[Strict-Transport-Security](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Strict-Transport-Security) response header (HSTS) lets a web site tell browsers that it should only be accessed using HTTPS, instead of using HTTP. It helps to protect websites against man-in-the-middle attacks such as protocol downgrade attacks and cookie hijacking.

> **res.setHeader('Strict-Transport-Security','max-age=63072000; includeSubDomains;');**

# Access-Control-Allow-Origin
[Access-Control-Allow-Origin](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin) response header indicates whether the response can be shared with requesting code from the given origin.

This is used in backend and is very necessary. Assume you have built an API for only example.com. If you dint put this in response headers then practically &lt;any>.com can hit you API and get proper response. Even if its an error response they will be able to get all your other details like response server name, type, traffic details, etc... To avoid such behaviour you can add this in the response header. Once done, if a request comes from &lt;any>.com in the response the browser detects that the &lt;any>.com is not in the cross origin header and will throw cross origin error and no header details will be disclosed.

> **res.setHeader("Access-Control-Allow-Origin","https://www.example.com");**

# Access-Control-Allow-Methods
[Access-Control-Allow-Methods](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Methods) response header specifies the method or methods allowed when accessing the resource in response to a preflight request. This is use to limit the type of HTTP requests the are allowed like POST,PUT,etc.

> **res.setHeader('Access-Control-Allow-Methods', 'POST, GET, OPTIONS')**

# Access-Control-Allow-Headers
[Access-Control-Allow-Headers](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Headers) response header is used in response to a preflight request which includes the Access-Control-Request-Headers to indicate which HTTP headers can be used during the actual request.

> **res.setHeader('Access-Control-Allow-Headers', 'X-Custom-Header, Authorization, Content-Type');**

# WAF
[WAF (Web application firewall)](https://en.wikipedia.org/wiki/Web_application_firewall) is a firewall for cloud applications. Most of the cloud services provide WAF as a service. It is simple and they even have a dashboard to track all items. 
> **Where & Why do we need this ?**
This is necessary for applications that handle lot of private information like banking. If you are developing any such service this will help a lot. It will handle most the heavy weight security scanning and threat identification. You might have to give your API backend endpoint to them tats it.

> **What will it do?**
It will basically act as a scanner for all you requests and responses. It verifies if any malicious activity takes place and reports to you.

# Examples
Below i have given example on how i did it in NodeJS with [expressjs](https://expressjs.com/). Its dead simple. In expressjs there is a concept called [middlewares](https://expressjs.com/en/guide/writing-middleware.html). They will practically act as callback functions that are called before request is sent to its respective API. Thus i set such a function and add response headers.

```
var express = require('express')
var app = express()

/* The middleware headers */
var setResponseHeaders = function (req, res, next) {
  res.setHeader("Access-Control-Allow-Origin","https://www.example.com");
  res.setHeader('Access-Control-Allow-Headers', 'X-Custom-Header, Authorization, Content-Type');
  res.setHeader('Access-Control-Allow-Methods', 'POST, GET, OPTIONS');
  res.setHeader('Strict-Transport-Security','max-age=63072000; includeSubDomains;');
  res.setHeader('Content-Security-Policy','frame-
src http://www.thirdpartyurl.com');
  res.setHeader('X-Frame-Options','allow-from http://www.thirdpartyurl.com');
  next()
}

/* Mention the middleware */
app.use(setResponseHeaders)

/* API */
app.get('/', function (req, res) {
  res.send('Hello World!')
})

app.listen(3000)
```

For frontend i had hosted in cloudfront and its a little work to do. We need to create a lambda function that will act as a middleware and add all the security headers here. I used this article for reference. Complete details with step by step instructions are given. **[https://aws.amazon.com/blogs/networking-and-content-delivery/adding-http-security-headers-using-lambdaedge-and-amazon-cloudfront/](https://aws.amazon.com/blogs/networking-and-content-delivery/adding-http-security-headers-using-lambdaedge-and-amazon-cloudfront/)**


**Hope it helps**. I would love to hear more approaches and techniques used out there. Let me know in the comments.