Question

I am creating a website that will demonstrate the dangers of XSS. Users will attempt to get JavaScript to execute using an XSS vulnerability.

However, I am running into problems in determining if JavaScript is actually being executed so that I can record that the user was successful. I will be running these checks on a node.js server.

I originally planned to run eval on the parts which would contain JavaScript if the user was successful, but thought that this would be too dangerous as it would be running on the server-side and could get the server exploited.

Are there any ways to using JavaScript to validate if a string is valid JavaScript other than running eval? Or is there a way to run eval without putting my server at risk?

Was it helpful?

Solution

You could use the esprima javascript parser to see if the string is valid javascript syntax.

Install using npm install esprima.

To use:

var esprima = require('esprima');

var userStringToTest = 'var a = 10;';

var isValid = isValidJs(userStringToTest);

if(isValid) {
  console.log('its valid!');
}
else {
  console.log('its NOT valid!');
}

function isValidJs(testString) {
  var isValid = true;
  try {
    esprima.parse(testString);
  }
  catch(e) {
    isValid = false;
  }
  return isValid;
}

As @FelixKing pointed out in his comment, this of course won't detect runtime errors. For your use case though, it sounds like you should be testing for syntax errors as opposed to runtime errors since that is both more strict and there really shouldn't be valid javascript syntax to begin with.

OTHER TIPS

What you need is a JavaScript sandbox, which will isolate their code from the code running it.

There are several to choose from. I've used "Sandbox" before: http://gf3.github.io/sandbox/

Execute their code in the sandbox, see if there were errors, return the output.

Google Caja would be a good solution for this.

The Caja Compiler is a tool for making third party HTML, CSS and JavaScript safe to embed in your website.

There are multiple wrappers that will let you run it on a node server, such as this one: https://github.com/theSmaw/Caja-HTML-Sanitizer

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top