Getting user agent value. Server side vs Client side? - javascript

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.

Related

Execution timing, AMPScript / JavaScript?

I am interested in using JavaScript on an ExactTarget landing page.
I'm hoping that the JavaScript I have on page can examine a cookie value, and based on this cookie value, set a variable in AMPScript.
If I were to use SSJS, would the JavaScript execute before the AMPScript, which would work as I hope, or would the AMPScript execute first, followed by the SSJS?
You can't mix Server-Side JavaScript and client-side JavaScript. AMPScript and SSJS are both evaluated before the page is displayed. Setting a cookie value is a client-side operation, so there's no cross-over. However, you can use SSJS to output client-side JS.
SSJS is translated to AMPScript, so there's an additional overhead associated with its use.
I frequently use both SSJS and AMPScript at the same time in landing pages. Some things are easier and/or not supported in one or the other.
BTW, there is a lot more SFMC dicussion going on over in http://salesforce.stackexchange.com.

How can I prevent someone from altering or avoiding my JavaScript logic when adding buttons to jQuery UI dialog?

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.

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.

Javascript bridge to Flash to store SO "cookies" within flash

After reading this on the question How do I uniquely identify computers visiting my web site?
:
A possibility is using flash cookies:
Ubiquitous availability (95 percent of visitors will probably have
flash)
You can store more data per cookie (up to 100 KB)
Shared across browsers, so more likely to uniquely identify a machine
Clearing the browser cookies does not remove the flash cookies.
You'll need to build a small (hidden)
flash movie to read and write them.
I tried to find if someone has already done something like this, so I wouldn´t have to reinvent the wheel. So far, no luck(maybe I don´t know the right term to search), except for the code in the flash side
The use I have for this is to prevent a user to answer a quiz multiple times, but future uses maybe banning trolls.
Does anyone knows a open source library that does this and allows me to access via javascript?
Caveats: I don't know flash and I don't own a license.
Edit: You can do that using evercookie. It's kind of evil, but works.
To build on what rmeador said, and to help get you started, you are going to need to know how to use two classes in the FLEX3 API, SharedObject and ExternalInterface.
SharedObject will allow you to store and retrive data from a client computer and ExternalInterface will allow your actionscript to communicate with your javascript.
Using shared object is simple.
To put data onto a users machine just create a SharedObject and add properities to the sharedObject's data properity.
private var sharedObject : SharedObject = SharedObject.getLocal("myCookie");
sharedObject.data.DATA_FOR_THE_COOKIE = DATA;
Retriving data from the SharedObject is just as simple. Make sure the size of the SharedObject is greater than 0 (Make sure the SharedObject exists) and the just look up the properity names through the SharedObject's data properity.
if(sharedObject.size > 0)
// access data from cookie with -> sharedObject.data.DATA_FROM_THE_COOKIE;
To pass the data stored in the SharedObject to your javascript you are going to need to use ExternalInterface.
Lets say you have a javascript function to retrieve the variables
function retrieveVars( vars ){
// Do something with vars.
}
To call this function from actionscript you will use
ExternalInterface.call("retrieveVars", DATA_ITEM_1, DATA_ITEM_2, ...);
Its that simple.
Please note that this technique will not work if the client's flash player has its storage settings set at 0, or if the client's browser does not have ActiveX or NPRuntime.
I'm hesitant to answer your question, because it sounds like this is straying dangerously close to Evil... Also, it's doomed to failure. If you really want to prevent a user from answering a quiz multiple times, the best thing you can do is have them register a user account. If you want to prevent them from registering multiple user accounts, you can have them verify something through a credit card or snail mail, both of which are generally untenable solutions. In short, the internet is anonymous.
Anyways, if you really want to go forward with this plan, you can build your application in Flex (a variant of Flash) fairly trivially. There's tons of documentation on the Adobe site. Some of it is rather sparse and annoying, particularly the collections API, but it'll be sufficient for your purposes. ActionScript (the programming language underlying both Flash and Flex) is very much like JavaScript and easy to learn. Flex has a free SDK (usually available in a small link from the page that tells you to get the expensive Flex Builder; Flex Builder is a primarily GUI tool, whereas you'll be writing straight code without an IDE with just the SDK), so a license shouldn't be a problem. The JavaScript to Flash bridge is also well documented.
BakedGoods seems to be exactly what you need (or rather, what you did need); its a Javascript library that establishes a uniform interface that can be used to conduct common storage operations in all native, and some non-native storage facilities, including Flash Locally Shared Objects (the "cookies" you speak of).
With it, creating an LSO can be accomplished with code as simple as:
bakedGoods.set({
data: [{key: "key", value: "value"}],
storageTypes: ["flash"],
complete: function(byStorageTypeRemovedItemKeysObj, byStorageTypeErrorObj){/*code*/}
});
Retrieving and removing data is just as easy. Trust me on all of this, I would know; i'm its maintainer :)
If for whatever reason you'd prefer to roll out your own solution, rmeador and ForYourOwnGood have supplied you with enough information to help you get started.
They've forgot to tell you how to do one very important thing, however: how to access, with Javascript, the Actionscript code that will handle the Shared Objects.
First, you will need to encapsulate your ActionScript code in a method, and then register that method as part of the ExternalInterface of its parent application:
function handleObjects(/*param1, param2, ... */):void {/*code*/}
ExternalInterface.addCallback("handleObjects");
Second, you will need to compile your Actionscript application (your code), and create an element in your HTML that references the resultant .swf file.
Then, assuming the aforementioned HTML element is represented as a DOMElement named flashDOMElement, you can call your method with the DOMElement:
flashDOMElement.handleSharedObjects(/*arg1, arg2, ... */);
And that's it! There are a couple of things that we've failed to mention or skimmed over, but all in all, rolling out your own solution is not hard. Rolling out your own reliable solution, however, is a different matter, which is partly why I suggest you use BakedGoods.
For people searching for this now, be sure do check out evercookie.
Evercookie definitely gets the job done, but this is a little closer to what you were originally asking for: https://github.com/nfriedly/Javascript-Flash-Cookies MIT license.

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