Anti-XSS filters for security
npm install secure-filterssecure-filters is a collection of Output Sanitization functions ("filters")
to provide protection against Cross-Site Scripting
(XSS) and other
injection attacks.

- About XSS
- Usage
- Installation - npm install --save secure-filters
- EJS
- Normal functions
- Client-side
- Functions
- html(value) - Sanitizes HTML contexts using entity-encoding.
- js(value) - Sanitizes JavaScript string contexts using backslash-encoding.
- jsObj(value) - Sanitizes JavaScript literals (numbers, strings,
booleans, arrays, and objects) for inclusion in an HTML script context.
- jsAttr(value) - Sanitizes JavaScript string contexts _in an HTML attribute_
using a combination of entity- and backslash-encoding.
- uri(value) - Sanitizes URI contexts using percent-encoding.
- css(value) - Sanitizes CSS contexts using backslash-encoding.
- style(value) - Sanitizes CSS contexts _in an HTML style attribute_
- Contributing
- Support
- Legal
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!** Also, simple validations like string length aren't as effective; it's
much safer to use _whitelist-based validation_.
The generally accepted flow in preventing XSS looks like this:
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.
secure-filters doesn't deal with Input Validation, only Ouput Sanitization.
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. Validator also has a 3rd party
express-validate middleware
module for use in the popular Express node.js server.
Input Validation can be specialized to the data format. For example, the
jsonschema module (NPM,
github) can be useful for providing
strict validation of JSON documents (e.g. bodies in HTTP).
Output Sanitization (also known as Ouput Filtering) is what secure-filters is
responsible for.
In order to properly santize output you need to be sensitive to the _context_
in which the data is being output. For example, if you want to place text in an
HTML document, you should HTML-escape the text.
But what about CSS or JavaScript contexts? You can't use the HTML-escape
filter; a different escaping method is necessary. If the filter doesn't match
the context, it's possible for browsers to misinterpret the result, which can
lead to XSS attacks!
secure-filters aims to provide the filter functions necessary to do this type
of context-sensitive sanitization.
"Sanitization" is an overloaded term and can be confused with other security
techniques.
For example, if you need to store and sanitize HTML, you'd want to parse,
validate and sanitize that HTML in one hybridized step. There are tools like
Google Caja to do HTML sanitization.
The sanitizer module
packages-up Caja for node.js/CommonJS usage.
secure-filters can be used with EJS or as normal functions.
``sh`
npm install --save secure-filters
:warning: CAUTION: If the Content-Type HTTP header for your document, or
the tag (or eqivalent) specifies a non-UTF-8 encoding these0x00A0
filters _may not provide adequate protection_! Some browsers can treat some
characters at Unicode code-points 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.
`js`
var ejs = require('secure-filters').configure(require('ejs'));
Then, within an EJS template:
`html`
Welcome <%-: userName |html%>
Click here to activate
There's a handy cheat sheet showing all the filters in EJS syntax.
Rather than importing the pre-defined names we've chosen, here are some other
ways to integrate secure-filters with EJS.
#### Replacing EJS's default escape
As of EJS 0.8.4, you can replace the escape() function during template<%= %>
compilation. This allows to be safer than the
default.
`js`
var escapeHTML = secureFilters.html;
var templateFn = ejs.compile(template, { escape: escapeHTML });
#### One-by-one
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.
`js`
var secureFilters = require('secure-filters');
var ejs = require('ejs');
ejs.filters.secJS = secureFilters.js;
`html`
#### Parametric
Or, you can namespace using a parametric style, similar to how EJS' pre-defined
get:'prop' filter works:
`js`
var secureFilters = require('secure-filters');
var ejs = require('ejs');
ejs.filters.sec = function(val, context) {
return secureFilterscontext;
};
`html`
The filter functions are just regular functions and can be used outside of EJS.
`js`
var htmlEscape = require('secure-filters').html;
var escaped = htmlEscape('">');
assert.equal(escaped,
'"><script>alert('pwn')</script>');
You can simply include the lib/secure-filters.js file itself to get started.
`html`
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'.
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:
` Hello, USERINPUThtml`
:warning: CAUTION: this is not the correct encoding for embedding the contents of
a
`
: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
`
This function escapes certain characters within a JSON string. Any character
not matched by /[",\-\.0-9:A-Z\[\\\]_a-z{}]/ is escaped consistent with thejs(value) escaping above. Additionally, the sub-string ]]> is\x5D\x5D\x3E
encoded as 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
`
Sanitizes output for a JavaScript literal in an HTML script context.
`html`
This function encodes the object with JSON.stringify(), thenjson()
escapes using detailed above.
For example, with a literal object like {username:'Albert
`
#### JSON is not a subset of JavaScript
Article: JSON isn't a JavaScript
Subset.
JSON is _almost_ a subset of JavaScript, but for two characters: LINE
SEPARATOR U+2028
and PARAGRAPH SEPARATOR. These
U+2029
two characters can't legally appear in JavaScript strings and must be escaped.
Due to the ambiguity of these and other Unicode whitespace characters,
secure-filters will backslash encode U+2028 as \u2028, U+2029 as \u2029,
etc.
Sanitizes output for embedded HTML scripting attributes using a special
combination of backslash- and entity-encoding.
`html`
click to activate
The string is escaped to <ha>, \'ha\',
\"ha\". Note the backslashes before the apostrophe and quote
entities.
Sanitizes output in URI component contexts by using percent-encoding.
The ranges 0-9, A-Z, a-z, plus hypen, dot and underscore (-._) are
preserved. Every other character is converted to UTF-8, then output as %XX
percent-encoded octets, where X is an uppercase hexidecimal digit.
Note that if composing a URL, the entire result should ideally be
HTML-escaped before insertion into HTML. However, since Percent-encoding is
also HTML-safe, it may be sufficient to just URI-encode the untrusted
components if you know the rest is application-supplied.
Sanitizes output in CSS contexts by using backslash encoding.
`html`
:warning: CAUTION this is not the correct filter for a style="" attribute; usestyle(value)
the filter instead!
:warning: CAUTION even though this module prevents breaking out of CSS
context, it is still somewhat risky to allow user-controlled input into CSS and