3

API with NestJS #145. Securing applications with Helmet

 6 months ago
source link: https://wanago.io/2024/02/12/api-nestjs-helmet-security/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

API with NestJS #145. Securing applications with Helmet

NestJS

February 12, 2024

This entry is part 145 of 145 in the API with NestJS

Ensuring that our application is secure is one of the most important things we must do as developers. One of the ways to protect our application from well-known vulnerabilities is to set appropriate response headers. There are quite a lot of different security-related response headers to consider. Fortunately, the helmet library can set them for us.

Helmet maintains a set of various response headers that aim to make applications more secure. When we look at their changelog, we can see that the maintainers keep the list of headers up to date by adding new ones and deprecating headers that are no longer necessary.

In this article, we learn how to use the helmet library with NestJS and its advantages.

Using the Helmet library with NestJS

To use Helmet with NestJS, we first need to install it.

npm install helmet

We can now use it in our bootstrap function.

main.ts
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import helmet from 'helmet';
async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.use(helmet());
  await app.listen(3000);
bootstrap();

Now, when we make a request to our API, we can see that it responds with various new headers. Let’s go through them.

Screenshot-from-2024-02-10-22-09-48.png

Content-Security-Policy

When a cross-site scripting (XSS) attack occurs, the attacker injects malicious code into our application. This often involves JavaScript code that can harm our users, for example, by stealing their cookies.

The person carrying out the XSS attack takes advantage of the browser’s inability to distinguish between a script that is part of our application and one that the attacker adds. By setting up a Content-Security-Policy header, we can specify what resources the browser can load and execute and avoid the others.

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

For example, script-src 'self' tells the browser not to load any scripts from origins different than the opened page. It also prevents all inline scripts and inline event handlers from running.

If you want to know more about origins and Cross-Origin Resource Sharing (CORS), check out API with NestJS #117. CORS – Cross-Origin Resource Sharing.

There are many other rules besides script-src that Helmet sets by default, such as:

default-src 'self';
base-uri 'self';
font-src 'self' https: data:;
form-action 'self';
frame-ancestors 'self';
img-src 'self' data:;
object-src 'none';
script-src 'self';
script-src-attr 'none';
style-src 'self' https: 'unsafe-inline';
upgrade-insecure-requests;

If you want to know more about them, read the article that covers the Content-Security-Policy in depth: Fighting cross-site-scripting (XSS) with content security policy.

Cross-Origin-Opener-Policy

In modern web development, websites often interact with resources from multiple origins. While this is a useful feature, it also opens up security risks.

For example, one website can open another using the window.open function. The newly opened website can then access the window object of the website that opened it through the window.opener property.

Thanks to Helmet setting the Cross-Origin-Opener-Policy header to same-origin, we isolate the browsing context. Then, the window.opener property is not available if both websites don’t have the same origin.

Cross-Origin-Resource-Policy

When a website requests resources from a different origin, it is considered a cross-origin request. Browsers implement a same-origin policy to restrict such requests. The same-origin policy allows a website to access data from another page only if both have the same origin.

We can alter this behavior through Cross-Origin Resource Sharing.

However, the same-origin policy does not prevent the browser from embedding resources from other origins. For example, it can display images using the <img> tag or play media using <video> even if those resources come from other origins. The Helmet library disallows other origins from embedding our resources by setting Cross-Origin-Resource-Policy to same-origin.

Origin-Agent-Cluster

Traditionally, browsers group websites by their origin to decide how much they should trust and isolate them. The Origin-Agent-Cluster response header is a relatively new feature that tells the browser to give a website its own resources like memory and processing power. It hints that our origin would benefit from dedicated resources and helps the browser prioritize allocating them. However, we give up a few features in exchange.

Referrer-Policy

When a browser makes an HTTP request, it includes the page’s address in the Referer request header. While it might be helpful for analytics, it might also lead to malicious tracking and leaking information.

Interestingly, Referer is a typo of the word “referrer”.

By setting the Referrer-Policy header to no-referrer, the Helmet library ensures that the browser removes the Referer header completely.

Strict-Transport-Security

Whenever we visit a website using the HTTPS protocol, and the server responds with the Strict-Transport-Security header, the browser remembers it. If we try accessing this site using HTTP, we’re automatically redirected to HTTPS instead.

This can help prevent man-in-the-middle attacks where the hacker can intercept our HTTP request and redirect us to a fake version of the site we want to visit. This could result in revealing sensitive information. However, if the website uses the Strict-Transport-Security header, the described situation can’t happen if we’ve been to the real site at least once before.

If you want to know more, check out Preventing man-in-the-middle attacks with Strict Transport Security.

X-Content-Type-Options

Websites can tell the browser to download various resources, like stylesheets, images, and JavaScript files. Each one should have a Content-Type response header. For instance, a correct header value could be text/css or image/png.

Sometimes, the Content-Type might be incorrect or missing from the response. When this happens, the browser can try to figure out the correct MIME type of the resource by itself through MIME sniffing. This can lead to issues. For instance, if our site lets users upload data to the server, an attacker could upload an HTML file but label it as image/png. When other users download and open this file, it could set the stage for an XSS (Cross-Site Scripting) attack.

Fortunately, the Helmet library sets the X-Content-Type-Option response header to nosniff. This stops the browser from inspecting the file if the MIME type is missing. Therefore, always ensuring we send the correct Content-Type response header is crucial.

If you would like to read more, go to Countering MIME sniffing with X-Content-Type-Options and Content-Type headers.

X-Download-Options

Using the Helmet middleware offers enhancements even for Internet Explorer 8. It is a problem when an IE8 user downloads an HTML file and opens it directly rather than saving it first. This causes the browser to execute the HTML file in the context of the website it was downloaded from.

By setting the X-Download-Options header to noopen, the Helmet library prevents Internet Explorer 8 from opening a file directly before saving it.

X-DNS-Prefetch-Control

Browsers send DNS queries to translate a domain name into an IP address. Although DNS requests use minimal bandwidth, the delay they cause can add up. If we can anticipate which hostnames we’ll need, we can look them up in advance to save time.

<link rel="dns-prefetch" href="https://wanago.io">

Unfortunately, some attackers might take advantage of the DNS prefetching. The Helmet library turns it off by sending the X-DNS-Prefetch-Control response header set to off.

X-Frame-Options

Clickjacking is an attack that makes use of iframes. Picture an attacker setting up a website with various buttons. Over these buttons, they overlay a transparent iframe that displays another page.

The attacker aligns the invisible iframe with the buttons. When the user attempts to click on them, they actually end up clicking on the invisible buttons within the iframe. This action hijacks the user’s click, which is called clickjacking.

Using the X-Frame-Options header, we can control whether the browser can render a page in an iframe. Helmet, by default, sets the header’s value to SAMEORIGIN. This tells the browser to allow the page to be displayed in an iframe only on websites with the same origin.

If you want to know more about clickjacking, check out The danger of iframe clickjacking and how to deal with it

X-Permitted-Cross-Domain-Policies

Programs like Adobe Flash Player and Adobe Acrobat can include website content in documents. By default, they block all cross-domain requests similarly to browsers. This behavior can be changed by supplying a prepared crossdomain.xml policy file. If an attacker manages to insert it, it can modify the cross-domain policy for certain Adobe products.

The Helmet library sets the X-Permitted-Cross-Domain-Policies response header to none and disallows the crossdomain.xml files.

X-XSS-Protection

The X-XSS-Protection header is a feature of browsers that prevents a page from loading if the browser detects the XSS attack. However, this feature has become obsolete, particularly with adopting the Content-Security-Policy header, which provides a more effective way to handle such security risks.

Additionally, it was found that the X-XSS-Protection feature could introduce certain problems. Therefore, the Helmet library sets X-XSS-Protection to to disable it.

X-Powered-By

The X-Powered-By response header specifies the technology our application uses under the hood. Since NestJS uses Express by default, all our endpoints respond with X-Powered-By: Express.

While security by obscurity is not enough to keep our application safe, some people believe it is not a good idea to let potential attackers know that we are using Express. Because of that, the Helmet library removes the X-Powered-By header.

Summary

In this article, we’ve gone through the Helmet library by explaining how to use it in our NestJS project and what advantages it gives us. Helmet enhances web application security by setting various HTTP headers that can help protect against a range of web vulnerabilities such as Cross-Site Scripting (XSS), clickjacking, and other exploits. Most of the headers set by Helmet are especially useful when we use NestJS to serve a website. However, headers such as Strict-Transport-Security or X-Content-Type-Options can be helpful if we develop a REST API.

Incorporating Helmet into your NestJS projects, whether for serving websites or API development, significantly boosts our application’s defense against common security threats.

Series Navigation<< API with NestJS #144. Creating CLI applications with the Nest Commander


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK