• This repository has been archived on 13/Feb/2022
  • Stars
    star
    138
  • Rank 255,051 (Top 6 %)
  • Language
    JavaScript
  • License
    BSD 3-Clause "New...
  • Created over 10 years ago
  • Updated about 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Anti-XSS Security Filters for EJS and More

secure-filters

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

Build Status

Data Flow Diagram

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! 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:

Data Flow Diagram

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.

Input Validation

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

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.

Hybrid 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.

Usage

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

Installation

  npm install --save secure-filters

⚠️ 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!

General Usage

Cheat Sheet

With EJS

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>

There's a handy cheat sheet showing all the filters in EJS syntax.

Alternative EJS uses.

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.

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.

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

Parametric

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(val, context) {
    return secureFilters[context](val);
  };
  <script>
    var myStr = "<%-: myVal | sec:'js' %>";
  </script>

As Normal Functions

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;');

Client-side

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.

html(value)

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>

⚠️ 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.

A Note About <%= %>

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

Prior to 0.8.5, 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.

js(value)

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>

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

⚠️ 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).

json(value)

Sanitizes output for a JSON string in an HTML script context.

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

This function escapes certain characters within a JSON string. 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 JSON string like '{"username":"Albert </script><script>alert(\"Pwnerton\")"}', json() gives output:

  <script>
    var config = {"username":"\x3C\x2Fscript\x3E\x3Cscript\x3Ealert\x28\"Pwnerton\"\x29"};
  </script>

jsObj(value)

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 using json(value) detailed above.

For example, with a literal object like {username:'Albert </script><script>alert("Pwnerton")'}, jsObj() gives output:

  <script>
    var config = {"username":"\x3C\x2Fscript\x3E\x3Cscript\x3Ealert\x28\"Pwnerton\"\x29"};
  </script>

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 U+2029. These 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.

jsAttr(value)

Sanitizes output for embedded HTML scripting attributes using a special combination of backslash- and entity-encoding.

  <a href="javascript:doActivate('USERINPUT')">click to activate</a>
  <button onclick="display('USERINPUT')">Click To Display</button>

The string <ha>, 'ha', "ha" is escaped to &lt;ha&gt;, \&#39;ha\&#39;, \&quot;ha\&quot;. Note the backslashes before the apostrophe and quote entities.

uri(value)

Sanitizes output in URI component contexts by using percent-encoding.

  <a href="http://example.com/?this=USERINPUT&that=USERINPUT">
  <a href="http://example.com/api/v2/user/USERINPUT">

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.

css(value)

Sanitizes output in CSS contexts by using backslash encoding.

  <style type="text/css">
    #user-USERINPUT {
      background-color: #USERINPUT;
    }
  </style>

⚠️ CAUTION this is not the correct filter for a style="" attribute; use the style(value) filter instead!

⚠️ CAUTION even though this module prevents breaking out of CSS context, it is still somewhat risky to allow user-controlled input into CSS and <style> blocks. Be sure to combine CSS escaping with whitelist-based input sanitization! Here's a small sampling of what's possible:

The ranges a-z, A-Z, 0-9 plus Unicode U+10000 and higher are preserved. All other characters are encoded as \h , where h is one one or more lowercase hexadecimal digits, including the trailing space.

Confusingly, CSS allows NO-BREAK SPACE U+00A0 to be used in an identifier. Because of this confusion, it's possible browsers treat it as whitespace, and so secure-filters escapes it.

Since the behaviour of NUL in CSS2.1 is undefined, it is replaced with \fffd , REPLACEMENT CHARACTER U+FFFD.

For example, the string <wow> becomes \3c wow\3e (note the trailing space).

style(value)

Encodes values for safe embedding in HTML style attribute context.

USAGE: all instances of USERINPUT should be sanitized by this function

  <div style="background-color: #USERINPUT;"></div>

⚠️ CAUTION even though this module prevents breaking out of style-attribute context, it is still somewhat risky to allow user-controlled input (see caveats on css above). Be sure to combine with whitelist-based input sanitization!

Encodes the value first as in the css() filter, then HTML entity-encodes the result.

For example, the string <wow> becomes &#92;3c wow&#92;3e .

Contributing

Please see the Contribution Guide.

Support

Support is provided via github issues.

For responsible disclosures, email Salesforce Security.

Changelog

1.1.0

This release changes the behavior of secure-filters, but should be backwards-compatible with 1.0.5.

  • The js, jsObj and jsAttr filter now use a strict allow-list for characters in strings. This is safer, but does increase the size of these strings slightly. Compliant JSON and JavaScript parsers will not be affected negatively by this change.
  • The example for jsAttr was incorrect. It previously stated that <ha>, 'ha', "ha" was escaped to &lt;ha&gt;, \&#39;ha\&#39;, \&quot;ha\&quot;

1.0.5

  • Vastly improved documentation and illustrations

1.0.4

  • Initial public release

Legal

© 2014 salesforce.com

Licensed under the BSD 3-clause license.

More Repositories

1

LAVIS

LAVIS - A One-stop Library for Language-Vision Intelligence
Jupyter Notebook
8,226
star
2

CodeGen

CodeGen is a family of open-source model for program synthesis. Trained on TPU-v4. Competitive with OpenAI Codex.
Python
4,594
star
3

BLIP

PyTorch code for BLIP: Bootstrapping Language-Image Pre-training for Unified Vision-Language Understanding and Generation
Jupyter Notebook
3,879
star
4

akita

🚀 State Management Tailored-Made for JS Applications
TypeScript
3,442
star
5

Merlion

Merlion: A Machine Learning Framework for Time Series Intelligence
Python
3,232
star
6

ja3

JA3 is a standard for creating SSL client fingerprints in an easy to produce and shareable way.
Python
2,502
star
7

CodeT5

Home of CodeT5: Open Code LLMs for Code Understanding and Generation
Python
2,437
star
8

decaNLP

The Natural Language Decathlon: A Multitask Challenge for NLP
Python
2,301
star
9

TransmogrifAI

TransmogrifAI (pronounced trăns-mŏgˈrə-fī) is an AutoML library for building modular, reusable, strongly typed machine learning workflows on Apache Spark with minimal hand-tuning
Scala
2,227
star
10

policy_sentry

IAM Least Privilege Policy Generator
Python
1,938
star
11

awd-lstm-lm

LSTM and QRNN Language Model Toolkit for PyTorch
Python
1,900
star
12

cloudsplaining

Cloudsplaining is an AWS IAM Security Assessment tool that identifies violations of least privilege and generates a risk-prioritized report.
JavaScript
1,865
star
13

ctrl

Conditional Transformer Language Model for Controllable Generation
Python
1,766
star
14

lwc

⚡️ LWC - A Blazing Fast, Enterprise-Grade Web Components Foundation
JavaScript
1,537
star
15

WikiSQL

A large annotated semantic parsing corpus for developing natural language interfaces.
HTML
1,520
star
16

sloop

Kubernetes History Visualization
Go
1,396
star
17

CodeTF

CodeTF: One-stop Transformer Library for State-of-the-art Code LLM
Python
1,375
star
18

ALBEF

Code for ALBEF: a new vision-language pre-training method
Python
1,276
star
19

pytorch-qrnn

PyTorch implementation of the Quasi-Recurrent Neural Network - up to 16 times faster than NVIDIA's cuDNN LSTM
Python
1,255
star
20

ai-economist

Foundation is a flexible, modular, and composable framework to model socio-economic behaviors and dynamics with both agents and governments. This framework can be used in conjunction with reinforcement learning to learn optimal economic policies, as done by the AI Economist (https://www.einstein.ai/the-ai-economist).
Python
964
star
21

jarm

Python
914
star
22

design-system-react

Salesforce Lightning Design System for React
JavaScript
896
star
23

tough-cookie

RFC6265 Cookies and CookieJar for Node.js
TypeScript
858
star
24

reactive-grpc

Reactive stubs for gRPC
Java
814
star
25

OmniXAI

OmniXAI: A Library for eXplainable AI
Jupyter Notebook
782
star
26

xgen

Salesforce open-source LLMs with 8k sequence length.
Python
704
star
27

vulnreport

Open-source pentesting management and automation platform by Salesforce Product Security
HTML
593
star
28

UniControl

Unified Controllable Visual Generation Model
Python
577
star
29

hassh

HASSH is a network fingerprinting standard which can be used to identify specific Client and Server SSH implementations. The fingerprints can be easily stored, searched and shared in the form of a small MD5 fingerprint.
Python
525
star
30

progen

Official release of the ProGen models
Python
518
star
31

Argus

Time series monitoring and alerting platform.
Java
501
star
32

base-components-recipes

A collection of base component recipes for Lightning Web Components on Salesforce Platform
JavaScript
496
star
33

matchbox

Write PyTorch code at the level of individual examples, then run it efficiently on minibatches.
Python
488
star
34

PCL

PyTorch code for "Prototypical Contrastive Learning of Unsupervised Representations"
Python
483
star
35

cove

Python
470
star
36

CodeRL

This is the official code for the paper CodeRL: Mastering Code Generation through Pretrained Models and Deep Reinforcement Learning (NeurIPS22).
Python
465
star
37

DialogStudio

DialogStudio: Towards Richest and Most Diverse Unified Dataset Collection and Instruction-Aware Models for Conversational AI
Python
431
star
38

warp-drive

Extremely Fast End-to-End Deep Multi-Agent Reinforcement Learning Framework on a GPU (JMLR 2022)
Python
429
star
39

observable-membrane

A Javascript Membrane implementation using Proxies to observe mutation on an object graph
TypeScript
368
star
40

PyRCA

PyRCA: A Python Machine Learning Library for Root Cause Analysis
Python
367
star
41

DeepTime

PyTorch code for Learning Deep Time-index Models for Time Series Forecasting (ICML 2023)
Python
322
star
42

ULIP

Python
316
star
43

logai

LogAI - An open-source library for log analytics and intelligence
Python
298
star
44

MultiHopKG

Multi-hop knowledge graph reasoning learned via policy gradient with reward shaping and action dropout
Jupyter Notebook
290
star
45

CodeGen2

CodeGen2 models for program synthesis
Python
269
star
46

provis

Official code repository of "BERTology Meets Biology: Interpreting Attention in Protein Language Models."
Python
269
star
47

jaxformer

Minimal library to train LLMs on TPU in JAX with pjit().
Python
255
star
48

EDICT

Jupyter Notebook
247
star
49

causalai

Salesforce CausalAI Library: A Fast and Scalable framework for Causal Analysis of Time Series and Tabular Data
Jupyter Notebook
223
star
50

ETSformer

PyTorch code for ETSformer: Exponential Smoothing Transformers for Time-series Forecasting
Python
221
star
51

themify

👨‍🎨 CSS Themes Made Easy. A robust, opinionated solution to manage themes in your web application
TypeScript
216
star
52

rules_spring

Bazel rule for building Spring Boot apps as a deployable jar
Starlark
215
star
53

simpletod

Official repository for "SimpleTOD: A Simple Language Model for Task-Oriented Dialogue"
Python
212
star
54

TabularSemanticParsing

Translating natural language questions to a structured query language
Jupyter Notebook
210
star
55

grpc-java-contrib

Useful extensions for the grpc-java library
Java
208
star
56

GeDi

GeDi: Generative Discriminator Guided Sequence Generation
Python
207
star
57

aws-allowlister

Automatically compile an AWS Service Control Policy that ONLY allows AWS services that are compliant with your preferred compliance frameworks.
Python
207
star
58

mirus

Mirus is a cross data-center data replication tool for Apache Kafka
Java
200
star
59

generic-sidecar-injector

A generic framework for injecting sidecars and related configuration in Kubernetes using Mutating Webhook Admission Controllers
Go
200
star
60

CoST

PyTorch code for CoST: Contrastive Learning of Disentangled Seasonal-Trend Representations for Time Series Forecasting (ICLR 2022)
Python
196
star
61

factCC

Resources for the "Evaluating the Factual Consistency of Abstractive Text Summarization" paper
Python
192
star
62

runway-browser

Interactive visualization framework for Runway models of distributed systems
JavaScript
188
star
63

glad

Global-Locally Self-Attentive Dialogue State Tracker
Python
186
star
64

ALPRO

Align and Prompt: Video-and-Language Pre-training with Entity Prompts
Python
177
star
65

densecap

Jupyter Notebook
176
star
66

cloud-guardrails

Rapidly apply hundreds of security controls in Azure
HCL
174
star
67

booksum

Python
167
star
68

kafka-junit

This library wraps Kafka's embedded test cluster, allowing you to more easily create and run integration tests using JUnit against a "real" kafka server running within the context of your tests. No need to stand up an external kafka cluster!
Java
166
star
69

sfdx-lwc-jest

Run Jest against LWC components in SFDX workspace environment
JavaScript
156
star
70

ctrl-sum

Resources for the "CTRLsum: Towards Generic Controllable Text Summarization" paper
Python
144
star
71

cos-e

Commonsense Explanations Dataset and Code
Python
143
star
72

hierarchicalContrastiveLearning

Python
140
star
73

metabadger

Prevent SSRF attacks on AWS EC2 via automated upgrades to the more secure Instance Metadata Service v2 (IMDSv2).
Python
129
star
74

dockerfile-image-update

A tool that helps you get security patches for Docker images into production as quickly as possible without breaking things
Java
127
star
75

Converse

Python
125
star
76

refocus

The Go-To Platform for Visualizing Service Health
JavaScript
125
star
77

CoMatch

Code for CoMatch: Semi-supervised Learning with Contrastive Graph Regularization
Python
117
star
78

BOLAA

Python
114
star
79

bazel-eclipse

This repo holds two IDE projects. One is the Eclipse Feature for developing Bazel projects in Eclipse. The Bazel Eclipse Feature supports importing, building, and testing Java projects that are built using the Bazel build system. The other is the Bazel Java Language Server, which is a build integration for IDEs such as VS Code.
Java
108
star
80

botsim

BotSIM - a data-efficient end-to-end Bot SIMulation toolkit for evaluation, diagnosis, and improvement of commercial chatbots
Jupyter Notebook
108
star
81

near-membrane

JavaScript Near Membrane Library that powers Lightning Locker Service
TypeScript
107
star
82

rng-kbqa

Python
105
star
83

MUST

PyTorch code for MUST
Python
103
star
84

fsnet

Python
101
star
85

bro-sysmon

How to Zeek Sysmon Logs!
Zeek
101
star
86

Timbermill

A better logging service
Java
99
star
87

best

🏆 Delightful Benchmarking & Performance Testing
TypeScript
95
star
88

eslint-config-lwc

Opinionated ESLint configurations for LWC projects
JavaScript
93
star
89

craft

CRAFT removes the language barrier to create Kubernetes Operators.
Go
91
star
90

AuditNLG

AuditNLG: Auditing Generative AI Language Modeling for Trustworthiness
Python
90
star
91

online_conformal

Methods for online conformal prediction.
Jupyter Notebook
90
star
92

lobster-pot

Scans every git push to your Github organisations to find unwanted secrets.
Go
88
star
93

violet-conversations

Sophisticated Conversational Applications/Bots
JavaScript
84
star
94

ml4ir

Machine Learning for Information Retrieval
Jupyter Notebook
84
star
95

apex-mockery

Lightweight mocking library in Apex
Apex
83
star
96

fast-influence-functions

Python
80
star
97

MoPro

MoPro: Webly Supervised Learning
Python
79
star
98

TaiChi

Open source library for few shot NLP
Python
79
star
99

helm-starter-istio

An Istio starter template for Helm
Shell
78
star
100

QAConv

This repository maintains the QAConv dataset, a question-answering dataset on informative conversations including business emails, panel discussions, and work channels.
Python
77
star