Skip to content

Instantly share code, notes, and snippets.

@jaysoo
Created June 1, 2013 19:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jaysoo/5691492 to your computer and use it in GitHub Desktop.
Save jaysoo/5691492 to your computer and use it in GitHub Desktop.
String escaping is the wrong solution to XSS prevention. Using the new nonce directive of Content Security Policy, we can prevent scripts from executing that don't have the valid nonce.
var express = require('express');
var app = express();
app.use(express.methodOverride());
// Naive nonce using just timestamp.
var nonce = new Date().valueOf();
var contentSecurityPolicy = function(req, res, next) {
res.header('Content-Security-Policy', "script-src 'self' 'nonce-" + nonce + "' http://ajax.googleapis.com");
next();
};
app.use(contentSecurityPolicy);
app.get('/', function(req, res){
// Only inline scripts with a valid nonce should execute.
var body = '<!doctype html><body>'
+ '<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>\n\n'
+ '<script nonce="' + nonce + '">$("body").append("<p>This should work with a valid nonce.");</script>\n\n'
+ '<script>$("body").append("<p>This should not work because nonce is missing.");</script>\n\n'
+ '<script nonce="bad">$("body").append("<p>This should not work because nonce is invalid.");</script>\n\n'
+ '<script nonce="' + nonce + '">$("body").append("<p>This should also work with a valid nonce.");</script>\n\n';
res.setHeader('Content-Type', 'text/html');
res.setHeader('Content-Length', body.length);
res.end(body);
});
app.listen(3000);
console.log('Listening on port 3000');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment