My JavaScript book is out! Don't miss the opportunity to upgrade your beginner or average dev skills.
Showing posts with label data. Show all posts
Showing posts with label data. Show all posts

Wednesday, August 24, 2011

Simulate Script Injection Via Data URI

Well, not only downloads on the fly, the data uri works for almost everything ( only iOS 5 beta does not want to work with inline data uri AUDIO sources .... but this is another story ... ) ... so ...

How To Simulate Script injection

Let's say you want a test but you don't want to bother a server. However, you want to be sure the test is asynchronous and it simulates the server.

var
head = document.getElementsByTagName("head")[0],
script = document.createElement("script")
;
head.insertBefore(script, head.lastChild);
script.src = "data:text/javascript;base64," + btoa(
"alert('Hello World')"
);


How To Simulate JSONP

Same trick, isn't it? ... except:

script.src = "data:text/javascript;base64," + btoa(
"callback(" + JSON.stringify(dummyData) + ")"
);


How To Drop Server Requests

well, this is the tricky one ...

Surely there is some job to do in the createResponse() function but ... hey, we can stop bothering servers now ;)

Monday, November 23, 2009

On element.dataset And data-* Attribute

Why on earth? I mean why we should put a data-whatever attribute into our layout? Where is the good old MVC? How can you consider data-* more semantic? more semantic than what? Why we would like to kill truly semantic pages and graceful enhancements? Why we need JavaScript redundant info inside nodes attributes but we cannot understand a script tag in the middle of the page? Why in the performances matter era we would like to let users download stuff that they will probably never use?

What Am I Talking About

We can find the "magic" data attribute description in the W3C Semantics, structure, and APIs for HTML documents page. These days there is a page that is going around even too much ... finally somebody realized that this data-thingy is nothing different than what we could have always used since ages: XML.

Why We Are Doing Wrong

If we are enthusiast about a custom attribute able to bring whatever information, we should ask ourself why on earth we are not using simply XML plus XLS to transform nodes with custom attributes. Each node can be easily and quickly transformed, in the client side as well and in a cross browser way, via one or more cached XSLT able to create runtime whatever we need.
We need to sort the music file list via data-length attribute? No problems at all, we can reorder via DOM every node we need and put the XML fragment transformed via XSLT into a single HTML node in that page. Moreover, we can use modular XSL to transform branches or specific cases ... but that is too clean and professional, isn't it?

Data Used Via Selectors

Let's say we have 3 songs with the same length, taking the example from W3 page, OK?

<ol>
<li data-length="2m11s">Beyond The Sea</li>
<li data-length="2m11s">Beside The Sea</li>
<li data-length="2m11s">Be The Sea</li>
</ol>

First of all that example is quite hilarious, to make a sort as fast as possible that kind of representation is not ideal, is it?
It does not matter, the point is that as soon as this stuff will be implemented, all jQuery users will start to think so semantic that everything will become a:

$("@data-whatever=whatevervalue").each(...)

Seriously ... if we want to make the web the worst semantic place ever, just put in medium skilled developers this kind of weapon, and we'll scream in few months HTML5 Failed!
Who will care anymore about the appropriate element when everything can be easily validated in the W3 for totally dirty and useless, for non JS users, layouts?

The Namespace War Has Started Already

I can imagine lots of new devs starting to use the data as if it is their own attribute, ignoring conflicts problem we've always had with the global namespace. Move this problem into the DOM, and the Cactus Jam is ready to eat.
On the other hand how best practice will be a DOM loads of nodes with multiple data attributes?

<div
data-jquery-pluginname-good-stuff="$(this).whatever()"
data-dojo-loadsync="thisNodeFile"
data-prototype-valueof="Object.prototype.valueOf=this"
/>

... I mean ... seriously, is this the HTML5 we are talking about? An empty element there just to make the anti semantic magic happen?

Dozens Of Different Ways

First of all querySelectorAll.
The document method we all were waiting for is finally 90% here and rather than use semantic and logic selectors to retrieve what we need and when we need, we prefer to make the DOM that dirty? Are we truly so monkeys that we cannot spot a list of songs and order them by their length that will be 99.9% of the time part of that song info and accordingly present in the DOM as context?
Where are classes? Where are external resources totally ignored by those users which aim is simply the one to surf quickly, or to crawl info? data-whatever?

Why We Don't Need data-*

First of all, classes. If we have a list of songs the class songlist in the single outer UL or OL node is everything we need to retrieve that list and order by title, duration, everything else present in that list, since in whatever grid we have ever used, we order by columns where we know the column content.
How can a user even decide to order by length if this length is not displayed?
How can he order by something not even showed?
It's like me in a shop asking to order by palm trees a list of sounds systems ... I think they'll look at me like a mad person and they would be right, don't you agree?
So, the semantic part of this attribute does not exist. The same example showed in the W3 draft is ridiculous for the reason I have already said. If the song length info is already in the DOM and properly showed we don't need redundant info for every user, we just need a good sort function for that list of songs and nothing else.

$.fn.sort = function(){
// proof of concept, not even tested
// written directly here in the blogger textarea
// don't try at home but please try to understand the logic
var li = Array.prototype.slice.call(this);
li.sort(function(a, b){
return
$(a).find(".length").text() <
$(b).find(".length").text() ?
1 : -1
});
return $(li).each(function(i, li){
li.parentNode.appendChild(li);
});
};
$(".songs li").sort();

Is above proof of concept that different from a $(".songs @data-length").sort() ? It's even shorter!

Map The DOM If Necessary

If we are struggling that much with this "so much missed data-*" we can still use the class to map common info ... how?

<ol class="songs">
<li class="map-0">Beyond The Sea</li>
<li class="map-0">Beside The Sea</li>
<li class="map-1">Be The Sea</li>
</ol>

If we need to attach properties into a DOM node we can still use the class attribute.
Semantic, classifying the node as a mapped one, not redundant, letting us provide more than once same kind of info for different nodes, and lightweight, avoiding data description provided by the mapped object.
In few words, and always via JavaScript, we can attach a file with this content:

var map=[{
length:"3m21s",
artist:"Nature"
},{
length:"2m59s",
artist:"You"
}];

For each node, when necessary, we could simply retrieve the associated map in this way:

function nodeInfo(node){
return map[
(
/(?:^|\s)map-(\d+)(?:\s|$)/.exec(node.className) ||
[0,-1]
)[1]
];
};

And that's it. Each mapped node will return an object or undefined when nodeInfo function is called. Again, all this stuff is a proof of concept, but can we agree that data-* is just the wrong response to solve a JavaScript problem that should be solved everywhere except into the HTML?

Sunday, November 15, 2009

Inline Downloads with Data URLs

A quick post about another silly idea ...
With Data URLs we can incorporate images in layout or CSS.
The schema is really simple:

data:[<mediatype>][;base64],<data>

Since we need to specify a mediatype we could play around creating something unexpected ;-)

My Silly Idea

If we select something in a web page we can perform different actions via right click. So far so good ... but one thing we are missing, at least in Firefox, is a "Save As" option. If we want bring a piece of code, text, something else, into another software or editor we need to select, right click, copy, open or find the editor, right click, paste.
The ultra skilled developers goes well with ctrl+c and ctrl+v but there are still 3 operations to do: copy, find the destination, paste
What about making possible to simply save that part and go on reading or surfing in order to do not distract too much our lecture and review eventually later that piece of text or code?

Firefox Inline Download


function download(text){
// Yet Another Silly WebReflection Experiment
var iframe = document.createElement("iframe");
iframe.src = "data:application/octet-stream;base64," + btoa(text);
iframe.style.position = "absolute";
iframe.style.top = "-10000px";
document.documentElement.insertBefore(
iframe,
document.documentElement.firstChild
);
};

download("Hello World :-)");

If we have configured Firefox to ask us where to save files, we can even choose the name. Being the inline data protocol that simple, unfortunately I could not find a way to name the file. The concept in any case is simple, we could create a bookmark or a link able to save the selected text, if any.
In this case we select, and with a click we can directly organize the content in a named file or we can open it with the editor that will be probably the first option in the Open With question.

Side Effects

Well, the first one is that I am not even sure if this could be considered a security problem, and I am testing in Firefox 3.6 beta 2 (so I am not even sure this is possible with other versions).
We cannot remove the iframe until the user has saved the content and never before the save dialog will be showed, otherwise a generic onload will remove the content before Firefox can understand what to do.
On the other hand, since the content will be inline, the "Open With" should always work 'cause Firefox, which is a clever browser, saves and eventually remove, even if we cancel the operation.

Conclusion

Nobody will probably ever use above snippet, but I thought it was an interesting and new way to manipulate a technique used for totally different purposes (OK, I have to admit the only excuse I have is my new netbook and I had to test some code after Notepad++ installation :D)

Tuesday, September 09, 2008

Internet Explorer Security Hole - A Better Example

Again, about the security hole I talked about last posts, but this time with a really simple example.

How does the example work



  • Open Internet Explorer, whatever version

  • Go in this page

  • Write a fake user name and a fake password, or a fake email address and a password

  • Click Submit



What does the example do



  • Emulates user actions via javascripts

  • with some version of IE, it could be able to grab both fields values

  • in any case, it demonstrates you that every site could steal your compiled fields in every other site, if the autocomplete option is not forced to be disabled



What could do a malicious, and hidden, code



  • steal your data

  • steal your email

  • steal your credit card information (a really famous company, as example, suffers this problem, so somebody could steal credit cards details of million of people)

  • steal your details

  • steal your searches via common search engines

  • etc, etc



More details in my old post I wrote last Saturday, the one that few people read carefully, understanding what was going on.

This is not a new bug, it exists, and I knew it, since 2004 or before, when banks did not use security checks, yet.

Kind Regards, and please choose another browser until Microsoft will not fix this problem for every IE.

Thursday, September 04, 2008

Security Basis, and an Internet Explorer data stealer

It has been about 4 years, or more, that I know about this problem, but for some reason I did not talk about it, scared by possible reactions.

In other words, I was waiting for some noise over the net, or some fix from Microsoft, but nothing is happening.

Actually, Microsoft is working hard on Internet Explorer 8, but the problem I am talking about, is still present ... so, I suppose it is time to tell you how dangerous this IE "feature" could be, and how dangerous could be to forget a little detail in a form, like the autocomplete attribute.

The magic autocomplete option


Every browser tries to make our net life as simple as possible, and when we start inserting data in an input field, it suggests us a couple of words or, if the name of that field is unique enough, directly the most probable word, name, or number, we are going to insert.
To perform this operation, we could start typing the name, or simply use the down arrow button to open the list of options, and choose, usually, the first one.

More magic than ever


In some old Internet Explorer versions, like the the 6th one, when we are filling out a login form, we simply need to insert the name, or email, and the password field will be magically populated.
This means that with 3 buttons, 2 down arrows, and 1 enter, we can perform a login.

Magic IE JavaScript


Internet Explorer allows JavaScript developers to fire events simulating user mode.
This means that if we have a focus on an input field, and we fire the keydown event, with down arrow code, the suggested list of options will magically appear.
At the same time, if we repeat the procedure, the first option is highlighted, and if we repeat the procedure again, the second option and so the third one, if any.
More beautiful, is that if we fire the event another time, this time using the enter code, the field will be populated.

How to steal information from the Internet Explorer users


Accordingly, if a malicious website is replicating a form, which user has filled out ones on a genuine website and a dedicated JavaScript starts automatically interacting with the replicated form, the Internet Explorer will silently expose user's information, previously used in "who knows" how many different websites.
A simple, well organized process could try different combinations N times, saving results in an object, or an array, and then sending that information via ajax or a basic get request to a server, allowing the malicious developer to save and reuse that information.

A real world example


To show you what I am talking about, I have created a simplified version of the described script.
Most important things to remember:

  • any displayed information, if any, will not be saved, but only displayed in an alert window, so with my example your data is still your one

  • only Internet Explorer, as far as I know, allows JS developers to create such malicious code to embed in a webpage (that's why I posted about FireFox crash, few days ago :))

  • apparently, IE8, and probably 7 too, do not let developers steal entire login information


To perform this test, you need to use Internet Explorer. If you have never used, or used it only to debug or develop some web applications, please try to login into your favourite web services, for example Gmail.
After that you can directly test my safe example page, and wait few seconds to know if my application was able to get your email account, or whatever else information.

Which websites expose user information?


I am sure this problem is not a secret for Microsoft IE Team, since in every login form, starting from hotmail, they force the atocomplete option to off.
Therefore, it is not possible to steal, for example, hotmail emails, but if you use the same address to login in to another website, which for some reason does not implement the autocomplete off option, it becomes obvious how thousands of spammers can obtain our email addresses in such an easy way.
Gmail login service (surprise!) does not implement the autocomplete off option, so if we use Internet Explorer to login into latter service, our Gmail account name could be easily exposed.
The worst case scenario ever, is represented by Credit Card Forms, where if nobody though about this "little security problem", our Account Name, Credit Card, Verification Code, and whatever else private information, could be grabbed by malicious websites, without us noticing it.
Of course, the expiration date is not that simple to retrieve, but what a powerful weapon this IE feature can be to enhance phishing?
Just try to imagine a page, with similar URL, that already contains all information, but misses only the expiration date, requiring user verification.

As Summary


Other browsers probably know about this problem, since nobody lets JavaScript interact with webpages in the real user mode.
The fix I can simply suggest, is to disable the autocomplete option in Internet Explorer or, even better, change the browser to be sure that if we are inputting our details on a website, that information will not be readable from any other website without our authorization.

Have a nice week end :P

Thursday, August 28, 2008

IE8 Beta 2 - inline images, and anything else

With IE8, we finally can "play" with inline images, specially for CSS or other little decorations.

The main limitation is that the length of the data protocol has a maximum fixed length, but even worst is that IE8 apparently introduced the data protocol only for images.

In another scenario,where we would like to use the same technique for other purposes, IE is still the only browser that does not respect standards.

This is an example:

function evalazy(src, callback){
var script = document.createElement("script"),
body = document.documentElement;
if(callback)
script.onload = callback;
script.type = "application/javascript";
script.src = "data:" + script.type + "," + encodeURIComponent(src);
body.removeChild(body.appendChild(script));
};

Above function is able to evaluate valid JavaScript code in an asynchronous way, calling a callback, if any, when evaluation has been completed ( kinda load runtime an external script ).

Since functions like atob and btoa are still not standard, the script is evaluated as url encoded string.
But even using a base64 string, the result does not change, IE does nothing, or it could generates an error, the classic could not complete the operation due to error 800a03e8 if the body is not present, and in some case, it could even crash during next script execution.

evalazy("testMe = 123", function(){
alert(testMe);
});


In this case the problem is JavaScript, but since the data protocol has been only partially implemented, we will not be able to include every other kind of resource that is not an image.

Hoping I am wrong, and hoping they'll make data protocol more "efficient", let's play with IE8 and its new features, really, and generally, appreciated. Thanks IE8 team :)