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');");
Related
I need to pass user agent value into front end.
I can get this value using $_SERVER['HTTP_USER_AGENT'] and write it into front end.
(Actually I will be using Mage::helper('core/http')->getHttpUserAgent(), but I think it's just a magento helper to call above mentioned function.)
Or I can use get navigator.userAgent with js on client side.
Which better and why? My primary concern is speed.
p.s. I understand that UA can be easily manipulated. We are not basing any serious functionality on the value, it's used as a secondary parameter.
I would personally use navigator.userAgent. Mainly, because passing values from PHP to JavaScript is pretty ugly in my opinion. Also, the value will be exactly the same for both. Even if someone decides to edit their useragent.
I think simplicity takes the cake here.
Performance will depend on the purpose. If you need this inside php, then use the server variable with helper getter you mentioned above. For js use navigator object.
In general both navigator.userAgent and HTTP_USER_AGENT are variables of Request Header and are both already present in memory (of server or users browser in case of js). So no measurable performance difference is possible.
I am using a jQuery UI dialog and I am adding buttons to the dialog in JavaScript based on some entitlements logic. (I pass in a boolean from my server-side AJAX call if I am entitled and then I show different buttons based on that flag.)
What concerned me is what is preventing someone from using developer tools like Firebug and putting a breakpoint on that line that does the check and either altering the flag or dragging to skip over that entitlements check.
So my question is specific to adding buttons onto a jQuery UI dialog (because its not like you can add the buttons from the server side since its a jQuery plugin), but I guess it highlights a more general point around any entitlements logic on the client side being "vulnerable". So if there are any general best practices around this point I would be interested (but still looking for an answer to my specific example).
NOTE: I am also doing a server-side entitlement check on POST as a backup, so I am still "protected" but I am still concerned about the point above.
Nothing prevents people from altering client-side code, it is inevitable.
You can, however, add buttons of the kind of "server-side", you just retrieve a string using the AJAX call, which happens to be a JavaScript function that adds buttons. And on the client side do eval() on that string which will execute the retrieved JS function and will add the buttons. Moreover, you can transmit your entire JavaScript code that way, so the client cannot skip anything since all is being executed in the eval().
A quick example:
Server-side function returns
string banana= "alert('test');";
return banana;
and client side does
eval(response.d);
Here is a theoretical example: FIDDLE
You cannot control what clients will do with your scripts, nor what requests they will make of your server. You must design your back-end API (not your JS client) to be the "gating mechanism" between the user and your system. It's best not to think of the JS as part of your system, but as a separate client that you ship as a reference implementation for your API.
But, if you wanted to at least make it difficult for users to mess with your code, you could minify and concatenate your JS scripts with something like Closure.
As the other person suggested, you cannot implement security on the client for exactly the reason you point out. You could use basic auth, or try setting up a token based approach.
Is it possible to detect if - let's say - someone uses firebug to change parts of the website that's been loaded.
E.g. I got <a href="javascript:myfunc('hello')"> and someone changes that to <a href="javascript:myfunc('NOThello')">. Can I immediately detect this change somehow?
Thank you.
No, you cannot.
You could obviously write code to check to see if something was the way you wanted it to be, but guess what? People could change that very code to bypass the detection. Web pages are complete insecure. You cannot trust anything in them. They can be easily altered - any part of them can be altered including HTML, javascript, etc... And, using debuggers is not the only way to alter web pages - there are many different techniques including things like active proxies.
You MUST verify and check on the server anything that is being submitted to a server because you simply cannot trust its origin. For example, people use client-side javascript to validate data that is entered into forms all the time, but this is ONLY done to improve the user experience if something is entered incorrectly (so you can more easily tell the user something is wrong BEFORE the data is submitted to the server). All validation checking must also be done on the server to make sure that only valid data gets into your server.
Ah, right, you're just curious about how to do that!
I can't reproduce your test case, but here are the options I see:
using a recursive setTimeout or setInterval checking when the element has been altered, but that is highly slow and ugly
using mutation observers, and unset the changes
Florent
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.
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.