/helmet

Project in NodeJS for implement the helmet middleware for FCC

Primary LanguageJavaScriptMIT LicenseMIT

Applied InfoSec Challenges for FCC project part 1

=============================================

GitHub package.json version GitHub package.json dependency version express GitHub package.json dependency version helmet Last commit Website MIT License Twitter Follow Workflow badge PRs Welcome

Created from the FCC repository, to compile the lessons about node, express and helmet.

ko-fi

Start with an empty repository and making the git init as follows:

git init
git clone https://github.com/Estebmaister/helmet.git

Adding the files from the original repo in FCC and start to coding.

Scripts

To install all the dependencies :

npm install

To run the server

npm start

Challenges

Table of Contents

  1. Install and Require Helmet
  2. Hide Potentially Dangerous Information Using helmet.hidePoweredBy()
  3. Mitigate the Risk of Clickjacking with helmet.frameguard()
  4. Mitigate the Risk of Cross Site Scripting (XSS) Attacks with helmet.xssFilter()
  5. Avoid Inferring the Response MIME Type with helmet.noSniff()
  6. Prevent IE from Opening Untrusted HTML with helmet.ieNoOpen()
  7. Ask Browsers to Access Your Site via HTTPS Only with helmet.hsts()
  8. Disable DNS Prefetching with helmet.dnsPrefetchControl()
  9. Disable Client-Side Caching with helmet.noCache()
  10. Information Security with HelmetJS - Set a Content Security Policy with helmet.contentSecurityPolicy()
  11. Configure Helmet Using the 'parent' helmet() Middleware

1. Install and Require Helmet

Helmet helps you secure your Express apps by setting various HTTP headers.

Install the Helmet package, then require it.

npm install helmet --save
  • Added helmet dependency to package.json.
  • Added const helmet = require("helmet"); to myApp.js.

⬆ back to top

2. Hide Potentially Dangerous Information Using helmet.hidePoweredBy()

Hackers can exploit known vulnerabilities in Express/Node if they see that your site is powered by Express. X-Powered-By: Express is sent in every request coming from Express by default. The helmet.hidePoweredBy() middleware will remove the X-Powered-By header. You can also explicitly set the header to something else, to throw people off. e.g. app.use(helmet.hidePoweredBy({ setTo: 'PHP 4.2.0' }))

  • Added to myApp.js app.use(hidePoweredBy({ setTo: "PHP 4.2.0" }));

⬆ back to top

3. Mitigate the Risk of Clickjacking with helmet.frameguard()

Your page could be put in a <frame> or <iframe> without your consent. This can result in clickjacking attacks, among other things. Clickjacking is a technique of tricking a user into interacting with a page different from what the user thinks it is. This can be obtained executing your page in a malicious context, by mean of iframing. In that context a hacker can put a hidden layer over your page. Hidden buttons can be used to run bad scripts. This middleware sets the X-Frame-Options header. It restricts who can put your site in a frame. It has three modes: DENY, SAMEORIGIN, and ALLOW-FROM.

We don’t need our app to be framed.

Use helmet.frameguard() passing with the configuration object {action: 'deny'}.

  • Added to myApp.js app.use(frameguard({ action: "deny" }));

⬆ back to top

4. Mitigate the Risk of Cross Site Scripting (XSS) Attacks with helmet.xssFilter()

Cross-site scripting (XSS) is a frequent type of attack where malicious scripts are injected into vulnerable pages, with the purpose of stealing sensitive data like session cookies, or passwords.

The basic rule to lower the risk of an XSS attack is simple: “Never trust user’s input”. As a developer you should always sanitize all the input coming from the outside. This includes data coming from forms, GET query urls, and even from POST bodies. Sanitizing means that you should find and encode the characters that may be dangerous e.g. <, >. More Info here.

Modern browsers can help mitigating the risk by adopting better software strategies. Often these are configurable via http headers.

The X-XSS-Protection HTTP header is a basic protection. The browser detects a potential injected script using a heuristic filter. If the header is enabled, the browser changes the script code, neutralizing it.

It still has limited support.

  • Added to myApp.js app.use(helmet.xssFilter());

⬆ back to top

5. Avoid Inferring the Response MIME Type with helmet.noSniff()

Browsers can use content or MIME sniffing to adapt to different datatypes coming from a response. They override the Content-Type headers to guess and process the data. While this can be convenient in some scenarios, it can also lead to some dangerous attacks. This middleware sets the X-Content-Type-Options header to nosniff. This instructs the browser to not bypass the provided Content-Type.

  • Added to myApp.js app.use(helmet.noSniff());

⬆ back to top

6. Prevent IE from Opening Untrusted HTML with helmet.ieNoOpen()

Some web applications will serve untrusted HTML for download. Some versions of Internet Explorer by default open those HTML files in the context of your site. This means that an untrusted HTML page could start doing bad things in the context of your pages. This middleware sets the X-Download-Options header to noopen. This will prevent IE users from executing downloads in the trusted site’s context.

  • Added to myApp.js app.use(helmet.ieNoOpen());

⬆ back to top

7. Ask Browsers to Access Your Site via HTTPS Only with helmet.hsts()

HTTP Strict Transport Security (HSTS) is a web security policy which helps to protect websites against protocol downgrade attacks and cookie hijacking. If your website can be accessed via HTTPS you can ask user’s browsers to avoid using insecure HTTP. By setting the header Strict-Transport-Security, you tell the browsers to use HTTPS for the future requests in a specified amount of time. This will work for the requests coming after the initial request.

Configure helmet.hsts() to use HTTPS for the next 90 days. Pass the config object {maxAge: timeInSeconds, force: true}. Glitch already has hsts enabled. To override its settings you need to set the field "force" to true in the config object. We will intercept and restore the Glitch header, after inspecting it for testing.

  • Added to myApp.js:
const ninetyDaysInSeconds = 90 * 24 * 60 * 60;

app.use(helmet.hsts({ maxAge: ninetyDaysInSeconds, force: true }));

Note: Configuring HTTPS on a custom website requires the acquisition of a domain, and a SSL/TSL Certificate.

⬆ back to top

8. Disable DNS Prefetching with helmet.dnsPrefetchControl()

To improve performance, most browsers prefetch DNS records for the links in a page. In that way the destination ip is already known when the user clicks on a link. This may lead to over-use of the DNS service (if you own a big website, visited by millions people…), privacy issues (one eavesdropper could infer that you are on a certain page), or page statistics alteration (some links may appear visited even if they are not). If you have high security needs you can disable DNS prefetching, at the cost of a performance penalty.

  • Added to myApp.js app.use(helmet.dnsPrefetchControl());

⬆ back to top

9. Disable Client-Side Caching with helmet.noCache()

If you are releasing an update for your website, and you want the users to always download the newer version, you can (try to) disable caching on client’s browser. It can be useful in development too. Caching has performance benefits, which you will lose, so only use this option when there is a real need.

  • Added to myApp.js app.use(helmet.noCache()); // Deprecated

  • Cache-Control is a header that has many directives. For example, Cache-Control: max-age=864000 will tell browsers to cache the response for 10 days. In those 10 days, browsers will pull from their caches. Setting this header to Cache-Control: no-store, no-cache, must-revalidate, proxy-revalidate will obliterate caching, as far as this header is concerned.

  • Surrogate-Control is another header that CDNs respect. You can use it to tell intermediate caches to eschew caching.

  • Pragma is a legacy HTTP header. Setting Pragma: no-cache will tell supported browsers to stop caching the response. It has fewer features than Cache-Control but it can better support old browsers.

  • Expires specifies when the content should be considered out of date, or expired. Setting this to 0 will tell browsers the content expires immediately. In other words, they shouldn’t cache it.

nocache is a relatively simple middleware that will set the four HTTP headers noted above: Cache-Control, Surrogate-Control, Pragma, and Expires.

// Make sure you run "npm install nocache" to get the nocache package.
const noCache = require("nocache");

app.use(noCache());

This header is not included in the default Helmet bundle, and will be removed in future versions of Helmet.

⬆ back to top

10. Information Security with HelmetJS - Set a Content Security Policy with helmet.contentSecurityPolicy()

This challenge highlights one promising new defense that can significantly reduce the risk and impact of many type of attacks in modern browsers. By setting and configuring a Content Security Policy you can prevent the injection of anything unintended into your page. This will protect your app from XSS vulnerabilities, undesired tracking, malicious frames, and much more. CSP works by defining a whitelist of content sources which are trusted. You can configure them for each kind of resource a web page may need (scripts, stylesheets, fonts, frames, media, and so on…). There are multiple directives available, so a website owner can have a granular control. See HTML 5 Rocks, KeyCDN for more details. Unfortunately CSP is unsupported by older browser.

By default, directives are wide open, so it’s important to set the defaultSrc directive as a fallback. Helmet supports both defaultSrc and default-src naming styles. The fallback applies for most of the unspecified directives.

In this exercise, use helmet.contentSecurityPolicy(), and configure it setting the defaultSrc directive to ["'self'"] (the list of allowed sources must be in an array), in order to trust only your website address by default. Set also the scriptSrc directive so that you will allow scripts to be downloaded from your website, and from the domain 'trusted-cdn.com'.

Hint: in the self keyword, the single quotes are part of the keyword itself, so it needs to be enclosed in double quotes to be working.

  • Added to myApp.js:
app.use(
  helmet.contentSecurityPolicy({
    directives: {
      defaultSrc: ["'self'"],
      scriptSrc: ["'self'", "trusted-cdn.com"],
    },
  })
);

⬆ back to top

11. Configure Helmet Using the 'parent' helmet() Middleware

app.use(helmet()) will automatically include all the middleware introduced above, except noCache(), and contentSecurityPolicy(), but these can be enabled if necessary. You can also disable or configure any other middleware individually, using a configuration object.

Example:

app.use(
  helmet({
    frameguard: {
      // configure
      action: "deny",
    },
    contentSecurityPolicy: {
      // enable and configure
      directives: {
        defaultSrc: ["self"],
        styleSrc: ["style.com"],
      },
    },
    dnsPrefetchControl: false, // disable
  })
);

We introduced each middleware separately for teaching purposes and for ease of testing. Using the ‘parent’ helmet() middleware is easy to implement in a real project.

Helmet is a collection of 12 smaller middleware functions that set HTTP response headers. Running app.use(helmet()) will not include all of these middleware functions by default.

Module Default?
contentSecurityPolicy for setting Content Security Policy
crossdomain for handling Adobe products' crossdomain requests
dnsPrefetchControl controls browser DNS prefetching
expectCt for handling Certificate Transparency
featurePolicy to limit your site's features
frameguard to prevent clickjacking
hidePoweredBy to remove the X-Powered-By header
hsts for HTTP Strict Transport Security
ieNoOpen sets X-Download-Options for IE8+
noSniff to keep clients from sniffing the MIME type
referrerPolicy to hide the Referer header
xssFilter adds some small XSS protections

You can see more in the documentation.

⬆ back to top