Reputation: 2112
I have a script which takes user input, performs some operations on that input and then executes the modified input.
Example:
User enters 'vbscipt or javascript'
My script converts it to:
var searchtest = "mystring.search('vbscript')>=0 || mystring.search('javascript')>=0";
And executes it using eval(searchtest);
However if the user enters 'vbscript javascript'
My script converts it to
var searchtest = "mystring.search('vbscript')>=0 mystring.search('javascript')>=0";
(Note lack of ||) Which will cause an error when I call eval(searchtest);
Is there a way to test the searchtest string to determine if it is a valid javascript expression before executing it?
Upvotes: 0
Views: 731
Reputation: 16033
JavaScript eval is evil !!
Instead of transforming user input as you are doing why not something like the following :
// list of values considered valid
myString = ['javascript', 'vbscript', 'perl', 'python'];
function search (x) {
// Returns true if x is a value an array (passed as `this`)
return this.indexOf (x) >= 0;
}
function searchTest (userInput, myString, search) { 'use strict';
function orClause (clause) {
// caluse is a series of values separated by `or`, return true
// if any search returns true for any of the values.
clause = clause.split (/\s+or\s+/i); // split on 'or'
while (clause.length) { // for each value
if (search.apply (myString, [clause.shift ()])) {
return true;
}
}
return false; // no matches....
}
userInput = userInput.split (/\s+and\s+/i); // split on 'and'
// userInput is now an array of clauses each is either a value or
// a series of values separated by `or`. We pass each clause to
// the orCaluse function and return true only if ALL returns are true.
while (userInput.length) {
if (!orClause (userInput.shift ())) {
return false; // and fails
}
}
return true; // All true so return true.
}
searchTest ('fred or javascript and python', myString, search),
I am assuming your expresson can be a sequence of and
s and or
s with and
s taking precedence
Upvotes: 2
Reputation: 22421
Yes, you can use eval
itself and catch syntax error exceptions. But don't do it! Blindly transforming user input and validating ready to execute code with eval is an open gate for many XSS attacks. Instead of validating transformed string, you should strictly validate user input instead to make absolutely sure that transformation will result in correct code limited only to exact operations you wish to allow.
Upvotes: 0