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

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.

Related

client side scripting language that enables storing data

I am creating a browser extension that has to store data.
I am going to have the client side language read from the page which is a game,
and save data if mistakes were made , or the data is not already accessible.
basically i'm trying to make a bot for a choice decision game when the
posibilities and the questions are built in.
since the possibilities are final I would really like it if in some way i would be
able to actually make the bot play for an hour and then have a file containing
the entire game's deicisions.
well , I can't do that with javascript since it disables storing data,
am I able to do it with another language which has access to the html DOM?
I have no problem to even use some language that wasn't supposed to do that
and then write a small library for DOM accessibility, as long as it allows DOM
access, I have no idea which though.
edit: I haven't noticed I actually got answers to this. I realize the question is very vague(it's a very old one), but basically, I just built a simple html parser via python. I asked a friend of mine how I could build a bot, he said he simply did it by creating a browser extension, and I decided I'll give it a shot. anyways, yes, I should've resourced more into the browser's api and check for a way to store client's data.
I'm not sure to clearly understand what you want to do but maybe you could use the local storage of your browser with Javascript. It's a simple way to store a little amount of data in a webApp context.
EDIT 1 :
Here's a little sample to help you :
// Store
localStorage.score = 5000;
// Retrieve data
var score = localStorage.score;

How to avoid using JavaScript eval() in user-defined function

I'm trying to make a generic table-top RPG helper web app. It has to be generic because Wizards of the Coast is very protective of their copyrights. So, in order to avoid cease-and-desists, the system has to be capable of loading arbitrary rules. That said, my buddies and I (along with most any other user) will be using it for D&D.
In D&D, modifiers are based on a character's stats. To get a modifier, you take the stat, subtract 10, divide by 2, and round down.
function getModifier(statValue) {
return Math.floor((statValue - 10) / 2);
}
My app will be capable to loading a game's rules from a .json file. I want to be able to make this modifier function user-definable. The easiest way would be to just eval() whatever they provide in the .json file, but obviously that's a terrible idea due to security issues.
Unfortunately, I can't think of a simple way to get around this in a secure manner. Obviously I could write my own parser, but that's more complicated than I'd like/am currently capable of.
Ideas?
I did a quick google search and found two options - http://mathjs.org and http://jsep.from.so
btw. writing your own parser is not that difficult. You may be able to write one that's sufficient for your purpose in less than 100 lines of code
First, bear in mind that this is all on the client-side. So long as you trust the JSON (it came from your server or it is controlled alongside the application itself), then you can use it. That doesn't completely rule out some trojan inserting malicious rules, but I don't think botnets have learned to play D&D yet.
To literally avoid eval and provide some modicum of security, you can use new Function. It takes a list of argument names followed by the function body, allowing you a large amount of control over how the function is defined and where it can be referenced from. You only need to store the body in the JSON file, allowing you to largely control the parameters and make it difficult to assign to the global scope, minimizing your attack surface (such as it is) quite a lot.
If you want to have fun with this and now your rules will largely be mathematical, you may consider using a tool like pegjs to generate a parser for your rules. Calculators are one of the classic introductions to parsers and compilers, so this could be an opportunity to play with some fun tech. The rules and parsers built by pegjs are very easy to use in a JS project (I have an example using PegJS and ES6 via Babel).
There are two options as I see it. One, if you 100% want to define the function in .json, you will need to parse. JSON does not allow functions, so you need to store the function as a string and eval it.
The better way would be to also provide a config.js ability. Perhaps the .json would have a "configUrl": property, and then expose well known apis, eg RPGHelper.setModifer(someFunction) that you can call from inside the config.js file. The user is then free to define whatever arbitrary logic there.
One solution to your problem is to use sandboxed iframes (current supported by all major browsers
You run user code on a separate page, with limited priviliges, in such a way that the code does not interfere with the rest of the application. You can communicate with the sandboxed page using postMessage() and window.onmessage.

Isn't it dangerous to have query information in javascript using breezejs?

Just starting to play with breeze.js because of the obvious gains in coding time, i.e. managing to access model data from the server direct within Javascript (I am a newbie here, so obviously bare with!).
In the past I have used the stock ajax calls to get/post data to the server, and I have used a few different client tools in the past to provide some help in querying local data, such as jLinq.
My question is this. Isn't it dangerous to have essentially full model query access in Javascript? I must be missing something because it looks like a really well thought through tool. In the past I have at least controlled what can be sent to the client via the backend query process, and again using something like jLinq etc I could filter the data etc. I can also understand the trade-off perhaps with gaining the direct query/none-duplicating local model problem, so just if anyone could provide some insight to this?
Thanks!
EDIT
Obviously I am not the only one, however I am guessing there is a reasonable response - maybe limiting the data being requested using DTO methods or something? The other question posted is here
It can be dangerous to expose the full business model. It can be dangerous to allow unrestrained querying of even that part of the model that you want to expose to the client. This is true whether you offer an easy-to-query API or one that is difficult to query.
That's why our teams are careful about how we construct our services.
You should only expose types that your client app needs. If you want to limit access to authorized instances of a type, you can write carefully prescribed non-queryable service methods. Breeze can call them just fine. You don't have to use the Breeze query facilities for every request. You'll still benefit from the caching, related-entity-navigation, change-tracking, validation, save-bundling, cache-querying, offline support.
Repeat: your service methods don't have to return IQueryable. Even when they do return IQueryable, you can easily write the service method to constrain the query results to just those entities the user is authorized to see.
Fortunately, you can blend the two approaches in the same service or in collaborating services.
Breeze gives you choices. It's up to you to exercise those choices wisely. Go out there and design your services to fit your requirements.
Breeze isn't meant to be your business logic in that sense. Keeping in mind the rule of thumb that if you do something in Javascript, anyone can do it, you ought to be restricting the visibility of your own service data as needed.
In other words, it's useful for you if you meant to make the data publicly visible anyway. But only expose the entities that you're happy exposing and allowing anyone to query; another way to look at it is that your API becomes a public API for your website (but not one you advertise and tell everyone to use).
I am personally not a fan of doing things this way as there is a dependency created on the schema of the backend implementation. If I want to make changes to my database tables, I now have to take my Javascript into consideration. I also lack in terms of integration and unit testing.
However, it can have its uses if you want to quickly build a website feature on non-sensitive data without having to build the service methods and various layers of implementation of it.
What about when you expose the Metadata? Isn't that considered dangerous. IMHO is not safe to expose metadata from the DbContext. I know you can construct metadata on the client, but the point is to do things as quickly as possible(if safe).

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.

Categories

Resources