secure-filters

Anti-XSS filters for security

secure-filters

secure-filters is a collection of sanitization functions ("filters") to provide protection against Cross-Site Scripting (XSS) and other injection attacks.

Table of select contents:

About XSS

XSS is the #3 most critical security flaw affecting web applications for 2013, as determined by a broad consensus among OWASP members.

To effectively combat XSS, you must combine input validation with output sanitization. Using one or the other is not sufficient; you must apply both! This module aims to provide only output sanitization since there are plenty of JavaScript modules out there to do the validation part.

Whichever input validation and output sanitization modules you end up using, please review the code carefully and apply your own professional paranoia. Trust, but verify.

You can roll your own input validation or you can use an existing module. Either way, there are many important rules to follow.

This Stack-Overflow thread lists several input validation options specific to node.js.

One of those options is node-validator (NPM, github). It provides an impressive list of chainable validators. In addition to validation, it gives a set of handy sanitization filters.

Validator has an xss() filter function that can strip-out certain common XSS attack-strings. But, use caution: XSS attacks can be so highly obfuscated that they may be able to bypass Validator's detection algorithm. Validator also has a 3rd party express-validate middleware module for use in the popular Express node.js server.

Usage

secure-filters can be used with EJS or as normal functions.

  npm install --save secure-filters

:warning: CAUTION: If the Content-Type HTTP header for your document, or the <meta charset=""> tag (or eqivalent) specifies a non-UTF-8 encoding these filters may not provide adequate protection! Some browsers can treat some characters at Unicode code-points 0x00A0 and above as if they were < if the encoding is not set to UTF-8!

To configure EJS, simply wrap your require('ejs') call. This will import the filters using the names pre-defined by this module.

  var ejs = require('secure-filters').configure(require('ejs'));

Then, within an EJS template:

  <script>
    var config = <%-: config |jsObj%>;
    var userId = parseInt('<%-: userId |js%>',10);
  </script> 
  <a href="/welcome/<%-: userId |uri%>">Welcome <%-: userName |html%></a>
  <br>
  <a href="javascript:activate('<%-: userId |jsAttr%>')">Click here to activate</a>

Rather than importing the pre-defined names we've chosen, here are some other ways to integrate secure-filters with EJS.

As of EJS 0.8.4, you can replace the escape() function during template compilation. This allows <%= %> to be safer than the default.

var escapeHTML = secureFilters.html;
var templateFn = ejs.compile(template, { escape: escapeHTML });

It's possible that the filter names pre-defined by this module interferes with existing filters that you've written. Or, you may wish to import a sub-set of the filters. In which case, you can simply assign properties to the ejs.filters object.

  var secureFilters = require('secure-filters');
  var ejs = require('ejs');
  ejs.filters.secJS = secureFilters.js;
  <script>
    var myStr = "<%-: myVal | secJS %>";
  </script> 

Or, you can namespace using a parametric style, similar to how EJS' pre-defined get:'prop' filter works:

  var secureFilters = require('secure-filters');
  var ejs = require('ejs');
  ejs.filters.sec = function(valcontext) {
    return secureFilters[context](val);
  };
  <script>
    var myStr = "<%-: myVal | sec:'js' %>";
  </script> 

The filter functions are just regular functions and can be used outside of EJS.

  var htmlEscape = require('secure-filters').html;
  var escaped = htmlEscape('"><script>alert(\'pwn\')</script>');
  assert.equal(escaped,
    '&quot;&gt;&lt;script&gt;alert&#40;&#39;pwn&#39;&#41;&lt;&#47;script&gt;');

You can simply include the lib/secure-filters.js file itself to get started.

  <script type="text/javascript" src="path/to/secure-filters.js"></script> 
  <script type="text/javascript">
    var escaped = secureFilters.html(userInput);
    //... 
  </script> 

We've also added AMD module definition to secure-filters.js for use in Require.js and other AMD frameworks. We don't pre-define a name, but suggest that you use 'secure-filters'.

Functions

By convention in the Contexts below, USERINPUT should be replaced with the output of the filter function.

Sanitizes output for HTML element and attribute contexts using entity-encoding.

Contexts:

  <p>Hello, <span id="name">USERINPUT</span></p>
  <div class="USERINPUT"></div>
  <div class='USERINPUT'></div>

:warning: CAUTION: this is not the correct encoding for embedding the contents of a <script> or <style> block (plus other blocks that cannot have entity-encoded characters).

Any character not matched by /[\t\n\v\f\r ,\.0-9A-Z_a-z\-\u00A0-\uFFFF]/ is replaced with an HTML entity. Additionally, characters matched by /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x9F]/ are converted to spaces to avoid browser quirks that interpret these as non-characters.

You might be asking "Why provide html(var)? EJS already does HTML escaping!".

At the time of this writing, EJS doesn't escape the ' (apostrophe) character when using the <%= %> syntax. This can lead to XSS accidents! Consider the template:

  <img src='<%= prefs.avatar %>'>

When given user input x' onerror='alert(1), the above gets rendered as:

  <img src='x' onerror='alert(1)'>

Which will cause the onerror javascript to run. Using this module's filter should prevent this.

  <img src='<%-: prefs.avatar |html%>'>

When given user input x' onerror='alert(1), the above gets rendered as:

  <img src='x&#39; onerror&#61;&#39;alert&#40;1&#41;'>

Which will not run the attacking script.

Sanitizes output for JavaScript string contexts using backslash-encoding.

  <script>
    var singleQuote = 'USERINPUT';
    var doubleQuote = "USERINPUT";
    var anInt = parseInt('USERINPUT', 10);
    var aFloat = parseFloat('USERINPUT');
    var aBool = ('USERINPUT' === 'true');
  </script> 

:warning: CAUTION: you need to always put quotes around the embedded value; don't assume that it's a bare int/float/boolean constant!

:warning: CAUTION: this is not the correct encoding for the entire contents of a <script> block! You need to sanitize each variable in-turn.

Any character not matched by /[,\-\.0-9A-Z_a-z]/ is escaped as \xHH or \uHHHH where H is a hexidecimal digit. The shorter \x form is used for charaters in the 7-bit ASCII range (i.e. code point <= 0x7F).

Sanitizes output for a JavaScript literal in an HTML script context.

  <script>
    var config = USERINPUT;
  </script> 

This function encodes the object with JSON.stringify(), then escapes certain characters. Any character not matched by /[",\-\.0-9:A-Z\[\\\]_a-z{}]/ is escaped consistent with the js(value) escaping above. Additionally, the sub-string ]]> is encoded as \x5D\x5D\x3E to prevent breaking out of CDATA context.

Because < and > are not matched characters, they get encoded as \x3C and \x3E, respectively. This prevents breaking out of a surrounding HTML <script> context.

For example, with a literal object like `{username:'Albert