How do I safely "eval" user code in a webpage? - javascript

I'm working on a webapp to teach programming concepts. Webpages have some text about a programming concept, then let the user type in javascript code into a text editor window to try to answer a programming problem. When the user clicks "submit", I analyse the text they've typed to see if they have solved the problem. For example, I ask them to "write a function named f that adds three to its argument".
Here's what I'm doing to analyse the user's text:
Run JSLint on the text with strict settings, in particular without assuming browser or console functions.
If there are any errors, show the errors and stop.
eval(usertext);
Loop through conditions for passing the assignment, eval(condition). An example condition is "f(1)===4". Conditions come from trusted source.
Show passing/failing conditions.
My questions: is this good enough to prevent security problems? What else can I do to be paranoid? Is there a better way to do what I want?
In case it is relevant my application is on Google App Engine with Python backend, uses JQuery, has individual user accounts.

So from what I can tell if you are eval'ing a user's input only for them, this isn't a security problem. Only if their input is eval'd for other users you have a problem.
Eval'ing a user's input is no worse than them viewing source, looking at HTTP headers, using Firebug to inspect JavaScript objects, etc. They already have access to everything.
That being said if you do need to secure their code, check out Google Caja http://code.google.com/p/google-caja/

This is a trick question. There is no secure way to eval() user's code on your website.

Not clear if the eval() occurs on client or server side. For client side:
I think it's possible to eval safely in an well configured iframe (https://www.html5rocks.com/en/tutorials/security/sandboxed-iframes/)
This should be 100% safe, but needs a couple of libraries and has some limitations (no es6 support): https://github.com/NeilFraser/JS-Interpreter
There are lighter alternatives but not 100% safe like https://github.com/commenthol/safer-eval.
Alternatively, I think something similar can be implemented manually wrapping code in a with statement, overriding this, globals and arguments. Although it will never be 100% safe maybe is viable in your case.

It can't be done. Browsers offer no API to web pages to restrict what sort of code can be executed within a given context.
However, that might not matter. If you don't use any cookies whatsoever on your website, then executing arbitrary Javascript may not be a problem. After all, if there is no concept of authentication, then there's no problem with forging requests. Additionally, if you can confirm that the user meant to execute the script he/she sent, then you should also be protected from attackers, e.g., if you will only run script typed onto the page and never script submitted via GET or POST data, or if you include some kind of unique token with those requests to confirm that the request originated with your website.
Still, the answer to the core question is that it pretty much is that it can't be done, and that user input can never be trusted. Sorry :/

Your biggest issue will always be preventing infinite loops for occurring in user-provided code. You may be able to hide "private" references by running eval in the right context, e.g.:
let userInput = getUserInput();
setTimeout(() => {
let window = null;
let global = null;
let this = null;
// ... set any additional references to `null`
eval(userInput);
}, 0);
And you could wrap the above code in a try/catch to prevent syntax and logic errors from crashing outside of the controlled eval scope, but you will (provably) never be able to detect whether incoming user input defines an infinite loop that will tie up javascript's single thread, rendering its runtime context completely stalled. The only solution to a problem like this is to define your own javascript interpreter, use it to process the user's input, and provide a mechanism to limit the number of steps your javascript interpreter is willing to take. That would be a lot of trouble!

Related

security considerations when using (end-user-defined) JavaScript code inside Java

I am working on a Java project. In it, we want to enable an end-user to define variables which are calculated based on a set of given variables of primitive types or strings. At some point, all given variables are set to specific values, and then the calculations should be carried out. All resulting calculated variables must then be sent to Java.
I am in the process of evaluating ways for the end-user to define his calculations. The (current) idea is to let him write JavaScript and let that code be interpreted/executed inside the Java program. I know of two ways for this to be done: Either use the javax.scripting API or GraalVM/Truffle. In both, we would do it like this:
The given variables are given into the script. In javax.scripting via ScriptEngine.put, in Graal/Truffle via Value.putMember.
The end-user can define variables in the global context (whose names must not collide with the ones coming from Java). How he sets their values is up to him - he can set them directly (to a constant, to one of the given variables, to the sum of some of them ...) or define objects and functions and set the values by calling those.
When the time comes where the given variables have a fixed value, the script is executed.
All variables that were defined in the global context by the script will be sent to Java. In javax.scripting via ScriptEngine.get, in Graal/Truffle via Value.getMember.
NOTE: We would not grant the script access to any Java classes or methods. In javax.scripting via check if the script contains the string Java.type (and disallow such a script), in Graal/Truffle via using the default Context (which has allowAllAccess=false).
The internet is full of hints and tips regarding JavaScript security issues and how to avoid them. On the one hand, I have the feeling that none of them apply here (explanation below). On the other hand, I don't know JavaScript well - I have never used it for anything else than pure, side-effect-free calculations.
So I am looking for some guidance here: What kind of security issues could be present in this scenario?
Why I cannot see any security issues in this scenario:
This is pure JavaScript. It does not even allow creating Blobs (which are part of WebAPI, not JavaScript) which could be used to e.g. create a file on disk. I understand that JavaScript does not contain any functionality to escape its sandbox (like file access, threads, streams...), it is merely able to manipulate the data that is given into its sandbox. See this part of https://262.ecma-international.org/11.0/#sec-overview:
ECMAScript is an object-oriented programming language for performing
computations and manipulating computational objects within a host
environment. ECMAScript as defined here is not intended to be
computationally self-sufficient; indeed, there are no provisions in
this specification for input of external data or output of computed
results. Instead, it is expected that the computational environment of
an ECMAScript program will provide not only the objects and other
facilities described in this specification but also certain
environment-specific objects, whose description and behaviour are
beyond the scope of this specification except to indicate that they
may provide certain properties that can be accessed and certain
functions that can be called from an ECMAScript program.
The sandbox in our scenario only gets some harmless toys (i.e. given variables of primitive types or strings) put into it, and after the child has played with them (the script has run), the resulting buildings (user-defined variables) are taken out of it to preserve them (used inside Java program).
(1) Code running in a virtual machine might be able to escape. Even for well known JS implementations such as V8 this commonly happens. By running untrusted code on your server, whenever such a vulnerability becomes known, you are vulnerable. You should definitely prepare for that, do a risk assessment, e.g. which other data is accessible on the (virtual) machine the engine runs on (other customers data?, secrets?), and additionally harden your infrastructure against that.
(2) Does it halt? What happens if a customer runs while(true); ? Does that crash your server? One can defend against that by killing the execution after a certain timeout (don't try to validate the code, this will never work reliably).
(3) Are the resources used limited (memory)? With a = ""; while(true) a += "memory"; one can easily allocate a lot of memory, with negative impact on other programs. One should make sure that also the memory usage is limited in such a way that the program is killed before resources are exhausted.
Just some thoughts. You're essentially asking if you can trust your sandbox/vitual machine, for that you should either assume that you're using a good one or the only way to be really sure is to read through all its source code yourself. If you choose a trusted and well known sandbox, I'd guess you can just trust it (javascript shouldn't be able to affect file system stuff outside of it).
On the other hand why aren't you just doing all this calculations client side and then sending the result to your backend, it seems like a lot of setup just to be able to run javascript server side. If the argument for this is "not cheating" or something similar, then you can't avoid that even if your code is sent to the server (you have no idea who's sending you that javascript). In my opinion doing this setup just to run it server side doesn't make sense, just run it client side.
If you do need to use it server side then you need to consider if your java is running with root permissions (in which case it will likely also invoke the sandbox with root permissions). On my setup my nodejs is executing under ~/home so even if a worst case happens and someone manages to delete everything the worst they can do is wipe out the home directory. If you're running javascript server side then I'd strongly suggest at the very least never do so under root. It shouldn't be able to do anything outside that sandbox but at least then even in the worst case it can't wipe out your server.
Something else I'd consider (since I have no idea what your sandbox allows or limits) is whether you can request and make API calls with javascript in that sandbox (or anything similar), because if it's running under root and allows that it would give someone root access to your infrastructure (your infrastructure thinking it's your server making requests when it's actually malicious JS code).
You could also make a mistake or start up your VM with an incorrect argument or missing config option and it suddenly allows a vulnerability without you being aware of it, so you'll have to make sure you're setting it up correctly.
Something else is that if you ever store that JS in some database, instead of just executing it, then you have to make sure that it's not made directly available to any other users without checking it otherwise you'd have XSS happening. For example you build an app for "coding tests" and store the result of their test in a database, then you want to show that result to a potential employer, if you just directly display that result to them you'll execute malicious code in their browser.
But I don't really see a reason why you should care about any of this, just run it client side.

Using eval() to evaluate student programmers code. Security flaw?

This is an express app where I am using CodeMirror to allow student programmers to write code in a glorified textarea. I'm using eval() to evaluate that code so that I can output a result for them. This result is passed to the server using socket.io and then returns to the client.
var codeInput = editor.getValue();
var result = eval(codeInput);
socket.emit('sendResult', result);
Is this safe to use? Does this compromise the security of my app any more than sending a user-submitted username or password or email?
In the absence of additional protection, this explicitly creates a reflected cross-site scripting vulnerability in (most of) the applIcations hosted on the server by design.
If there is nothing else other than static content hosted on the site, and you can guarantee there never will be anything else on the site, then you only need to worry about what processing is done with the result (properly escaping the content before committing it to storage, properly escaping the content before displaying it).
i.e. this should have a dedicated vhost name.
Improper use of eval can open up your application to injection attacks I guess would be the major issue here. So in short, yes, the security of your app will most certainly be compromised by using eval.
In addition, it'll be more difficult to debug as you'll have no visibility of line numbers, with performance hits on the top of that, too.
Out of interest, have you explored any other avenues?
Based on the context where the eval is executed, it could be very dangerous.
An fast compromise could be execute the eval inside a sandboxed IFrame.
Here a simple example, where
window.localStorage['sekrit']
is executed with just the "allow-scripts" permission (sandbox="allow-scripts").
I think all you need can be found in that page source.
More details and a list of other permission can be found in this article.
I would suggest to use something like JSLint, instead of executing the code with eval.
JSLint will parse and analyses the source code and will returns it findings.
So you won't have any security issues.
Here you can see it in action.

How to guard against scope objects getting changed?

I'm an Angular noob. In an app I have taken over there is an object in the scope that defines the role of the current user (e.g. user.role=REGULAR).
Is there a way to keep a user from opening firebug and changing user.role=ADMIN?
For example, I have seen code that shows a tab based on a value in a scope, but I'm not sure how to keep a user from changing that value (and getting access to the tab). Is there a pattern to deal with this? Does everything access-related need to come directly from a web service/protected remote location?
There is no way to do this. Your design has a fundamental issue; it relies on client side validation.
You can never ever ever ever ever trust anything coming from the client. Anything that you truly want validated or authenticated must be done on the server side, particularly security related matters.
The most important rule is that once it leaves the server and hits the client, its out of your control. Assume its compromised, assume its not trust-worthy, and assume you have to check everything.
In your case, if a user is not an admin don't even provide them with admin options.
Well, you can try to hide the object inside of a closure or use Object.freeze in browsers that support it, however there is no getting around the fact that the code is being sent to and executed on the client. Even if there was a foolproof way of preventing modification ( which there isn't ), the client could have modified the payload in Fiddler or something before it reached the browser.
With that in mind, you cannot trust anything on the client for access/authorization; you must verify this on the server or you'll have security holes/risks.

How to disable JavaScript function calls from the browser console?

I'm working on a web application in HTML/JavaScript, and I want to prevent users from calling functions in their browser console in order to avoid cheating. All these functions are contained in a unique file called functions.js which is loaded in the head of the index.html file.
After a search on the web I found this solution, which works fine in Google Chrome, but it is inefficient in other browsers such as Firefox:
var _z = console;
Object.defineProperty( window, "console", {
get : function(){if( _z._commandLineAPI ){ throw "Script execution not permitted" } return _z; },
set : function(val){ _z = val }
});
Is there a general way to disable functions call from console? Does it depend on the browser or is it just a problem of scoping or maybe something else that I have ignored?
Is there a general way to disable functions call from console?
No. there isn't: Never. Well, apparently, Facebook found a way in Google Chrome to do so: How does Facebook disable the browser's integrated Developer Tools? - though, I would consider it a bug :-)
Is it maybe something else that I have ignored?
Yes. JavaScript is executed client-side, and the client has the full power over it. He can choose whether or not to execute it, how to execute it and modify it as he wants before executing it. Modern developer tools allow the user to execute arbitrary functions in arbitrary scopes when debugging a script.
You can make it harder to introspect and use (call) your code by avoiding to expose your methods in the global scope, and by obfuscating (minifying) the source. However, never trust the client. To avoid cheating, you will have to perform all crucial task on the server. And don't expect all requests to come from your JavaScript code or from a browser at all; you will need to handle arbitrary requests which might be issued by some kind of bot as well.
Rather than eliminating access to the console, just code your javascript so it doesn't pollute the global namespace. It will make it much harder (or in simple cases virtually impossible) for code executed from the console or address bar to execute your code: https://stackoverflow.com/a/1841941/1358220
It's also worth noting, if you have some code you want the user not to be able to edit or execute, move it to the serverside and only expose the result to the client. You're currently trying to fix a bad design design with a bad coding decision. Improve your design and the implementation will take care of itself.
Minify your JavaScript source to obfuscate any meaning. It won't make it impossible to cheat, but really hard to figure out ways to cheat.
if (window.webkitURL) {
var ish, _call = Function.prototype.call;
Function.prototype.call = function () { //Could be wrapped in a setter for _commandLineAPI, to redefine only when the user started typing.
if (arguments.length > 0 && this.name === "evaluate" && arguments [0].constructor.name === "InjectedScriptHost") { //If thisArg is the evaluate function and the arg0 is the ISH
ish = arguments[0];
ish.evaluate = function (e) { //Redefine the evaluation behaviour
throw new Error ('Rejected evaluation of: \n\'' + e.split ('\n').slice(1,-1).join ("\n") + '\'');
};
Function.prototype.call = _call; //Reset the Function.prototype.call
return _call.apply(this, arguments);
}
};
}
If you want to avoid "cheating", you will need server-side verification of user input. The client can only send the server information according to a server-side defined protocol, and thus cheating is impossible, unless your protocol has security leaks (and most protocols do, especially new protocols).
Sandboxes such as the Facebook API, Google Caja and more allow you to arbitrarily enforce any constraints by "re-writing" the language (they run a parser on and basically re-compile user-given code and make everything that is unsafe safe).
This works as long as you can make sure that user code can only run inside these environments. This way code from other users cannot mess with your client, but you can of course still mess with your own client.
For those looking for it today:
This obfuscator tool: https://obfuscator.io has the feature "Debug Protection" this blocks the console and even the inspection mode of your browser.
It also stops any javascript when the inspector was opened.
Works like a charm.

Is it possible to manipulate every Javascript variables, objects while or after running?

It seems there's no way to completely hide source/encrypt something to prevent users from inspecting the logic behind a script.
Aside from viewing the source, then, is it possible to manipulate every variables, objects while a script is running?
It seems it is possible to some degree: by using Chrome's developer tools or Firebug, you can easily edit variables or even invoke functions on the global scope.
Then what about variables, functions inside of an instantiated objects or self invoked anonymous functions? Here is an example:
var varInGlobal = 'On the global scope: easily editable';
function CustomConstructor()
{
this.exposedProperty = 'Once instantiated, can be easily manipulated too.';
this.func1 = function(){return func1InConstructor();}
var var1InConstructor = 'Can be retrived by invoking func1 from an instantiated object';
// Can it be assigned a new value after this is instantiated?
function func1InConstructor()
{
return var1InConstructor;
}
}
var customObject = new CustomConstructor();
After this is ran on a browser:
// CONSOLE WINDOW
varInGlobal = 'A piece of cake!';
customObject.exposedProperty = 'Has new value now!';
customObject.var1InConstructor; // undefined: the variable can't be access this way
customObject.func1(); // This is the correct way
At this stage, is it possible for a user to edit the variable "var1InConstructor" in customObject?
Here's another example:
There is a RPG game built on Javascript. The hero in the game has two stats: strength and agility. the character's final damage is calculated by combining these two stats. It is clear that players can find out this logic by inspecting the source.
Let's assume the entire script is self invoked and stats/calculate functions are inside of objects' constructors so they can't be reached by normally after instantiated. My question is, can the players edit the character's str and agi while the game is running(by using Firebug or whatever) so they can steamroll everything and ruin the game?
The variable var1InConstructor cannot be re-bound under normal ECMAScript rules as it is visible only within the lexical scope. However, as alex (and others) rightly say, the client should not be trusted.
Here are some ways the user can exploit the assumption that the variable is read-only:
Use a JavaScript debugger (e.g. FireBug) and re-assign the variable while stopped at a breakpoint within the applicable scope.
Copy and paste the original source code, but add a setter with access to the variable. The user could even copy the entire program invalidating almost every assumption about execution.
Modify or inject a value at a usage site: an exploitation might be possible without ever actually updating the original variable (e.g. player.power = function () { return "godlike" }).
In the end, with a client-side program, there is no way to absolutely prevent a user from cheating without a centralized authority (read: server) auditing every action - and even then it still might be possible to cheat by reading additional game state, such as enemy positions.
JavaScript, being easy to read, edit, and execute dynamically is even easier to hack/fiddle with than a compiled application. Obfuscation is possible but, if someone wants to cheat, they will.
I don't think this constitutes an answer, it could be seen as anecdotal, but it's a bit long for a comment.
Everything you do when it comes to the integrity of your coding on this issue has to revolve around needing to verify that the data hasn't changed outside of the logic of your game.
My experience with game development (via flash, primarily...but could be compared to javascript) is that you need to think about everything being a handshake where possible. When you are expecting data to come to the server from the client you want to make sure that you have some form of passage of communication that lessens the chance of someone simply sending false data. Store data on the server side as much as possible and use the client side code to call for it when it's needed, and refresh this data store often.
You'll find that HTML games tend to do a lot of abstraction of the logic to the server side, even for menial tasks. Attacking an enemy, picking up an item, these are calls to functions within server-side code, and is why the game animation could carry on in some of these games while the connection times out in the background, causing error messages to pop up and refresh the interface to the server's last known valid state.
Flash was easier in this regard as you didn't have any access to alter any data or corrupt it unless it left the flash environment
Yes, anything ran on the client should be untrusted if you're using the data from it to update a server side state.
As you suggested, you can't hide the logic/client-side code. You can make it "harder" for people to read the source by obfuscating it, but it's very trivial to undo.
Assuming you're making a game from your example, the first rule of networked games is "never trust the client". You need to either run all the game logic on a server, or you need to validate all the input on a server. Never update the game state based on input from a client without validating it first.
You can't hide any variable.
Also, if the user is so good in javascript, he can easily edit your script, without editing the variables value through the console.
JS code that is injected into an HTML using Ajax is pretty darn difficult to get your hands on, but it also has it's limitations. Most notably, you can't use JS includes in injected HTML . . . only inline JS.
I've been working with some of that recently actually and it's a real pain to debug. You can't see it, step into it, or add breakpoints to it in any way that I can figure out . . . in Firebug or Chrome's built-in tool.
But, as others have said . . . I still wouldn't consider it trusted.

Categories