Sitemap

Securing Node Web Applications

Introduction

6 min readFeb 29, 2016

--

This article illustrates how to resolve some of the most common security threats to Node.js web applications as identified by this OWASP article:

https://speakerdeck.com/ckarande/top-overlooked-security-threats-to-node-dot-js-web-applications

Many of these issues can be addressed by using the Helmet middleware library (https://www.npmjs.com/package/helmet), so code examples are provided for “standard” Express applications, and for applications where Helmet is being used.

1. Remove X-Powered-By Header

The X-Powered-By header (set to “Express” by default in a Node / Express application) can be used by attackers to identify the site’s infrastructure and should therefore be hidden.

In a standard Express application, this is as simple as this:

app.disable( 'x-powered-by' ) ;

When using Helmet:

app.use( helmet.hidePoweredBy() ) ;

2. Default Session Cookie Name

Some frameworks will give the session cookie a name that helps to identify the framework in question, again this should be hidden by giving it a generic name e.g. “sessionid”:

var session = require( 'express-session' ) ;app.use( session( {
secret: 'super-duper-unguessable-secret-key’,
key: 'sessionid'
} ) ) ;

3. Protection Against CSRF

What is CSRF: https://en.wikipedia.org/wiki/Cross-site_request_forgery

Protection can be implemented using the csurf middleware:

Command Line

npm install csurf — save

Application.js

var csrf = require( 'csurf' ) ;
app.use( csrf() ) ;

Routing

Include the following middleware function before any routing to ensure that it is executed for all requests:

app.use( function( req, res, next ) {
res.locals.csrftoken = req.csrfToken() ;
next() ;
} ) ;

Form Template

Any forms will need to include a hidden CSRF field to allow the POST request to be accepted by the server:

<input type="hidden" name="_csrf" value="{{ csrftoken }}" />

(The syntax for this might vary depending on the templating engine being used.)

Express CSRF middleware does not verify tokens for HTTP GET, OPTIONS and HEAD requests (which is the correct behaviour), so ensure that any GET APIs do not perform any operations that change the underlying data (which they shouldn’t if they are REST compliant).

4. Protection Against XSS

What is XSS: https://en.wikipedia.org/wiki/Cross-site_scripting

Cross-site scripting vulnerabilities can be used to steal session cookies to impersonate users, and to redirect users to malicious sites. Some template libraries handle output encoding by default, but this does not protect fully against XSS attacks, so you should encode all untrusted data depending on the context of where it will be placed.

All encoding should be done using a proven, trusted library e.g. the OWASP Enterprise Security API (ESAPI):

https://github.com/ESAPI/owasp-esapi-js

A Node port of this is available here:

https://github.com/ESAPI/node-esapi

Basic usage:

var ESAPI = require( 'node-esapi' ).encoder() ;
ESAPI.<ENCODER-FUNCTION>( '<OUTPUT-TO-ENCODE>' ) ;

Encoding filters can be added to Nunjucks (my preference of JavaScript templating engine, other templating engines are available) as follows:

main.js

var env = nunjucks.configure( autoescape: false ) ;
env.addFilter( 'encodeForHTML', function( unencoded ) {
return ESAPI.encodeForHTML( unencoded ) ;
} ) ;

and repeat for all other required encoding functions. Note that by default, Nunjucks will attempt to escape output (the autoescape option) — we need to disable if we want to replace it with the ESAPI encoding functions.

template.js

Usage inside a template is then simple:

{% set unencoded = '"This could be any old nonsense!"' %}
<p>{{ unencoded | encodeForHTML }}</p>

Encode For HTML Body

<div>Untrusted Data</div>
  • Encode & as &amp;
  • Encode < as &lt;
  • Encode > as &gt;
  • Encode “ as &quot;
  • Encode ‘ as &#x27;
  • Encode / as &#x2F;

Encode For HTML Attributes

<input type="text" name="forename" value="Untrusted Data" />
  • Encode non-alphanumeric characters as &#xHH; format.
  • Always ensure that attributes are enclosed in quotes.

Encode For CSS

<div style="width: Untrusted Data">contents</div>
  • Encode untrusted data using CSS hex encoding (\HH or \HHHHHH).

Encode For JavaScript

<script>var forename='Untrusted Data' ;</script>
  • Encode non-alphanumeric characters as \uXXXX; unicode format

Encode For URL

<a href="Untrusted Data">Link Text</a>
  • Encode untrusted data using encodeURI().

Encode For URL Parameter

<a href="/details?id=Untrusted Data">Link Text</a>
  • Encode untrusted data using encodeURIComponent().

Encode For DOM-Based XSS

Get Andy Neale’s stories in your inbox

Join Medium for free to get updates from this writer.

Encode on both client and server:

<a href="/list#id=Untrusted Data">Link Text</a><script>
document.write( '<h1>' + document.location.hash + '</h1>' ) ;
</script>

5. Additional Cookie Security

Add HTTPOnly and Secure attributes on session cookies:

var session = require( 'express-session' ) ;app.use( session( {
secret: 'super-duper-uncrackable-secret-key',
key: 'sessionid',
cookie: {
httpOnly: true,
secure: true
}
} ) ) ;

The HTTPOnly flag, if supported by the client browser — and 99% of browsers since 2011 do support it — prevents the cookie from being accessed via client-side scripting, thereby mitigating the risk from XSS attacks. The Secure flag, if supported by the client browser, ensures that the relevant cookie will only be sent over an HTTPS connection — the cookie will not be sent via an unsecured HTTP connection.

6. Content Security Policy

A content security policy specifies authorised sources for page resources (e.g. images and scripts), and prevents a browser from loading resources from unauthorised locations, which helps to block XSS attacks.

https://en.wikipedia.org/wiki/Content_Security_Policy

Using Helmet:

app.use( helmet.csp( {
directives: {
"default-src": [ "'self'" ],
"img-src": [ "static.example.com", "cdn.example.com" ]
}
} ) ) ;

7. Regular Expression Denial of Service (ReDoS) Attack

Regular expressions are executed as blocking operations in Node, and therefore care should be taken to ensure that long-running expressions are avoided.

https://www.owasp.org/index.php/Regular_expression_Denial_of_Service_-_ReDoS

Any regular expressions used should be verified using a tool for detecting vulnerable patterns:

https://www.microsoft.com/en-gb/download/details.aspx?id=20095

http://www.cs.bham.ac.uk/~hxt/research/rxxr.shtml

NEVER accept user inputs as regular expressions.

8. HTTP Pollution Parameter

Supplying multiple instances of an HTTP parameter with the same name can caused unexpected side effects:

GET //search?forename=Andy&forename=Andy

In Node, these multiple responses are concatenated, so (assuming a typical Express application) req.query.forename is now no longer a simple string, but an array:

[ "Andy", "Andy" ]

If your code doesn’t check for this, then type errors could occur — uncaught errors in asynchronous code could crash the Node instance, potentially causing a Denial of Service (DoS) attack.

Your code should always check the expected type as part of the input validation, and ensure robust error handling using try / catch.

Ideally, you should use domains and clusters to create multiple resilient worker processes, and therefore ensure that any untrapped errors do not lead to application failures or DoS problems.

https://nodejs.org/api/domain.html

https://nodejs.org/api/cluster.html

https://gist.github.com/jedi4ever/6079180

http://shapeshed.com/uncaught-exceptions-in-node/

https://gist.github.com/isaacs/5264418

There is a Node module that protects against HTTP parameter solution — called hpp — in a nutshell, this identifies any repeated parameters and only passes the last specified value. Usage is simple:

var bodyparser = require( 'body-parser' ),
hpp = require( 'hpp' ) ;
app.use( bodyparser.urlencoded() ) ;
app.use( hpp() ) ;

9. Protect Against Server-Side JS Injection

When eval(), setTimeout(), setInterval() or Function() (all of which can be used to execute arbitrary pieces of JavaScript code) are used to process user-provided inputs, these can be exploited by an attacker to inject and execute malicious JavaScript code on the server. To avoid this:

  • Validate user inputs server-side before processing.
  • Do NOT use any of the four commands listed to parse user inputs.
  • When parsing JSON input, use JSON.parse() instead of eval().
  • For type conversions, use the appropriate conversion method e.g. parseInt().
  • Include ‘use strict’ at the beginning of all modules or functions to enable strict mode.

10. HTTP Headers

There are a number of security-related headers which can be set easily in Express or Helmet:

Strict-Transport-Security enforces secure (HTTP over SSL/TLS) connections to the server

X-Frame-Options provides clickjacking protection

X-XSS-Protection enables the cross-site scripting (XSS) filter built into most recent web browsers

X-Content-Type-Options prevents browsers from MIME-sniffing a response away from the declared content-type

Express

app.use( function( req, res, next ) {
res.header( 'Strict-Transport-Security', 7776000000 ) ;
res.header( 'X-Frame-Options', 'SAMEORIGIN' ) ;
res.header( 'X-XSS-Protection', 0 ) ;
res.header( 'X-Content-Type-Options', 'nosniff' ) ;
next() ;
} ) ;

Helmet

app.use( helmet.hsts( { maxAge: 7776000000 } ) ) ;
app.use( helmet.frameguard( 'SAMEORIGIN' ) ) ;
app.use( helmet.xssFilter( { setOnOldIE: true } ) ) ;
app.use( helmet.noSniff() ) ;

References

Presentation illustrating the key security threats discussed above:

https://speakerdeck.com/ckarande/top-overlooked-security-threats-to-node-dot-js-web-applications

Excellent tutorial discussing the top 10 security threats as identified by OWASP, and solutions to those issues:

http://nodegoat.herokuapp.com/tutorial

The Node Security Project:

https://nodesecurity.io/

Helmet, a Node package to mitigate a number of security threats, which includes detailed descriptions of both the threats and solutions:

https://www.npmjs.com/package/helmet

A checklist of security issues (and solutions) for Node applications:

https://blog.risingstack.com/node-js-security-checklist/

--

--

Andy Neale
Andy Neale

Written by Andy Neale

Web developer. Currently building web apps in React. Also known to use Node, jQuery, Foundation and more. Frequently covered in cats.