Javascript eval limits - javascript

Is there a limit to javascript's eval, like in lenght?
I'm trying to build an app where you can store JS code in the DB, which you can later load and eval in order to execute it, but i'm reaching a limit.
First of all, the code has to all be in one line. Any multiline statements are not executed.
Next, i'm reaching a limit in length (i guess). If i execute the code manually, it works, but put that same code in the db, load it via ajax, and try to execute it, and it fails.
Any ideas why?

You don't need to use eval and its not exactly a good thing to use. You could just have it print out to the page and it will run.
Here is the accepted answer on why you should not use eval:
Improper use of eval opens up your code for injection attacks
Debugging can be more challenging (no line numbers, etc.)
eval'd code executes more slowly (no opportunity to compile/cache eval'd code)

I have run into this also. As others have said here - eval comes in handy when you are generating the Javascript on the fly and then want to have it execute on the browser. My usages of this technique are to go small things like a simple function that will just make a call back to the server when a button is pressed. Depending upon the circumstances there might be two functions or just one. I've also used it to display information that changes from a database. The information is always just plain text. So no injection attack can be done.
Anyway, I too have run in to this limitation of the Javascript EVAL statement and it seems to me that there is a 1024 character limit. When I go over this I start getting weird things like eval just spitting out the original text. This is really evident because I hex everything before sending it to the browser so I can have things like single and double quotes in the text without it causing eval any problems. (And hexing everything helps prevent injection attacks.)
I also side with the person who said to use getscript in jQuery. It works just as well as the eval without the size limitations. The only extra step you have to take is to create the Javascript file first.
I hope this helps and answers the original poster's question. That being I believe the size limitation is 1024 bytes.

You could create a javascript function that creates a script-tag dynamically (createElement('script') and append it to the head- or bodytag) and point the source to your app. The src can contain parameters, used like a get request, like for example: src="jsapp.aspx?script=myscript&includefunction=loadfn" No eval needed. You can even define an onload handler for your new script tag. Plenty of documentation on the net for that.
You wouldn't even have to use XHR (AKA Ajax) for that.

Related

Check JavaScript before submitting / Deny access to global variables

I have made a math formula editor which allows the user to enter a math formula. This will then be converted to a JavaScript equation in a string, which will be executed using eval(). The user will also be able to submit it so that other users can view his function. The big problem with this is that it would be possible to enter JavaScript code in the formula, which would then be executed by the browsers of other users viewing it. I unfortunately can't just escape the formula because I am converting things like Sinus to a Math.sin() function. I am open to any suggestions how I can prevent the user from putting JavaScript code into the Math formula, here are my ideas:
Somehow check the code. The problem is that as said I can't just scan for any JavaScript function because I am using things like Math.sin() or Math.log(). So I would like to allow any method of the Math object and also normal math using standard operators. Another problem with this is that JavaScript can be disabled and modified, which could be a security concern. It would therefore be great if I could do this scanning using PHP.
Execute the equation in a "safe environment". Now I don't know if this is possible in JavaScript, but I am basically looking for something where the function that is being executed can't access or modify any functions (except any methods of the Math object) and can't change any of the global variables, including the document variable. I don't know whether this is possible or not but maybe somebody knows something.
Thanks for your help, Moritz
UPDATE: I have found a way. I made a function which shadows all global variables and functions with a local variable. This is the function:
function safeEval(string,banned) {
for(var i=0;i<banned.length;i++) {
eval('var '+banned[i]);
}
return eval(string);
}
Where banned is an array of strings which will be shadowed. To block all global variables, you can call it like this:
safeEval('document.write("test")',Object.keys(window))
This will throw an error, which is exactly what I want. Object.keys(window) will return an array of all global variables (and functions), including safeEval.
ANOTHER UPDATE: As Rainer Plumer pointed out, this is not safe as you can use this as follows: safeEval('this.document.write("test")',Object.keys(window))
Hope I could help. Moritz
The "safe environment" is a good idea; It can achieve by Iframe.
According to your description, you need a "safe environment" to run a JavaScript equation, I think Iframe is very good to do that. This process runs a JavaScript equation can be done in Iframe, and it is safe because the page and Iframe are independency document.
Then you can use postMessage or something else to get result from Iframe, show it to users. You have to use another domain in Iframe that can ensure nobody can get users cookie or something else important, one of the famous website is codepen.io doing that.

Does javascript execute if no function is called?

I have some wordpress pages with javascript code that require javascript file references. For pages that don't call functions within these js file references, there should be no performance impact for including these files (except the file call) right?
-- EDIT in response to #cdhowie --
If only certain pages require these javascript files, is it possible to move them out of the head section and into the page? I've read this is bad practice.
But in theory, this prevents the entire site from having a performance hit for files that are not being utilized?
The referenced JavaScript files will be downloaded (or fetched from the cache) and then be executed by the browser's JavaScript interpreter in both cases. The "JavaScript file references" need to be executed in order to create the variables and functions that you might use, and the browser has no way of knowing ahead of time if you will use them. Further, the included files might actually manipulate the document, and the browser doesn't know this either until it has executed them.
So yes, there will be a performance impact whether or not you call the functions. Whether or not it's significant enough for you to worry about is something you will have to determine. (Always profile your page's loading time before making decisions like this!)
Javascript functions are only executed when you explicitly call them (or implicitly in callbacks and whatnot). The code will however still be interpreted by the browser on each page regardless of functions being called or not.
Edit:
I was wrong to say the performance hit is irrelevant. It really all depends on your exact situation (where the code is coming from, how much code, etc.) and also how much you care about performance in terms of milliseconds.
One possible "performance" issue is if those extra .js files are on your server. If so and you are loading them when it is not needed, you are causing for unneeded traffic and bandwidth in regards to your server.
This will execute, but take up very little cpu time
<script type="text/javascript">
// just a comment
</script>
no functions, just a comment... but it's still "code", still has to be parsed, still has to be checked for syntax errors, etc...

Eval() vs Developer Tools

So the age old standard is that using Eval is bad because it can cause major security issues; especially in scenarios where you are evaluating something that potentially came from user input somewhere down the line. This makes 100% sense, and I have never had any problem avoiding the use of Eval. I was facing an odd situation recently, though, that sort of made me think about this type of thing a bit differently.
I wrote a JS function sort of like:
function someFun(param, callback) {
bool = someOtherFun(param);
if(bool)
callback();
else
return false;
}
This is much stripped down, but the principal is the same: it calls another function and based on the return value of that will either execute a function provided as a parameter or it will return false. It made me think, though, that this sort of thing could be exploited just as easily as Eval(txtbox.value) with the use of the JS console in F12. Does that matter?
In this world of F12, it seems to me like Eval is the least of our worries. Anyone who knows what an injection attack is is likely to know what F12 is as well. Am I wrong?
While you are correct that tools like F12 and firebug expose your JavaScript to a new level of scrutiny and make it easy for people to attack, you are missing the danger of using eval.
Instead of worrying what a the current user (with the page loaded in the browser might do) lets concern our selves with their co-worked at the next computer. Suppose that co-worker types a comment on Stack Overflow, which is then stored in a database, and then sent out to our user's computer to be displayed. And lets suppose that as part of that rendering process that comment is encoded into JSON and then eval is called on it.
This is where there is a dangerous exploit waiting that has nothing to do with our user inspecting or executing their own JavaScript on the page. If their co-worker embedded malicious JavaScript in their comment and we call eval on it, that JavaScript may be executed causing that malicious code to run on every computer that views the page.
That is why we should avoid using eval.
I don't see the exploit scenario. Yes, they could call your function passing a malicious callback. Or... they could just call the malicious callback from the Console.

What risk or liablities in using eval() in the following manner

I'm working on creating one of those robot games. The user creates a robot and then puts it in a battlefield with other robots.
I'd like to let the users use javascript to program their bots. I'll provide a number of functions for them to call, but they also can build thier own. (sorta)
To date, the only solution I have come up with is to use the javascript eval() function to execute the code the users have written.
I want to know two things:
Anyone have any alternative suggested implementations that still allow the users to write in javascript?
Can the users do anything with this flaw that they could not do using the firefox javascript debugging tools? (ie: on their own without my use of the eval() function)
Note: The javascript code is stored within mySQL. ajax is used to pull the jscript out and display to users. ajax is used to send javascript updates back into SQL. All code submitted by users and about to be inserted in the database is run through a "clean()" function.
So basically you will allow UserA to write javascript which will be evalled in UserB's browser?
If so, then that sounds like a fairly bad idea ;)
You could use a middle layer such as http://code.google.com/p/google-caja/wiki/CajaCajole to make it a bit safer.
An example of what they could do is: write javascript which will present what looks like your login page, then send the username and password to another server.
Another example would be to inject a script tag which then gets the 'full' payload which could get up to all kinds of mischief, like fx showing a friendly popup with the new exclusive downloadable Portal game that you got a special deal with Steam to make available etc etc. Just download and Run! Then it creates a hidden iframe to some trojan cdn. :)
I never thought I'll say this, but Project Narcissus might be of use to you. It's a JavaScript engine written in JavaScript.
Cool idea.
eval does have a slight disadvantage against other methods of script injection.
You can create a function on the fly with Function. Try this:
var command = "alert(123)";
var doStuff = new Function(command);
doStuff();
eval runs in the private scope, Function runs in the global scope. That means if you have an internal value that bots aren't supposed to be able to modify, they might have access to it if you run their logic through eval, but they shouldn't if you use Function. More info here:
changing string to a function in javascript (not eval)
Many AJAX libraries can be set to execute the returned JS automatically. No need for eval().
The most important thing is to let pages containing user scripts run on a separate, "sandboxed" domain that has no session cookies from the main site that could be connected to user accounts and such.
That, together with some manual monitoring of the submissions, will already take away a lot of the script injection risks.
There will always be some risk of malicious code being run on the user's browser when allowing Javascript from your users, but it stands to reason that getting malicious JavaScript is a general risk on the Internet, and it's up to the client to protect against it.
What I wouldn't do is eval() user-entered JavaScript inside the main domain of the project. That opens too many real dangers of attack.

Executing JavaScript from Flex: Is this javascript function dangerous?

I have a flex application that needs the ability to generate and execute JavaScript. When I say this, I mean I need to execute raw JavaScript that I create in my Flex application (not just an existing JavaScript method)
I am currently doing this by exposing the following JavaScript method:
function doScript(js){ eval(js);}
I can then do something like this in Flex (note: I am doing something more substantial then an alert box in the real Flex app):
ExternalInterface.call("doScript","alert('foo'));
My question is does this impose any security risk, I am assuming it's not since the Flex and JasvaScript all run client side...
Is there a better way to do this?
There's no need for the JavaScript function, the first argument to ExternalInterface can be any JavaScript code, it doesn't have to be a function name (the documentation says so, but it is wrong).
Try this:
ExternalInterface.call("alert('hello')");
This isn't inherently dangerous, but the moment you pass any user-provided data into the function, it's ripe for a code injection exploit. That's worrisome, and something I'd avoid. I think a better approach would be to only expose the functionality you need, and nothing more.
As far as I know, and I'm definately not a hacker, you are completely fine. Really, if someone wanted to, they could exploit your code anyway clientside, but i don't see how they could exploit your server side code using javascript (unless you use server side javascript)
I don't see where this lets them do anything that they couldn't do already by calling eval. If there's a security hole being introduced here, I don't see it.
Remember also that the script actions are controlled by the "AllowScriptAccess" tag in the statement. If the web page doesn't want these actions, they should not permit scripts to call out.
http://kb.adobe.com/selfservice/viewContent.do?externalId=tn_16494
ExternalInterface.call("eval", "alert('hello');");

Categories

Resources