Is this use of JavaScript eval admissible? - javascript

I am making a website and I want to use the following design:
Each time a user clicks a link an ajax request is sent.
The reply contains 2 fields:
the HTML that replaces the content area
A JavaScript to be evaluated (JavaScript behaviors attached to objects withing the new HTML content)
Does this use of JavaScript eval() have any downsides?
Edit
The JavaScript that is to be evaluated is varied - it's not something that can be sensibly expressed with a single function taking different arguments.
Cross-site scripting was mentioned, but I don't see how this use is different from a user visiting a new JavaScript-containing page.

This mainly depends upon how the javascript to be evaluated is generated. Any use of eval is potentially subject to cross site scripting, but only if the js is generated by something that a user can control. If the server is returning a static js, that's no more inherently bad than the use of js anywhere else.

Can't think of any, although my imagination may be a bit lacking. ) Besides, isn't JSONP something of the same method?

Related

Count the javascript functions on a page (with javascript)

Good day all.
I would like to count the js functions present on a given page, and then send this number via ajax (the ajax part is the simple part) do you think is it possible to achieve that in javascript? what should be the best way to do it?
thanks in advance.
explanation:
I'm trying to figure out how to counter measure some fraud attempts on some subscription pages, I suspect that some javascript is injected on the page before the user click, so having the number of functions present at the load event, and then the number of those present on the submit event, should lead me in the right direction.
Well, if someone is injecting code to your site, they could just as easily use that code to turn off your code counting functions. You can never trust anything that happens on the client side and must validate everything on the server.
As for the technical side, you'd use a tool like acorn to traverse the syntax tree and find all FunctionDeclaration and FunctionExpressions (and arrows, concise method definitions and methods). That would not find all functions, but it would find all statically created ones.
Once the code started executing it's impossible since it's easily reducable to the halting problem. You don't know if a code will create a function at some point in the future.

Can these javascript methods be considered XSS safe?

I am implementing a so called "single page app" which accepts JSON as input. That also means that all HTML is rendered in the browser, also all templates (am using knockout) are seemingly unaffected by user input, in the sense that the template is not constructed dynamically by the backend but rather embedded statically in the client. In other words, I do NOT anything like this:
echo '<input type="text" value="$var">'
So all rendering of user content essentially boils down to these JS methods:
document.createTextNode(userVar); // for displaying static text
inputElement.value = userVar; // for populating input fields
document.title = userVar; // some user input can be reflected in the doc title
window.history.pushState = ... // no user input is set here directly, but there are URIs where this could be set using an outside link
So now the question would be: are these methods all 100% XSS safe? Or would there still be any way to trigger a XSS attack - and if "yes", how could this be done?
I believe those four functions are safe. The document.createTextElement method appears to be safe, and none of the other methods are capable of adding objects to the DOM.
In order to launch an XSS attack, an attacker must be able to either hijack an existing script to run arbitrary code (why eval is evil) or insert their own scripts through vectors such as <script> tags. Since you are using methods that aren't capable of adding elements to the DOM, nor are they capable of manipulating event handlers, I would think that you are safe.
We would also need to be able to see more of your backend code to make that call, however, but on the frontend it looks okay.
Whether or not your JavaScript is susceptible to Cross-Site Scripting (XSS) is one question, whether it is secure at all is another. The idea with XSS is that the attacker puts code into your system, which is then run by another user, it might redirect them to another (potentially malicious) site for example.
If you're not storing the input data to your system, and then displaying it to another user, then you're safe from XSS. The user can only attack themselves, which is pointless in my opinion.
If however you are storing the input data to your system, then you have a potential problem (hard to know without knowledge of your back-end). But whatever you submit via JavaScript, wherever you send it, the back-end has to process (verify and validate) it before storing to ensure it's not malicious.
Bottom line is don't rely on JavaScript. Whether your script is 10 lines, or 1,000,000 lines it can all be manipulated via the front-end because it runs client side. You can try this yourself in Google Chrome using the inspector.

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

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!

Dynamically printing javascript

I recently ran into a situation where it made sense (at first at least) to have my server-side code not only "print" html, but also some of the javascript on the page (basically making the dynamic browser code dynamic itself). I'm just wondering if there is sometimes a valid need for this or if this can usually be avoided...basically from a theoretical perspective.
Update:
Just to give an idea of what I'm doing. I have a js function which needs to have several (the number is determined by a server-side variable) statements which are generating DOM elements using jQuery. These elements are then being added to the page. So. I am using a server-side loop to loop over the number of elements in my object and inside of this loop (which also happens to be inside of a js function) I am aggregating all of these statements.
Oh and these dom elements are being retreived from an xhr (so the number of xhr requests is itself a server-side dependency) and then processed using jQuery..which helps explain why im not just printing the static html to begin with. Sounds kind of ridiculous I'm sure, but its a complicated UI..still I'm open to criticism.
I can smell some code smell here... if you're having to generate code, it probably means one of:
you are generating code that does different things in different situations
you are generating same kind of functionality, only on different things.
In case 1, your code is trying to do too much. Break your responsibilities into smaller pieces.
In case 2, your code is not generic enough.
Yes there is sometimes a need and it is done often.
Here is a simple usage in an Asp.net like syntax
function SayHi( ){
alert( "Hello <%= UserName %>");
}
Just a suggestion. If your server-side is generating HTML/Javascript, then you're letting view-side logic creep into your server-side. This violates separation of concern if you're following an MVC-style architecture. Why not use a taglib (or something of that nature) or send JSON from the server-side?
One usefull feature is to obfuscate your javascript on the fly.. When combined with a caching mechanism it might actually be useful. But in my opinion javascript generation should be avoided and all serverside variables should be handed to the script from the templates (on class or function init) or retrieved using XMLHTTP requests.
If your application generates javascript code only for data (eq. you want to use data from sql in js), the better practice is to use JSON.
Yes, sometimes for some specific task it may be easier to generate javascript on the fly in a bit complex way, like in rails rjs templates or jsonp responses.
However, with javascript libraries and approaches getting better and better, the need for this is becoming less, a simple example you may have needed to decide on a page whether to loop some elements and apply something or hide another single element, with jquery and other libraries, or even one's own function that handles some complex situation, you can achieve this with a simple condition and a call.

Practical use cases for returning javascript from an XHR/Ajax request?

I've never really had to return javascript from an XHR request. In the times I've needed to apply behaviour to dynamically loaded content I could always do it within my script making the call.
Could someone provide actual real world cases just so I'm aware, of when you'd actually need to do this ( not for convenience ), or some reasons of why in some cases it's better to return js along with the other content instead of building that functionality in your callback?
The only scenario that's coming to my head is on a heavily customized site, if the site supports multiple languages for example and the functionality changes depending on the language, and ajax is used to pull in dynamic content and perhaps in some languages a certain behavior needs to happen while in others another needs to happen and it's more efficient returning js in script blocks instead of dumping all that logic into a callback.
Sometimes it is more convenient to "prepare" the JavaScript code on the server side. You can use the server's programming or scripting language to generate the code and you can fill it with values from the database. This way most of the logic takes place on the server and not the client. But it is really a matter of taste. OK, that wasn't a real world case but maybe my opinion is helpful anyway.
We use XHR to request an entire web page that includes java script for menus etc. We then replace the current page with the new one that has been sent over XHR

Categories