Check JavaScript before submitting / Deny access to global variables - javascript

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.

Related

check if javascript variable has been changed from console

I am developing a JS game and wish to prevent cheating as much as possible. I understand that this is near impossible but I would like to prevent users from going into the console and changing their lives by saying something like game.lives = 99;
Is there a way I can detect if a variable such as lives has been changed from the console thus marking the game hacked and stopping the execution of my code? I understand I could do server side checking but I want to avoid lag. I am looking for a JS answer if there is one.
You won't be able to completely stop a user from changing the javascript code or variable values. You only can make it more difficult. Fisch mentioned using closure so as all variables will be private. Look into the immediately invoked function expression (IIFE) pattern. It's used in a lot of plugin style code and helps prevent modifications.
If a user wants to change a variables value, nothing will stop them from running the game in debug mode and modifying values at breakpoints.
You could use a closure which would essentially make all your variables private and thus not accessible from the console. If you need to have some public variables and methods, you could use a revealing module pattern. you can read more about them here: http://www.joezimjs.com/javascript/javascript-closures-and-the-module-pattern/

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.

Ways to make Javascript code hacking / injection / manipulation difficult?

Are there ways to prevent, or make it difficult enough, for someone to inject Javascript and manipulate the variables or access functions? A thought I had is to change all var names randomly on each reload so the malware script would need to be rewritten every time? Or are there other less painful ways?
I understand that eventually someone will hack his way in, but I'd like to know ways to make it difficult to reproduce the action, so that people won't publish a bookmarklet or something similar for everyone to use. I don't care if experts find their way in the code, but I'd like it to be a bit more complex than javascript:d=0;
If you know ways to make hacking Javascript a bit more difficult, please write those.
Accept that your javascript will be "manipulated" and make provision at the server side. There's fundamentally nothing you can do to stop people tinkering with the client.
You can write your JS to use only private methods and variables in a self-executing function. For example, the following code leaves no sign of itself in the global namespace for anyone to monkey with.
(function(){
var x = 1;
var y = 2;
var z = "A am z";
var clickHandler = function() {
alert('You clicked the body');
};
document.getElementsByTagName('body')[0].addEventListener('click',clickHandler,true);
}());
[EDIT]
The above code is susceptible to a user overwriting any globally available objects, methods, events or properties you are using (in this case, document, getElementsByTagName and addEventListener), so if you are truly paranoid you can copy these to your function scope before the page has loaded and the user has a chance to overwrite them. Using addEventListener is a good idea because unlike the event body.onclick, it cannot be removed or overwritten from outside the function.
Any user that will really want to tamper with the client will be able to. The code is on his machine. Even if you obfuscate the client side code, there are tools out their that will help someone deobfuscate the code back in a second.
What you need to think about though is making the site safe on the server, and safe for other users as well.
This means (as a minimum):
Checking/Validating every request and input parameters on the server so Users won't be able to alter any server side data by triggering 'hacked' client side functions you wrote.
Check all data that you output to the screen that was originated from user input. Other users might have inserted client side scripts that are dangerous for your site, and especially dangerous to the other users on your site. (If you're using .net then check out the AntiXSS library)
Obfuscation and minification should make it a good bit more difficult to hack, but I agree with spender.

Javascript eval limits

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.

Javascript: declaring a variable before the conditional result?

My JavaScript is pretty nominal, so when I saw this construction, I was kind of baffled:
var shareProxiesPref = document.getElementById("network.proxy.share_proxy_settings");
shareProxiesPref.disabled = proxyTypePref.value != 1;
Isn't it better to do an if on proxyTypePref.value, and then declare the var inside the result, only if you need it?
(Incidentally, I also found this form very hard to read in comparison to the normal usage. There were a set of two or three of these conditionals, instead of doing a single if with a block of statements in the result.)
UPDATE:
The responses were very helpful and asked for more context. The code fragment is from Firefox 3, so you can see the code here:
http://mxr.mozilla.org/firefox/source/browser/components/preferences/connection.js
Basically, when you look at the Connect preferences window in Firefox, clicking the proxy modes (radio buttons), causes various form elements to enable|disable.
It depends on the context of this code. If it's running on page load, then it would be better to put this code in an if block.
But, if this is part of a validation function, and the field switches between enabled and disabled throughout the life of the page, then this code sort of makes sense.
It's important to remember that setting disabled to false also alters page state.
(Incidentally, I also found this form very hard to read in comparison to the normal usage.
Not necessarily, although that was my first thought, too. A code should always emphasize its function, especially if it has side effects. If the writer's intention was to emphasize the assignment to sharedProxiesPref.disabled then hey, roll with it. On the other hand, it could have been clearer that the action taking place here is to disable the object, in which case the conditional block would have been better.
It's hard to say what's better to do without more context.
If this code being executed every time that proxyTypePref changes, then you're always going to need set shareProxiesPref.disabled.
I would agree than an if statement would be a bit more readable than the current code.
Isn't it better to do an if on proxyTypePref.value, and then declare the var inside the result, only if you need it?
If you're talking strictly about variable declaration, then it doesn't matter whether or not you put it inside an if statement. Any Javascript variable declared inside a function is in scope for the entire function, regardless of where it is declared.
If you're talking about the execution of document.getElementById, then yes, it is much better to not make that call if you don't have to.

Categories

Resources