Presentation on HTML5 Security, Part-2 - OWASP Hyd

In continuation my previous talk on HTML5 Security at OWASP Hyd, I have covered few more interesting concepts at OWASP Hyd August meet. Slides are more or less the same as my previous session but it was more demo driven where I've shown known security problems and secure coding practices to be followed while using HTML5. 

I've been committing some of the basic demos whenever I find time into my github account. I shall blog more about some interesting topics very soon.

Browser Internals: Content Isolation with Same Origin Policy-Microsoft UG Dev Day

Microsoft User Group Hyderabad (MUGH) has organized Developer Day at Broadridge Financial Solutions, Hyderabad this weekend. It was a half day event with very good line up of sessions and I had the opportunity to present on a very exciting topic-"Content Isolation with Same Origin Policy".

"Same Origin Policy (SOP)" is one of the foundations of web security, which is built into web browsers. Web developers often do not understand this policy clearly and work with several misconceptions. The goal of this session is to show how important SOP is for the web, how it is bypassed using hacks and what HTML5 offers as a standard to overcome its limitations. Getting a full understanding of SOP isn't easy in a one hour session as it is relatively vast and complex. However, I have tried to simplify several ideas and put them in one place in the slides. Folks who couldn't attend the session will also be benefitted from the slides.

Along with my talk, there was an interesting talk "One Service, Any Device, Any Platform-Web API" by fellow MVP Shravan and "A Lap around the new Windows Azure" by our super techie Phani, cofounder of BrainScale. It is really motivating to see close to 100 techies coming to learn cutting edge stuff over a weekend. That was a great time spent! See you in the next tech event. Happy coding :)

HTML5 Sandbox and some notes

While building mashups, one of the primary goals is to securely isolate content coming from different origins. Generally, client side mashups are built in one of the two ways-(1) Embedding third party scripts in a web page (2) Loading remote content via iframes. Embedding scripts provides more interactivity but dilutes security since the scripts run with full privileges and could be malicious. Using iframes reduces interactivity but enhances security since they isolate content via same-origin-policy (Script inside a cross-origin iframe cannot access DOM of parent page).

[Note: By chance if you are wondering why you should bother about mashups since you have never built them, you are mistaken. If you are embedding scripts for website analytics, social plugins (Like, Tweet, +1 etc.), advertisements, comments system (e.g., Disqus) and so on, you are already having a mashup!]

Though iframes follow same-origin-policy and provide security in some sense, they are well known for their notorious activities like frame phishing, top window redirection, clickjacking, triggering drive by downloads etc. The “sandbox” attribute for iframes which is introduced in HTML5 promises to thwart the problems caused by iframes. Sandbox is currently supported only in Internet Explorer 10, Chrome 17+.

A sandboxed iframe by default disables script, popups, form submissions, top navigation etc. Some of the restrictions can be relaxed by specifying space separated white list tokens (allow-forms, allow-scripts, allow-same-origin, allow-top-navigation).

<iframe sandbox src="http://crossOrigin.com"></iframe>
<iframe sandbox="allow-forms allow-scripts allow-same-origin allow-top-navigation"
src="page2.html"></iframe>


The details about sandbox and its white list tokens are discussed in several blogs, hence purposefully omitting it here. One interesting feature in sandbox is, when a sandboxed iframe loads content from the same origin as the parent document, the loaded content is still treated as if it originated from cross origin, thereby reducing its script privileges. This restriction can be removed by using the token “allow-same-origin”.

Below are some of the cases where developers have to be cautious while using sandbox.

Disabling Clickjacking Defense:

Even till date, several sites rely on JavaScript based frame busting defense to get rid of clickjacking (X-Frame-Options response header is a better defense, but unfortunately has lesser implementation). Such sites when embedded in a sandboxed iframe are greatly affected. Since sandbox disables JavaScript, the clickjacking protection used in the framed site is lost, hence back to square one!

Allow-scripts and Allow-same-origin combination:

This combination of tokens is a little tricky and could negate the effect  of sandbox. The “allow-scripts” token enables JavaScript inside iframe and the “allow-same-origin” token will give the iframe complete privileges to access DOM of the parent. So if the embedded iframe has a vulnerable input field, script can be injected to remove the “sandbox” attribute altogether and then carry further exploits. Thus the security benefits of sandbox can be removed completely.

Effect on Nested Browsing Contexts:

If a webpage has nested browsing contexts (page containing an iframe which in turn loads another iframe), then reasoning about the effect of sandbox tokens becomes complicated. Let us consider the scenario in the image on the right below-a parent page has an iframe to a page (Child1) with "allow-scripts" sandbox token. Child1 loads another iframe which points to Child2 having "allow-forms" token. At a quick glance, developers may conclude that the innermost page will have both forms and scripts allowed, but it is on the contrary. The inner page has everything disabled and for a good reason! The child1 frame has forms disabled and it will overwrite the "allow-forms" of Child2. Also, Child1 has scripts enabled but Child2 has them disabled. Hence it does not allow script execution. So it is advisable not to manipulate sandbox tokens dynamically, since it is difficult to reason about the after effects on sandbox restrictions.

DEMOS: Click the images for demos (Source at: https://github.com/novogeek/html5sandbox )

Sandbox demo 1

Sandbox demo 2

 

 

 

 

 

 

 

 

 

In the first demo, there is an iframe with JS based clickjacking protection and by default sandbox option is selected. You can see the clickjacking defense by selecting “normal frame”. So this shows how sandbox defeats JS based clickjacking defense. Also in the same demo you can select “allow-scripts” and “allow-same-origin” optons and inject the snippets provided below the page into the XSS vulnerable page.

In the second demo, inspect the iframes and load them independently in different windows and to see the effect of sandbox tokens in nested browsing contexts.

Hope the article provided some useful information about HTML5 Iframe Sandbox and its secure usage. Feel free to get back with queries or please share aspects which you feel interesting about Sandbox. Happy coding Smile

Presentation on HTML5 Security-OWASP Hyderabad

Happy to say that I had the opportunity to present at OWASP Hyderabad chapter on "HTML5 Security" on 19th May, 2012. The event had awesome audience from diverse backgrounds in security domain-security researchers, penetration testers, security consultants, few developers etc. The talk went for about 2.5 hours(yes!!) and was quite interactive. The audience were very patient, passionate and we had lots of discussions on several interesting topics.

 

I have built some cool demos for the presentation but the code is not well organized. I shall clean the code and upload to my github account shortly. I would be continuing this talk in next month's OWASP meet too.

JSFoo Chennai 2012–”JavaScript is mischievous. Handle 3rd party content with care!”

It is always exciting to attend a technical conference focusing on a particular theme and even more if you get the opportunity to present. Continuing their good run, HasGeek has organized JsFoo Chennai 2012, India’s first JavaScript conference series, at IIT Madras Research park. There were several interesting proposals made and mine got voted for the final schedule along with other awesome entries.

My session is about the security considerations one should think of while integrating 3rd party JavaScript content into their site (in other words, security of web mashups). 

mashups

Presentation: Click here

Demos: Recursive Mashup Attack and Clickjacking

Learning aside, the best part is, I’ve met several awesome passionate geeks, few whom I know on twitter and few I would have never met otherwise. Loved the event even more, since people working on different platforms and having good expertise in JavaScript came under one roof and discussed. Diverse opinions and lots of learning!!

For those who missed, check JsFoo site for videos of sessions, which will be uploaded shortly. Also, here is an interesting review written by one of the attendees.

The need for HTML5 postMessage API

The postMessage API in HTML5 specification is useful for making cross domain calls across frames. This is typically useful for mashups, Web 2.0 sites (e.g., pageflakes.com) where different widgets might need to communicate with each other.

HTML5 postMessage Demo

Few developers have already started using HTML5 postMessage in their projects, without knowing why they are using. Here are a couple of questions an inquisitive developer might have in mind:

1. How are mashups and rich Web 2.0 applications built even before HTML5 postMessage API came into existence?

2. What is the trust model which Web 2.0 sites have? (Who trusts whom?)

3. Is there really a need for a new API when workarounds met the needs?

This post tries to answer these questions and explains why postMessage API is important. Though the usage of API looks trivial, the birth of this API is the outcome of several insightful research papers, which are also a motivation for this post.

In the screenshot, the web pages loaded in the top window and iframe are from different domains. On clicking the submit button, the message in textbox is sent to iframe and displayed in the last line. Notice that the top window url (http://localhost/postMessage) has a default port number(80), while the iframe has a different port number (81). Hence the site in iframe is treated as that from a cross domain.

HTML5 postMessage API is as simple as the below JavaScript code.

<script language="javascript">
        window.onload = function () {
            win = document.getElementById("ifrDomain2").contentWindow; //get the target iframe window
            frm = document.getElementById("frmPost");  //get the form which needs to post a message
 
            frm.onsubmit = function (e) {
                msg = document.getElementById("txtMessage").value;  //get the message to be posted from the textbox
                win.postMessage(msg, "http://localhost:81/");  //post the message to the destination URL
                e.preventDefault();  //prevent default action (suppress postback)
            };
        };
</script>

Now let us see why such an API is needed in the first place and try to answer the above questions.

Same Origin Policy and Trust Model:

As most of you know, the Same Origin Policy (SOP) of browsers disallows scripts loaded from one origin to access DOM of another origin (Two sites do not belong to same origin if they differ in at least one of the three- protocol, domain name or port number). Due to this, an AJAX call cannot be made from one domain to another domain from a browser. So far so good, since if this policy is not in place, an attacker can make an AJAX call to your site and grab your cookie.

However, the SOP is not applicable to scripts themselves! Developers can always embed script tags which point to different domains (just as we include reference to jQuery or any JS library from CDNs). If there are scripts from multiple sources, the application is not secure. But this is how mashups and most of our web applications are built! Isn’t this ironical? Moreover, the scripts which are loaded from different domains run under the privilege of the host site. So whether it is external script file or JSONP script injection, the developer should have ‘complete trust’ on the scripts being injected.

As Douglas Crockford rightly points, “A mashup is a self-inflicted XSS attack”. It is more of a work around than a standard.

Instead of loading external scripts in an integrated site, an alternative is to use iframes to load external sites. Since iframes provide complete isolation mechanism, aggregating content is secure, but genuine communication between frames goes for a toss.

Most of the modern Web 2.0 sites rely on external JS libraries, AJAX and JSONP techniques for fetching, manipulating content. In this case, communication between widgets (divs) is not a problem since entire DOM is accessible to any script (bad design w.r.t security as discussed above). Sites using iframe for isolating widgets rely on “fragment identifiers” (e.g., yoursite.com#message) for communicating between widgets (has confidentiality but no authentication and integrity). These (flawed?) solutions answer our 1st question.

So the trust model we have is, you as a developer/site owner should either trust all (in case of scripts) or trust none (in case of iframes), but nothing in between. This answers our 2nd question. You may trust the JavaScript provided by Google analytics, maps, facebook widgets etc., but this dependency on ‘trust’ does not scale well.

Browser vs. OS:

The modern web has seen data intensive, rich and interactive web applications, which mimic desktop applications. Mashups, which are applications that combine data from multiple data sources, have changed the boundaries of a web browser. Concepts like Web OS started evolving which guided researchers to draw a parallel between browsers and OS.

  • The “system calls” in OS are analogous to “DOM calls” in browsers
  • “Processes” in OS are analogous to “Frames” in browsers
  • “Disk storage” in OS is analogoius to “cookies, localStorage, IndexedDB etc.” in browsers
  • In an OS, “Users” are the principals (which need to be distinguished), whereas in a browser, “Origins” are the principals.

Browsers, which were designed to handle pages from a single domain at a time are now forced to handle pages/data from multiple domains. In other words, as researchers say, web browsers have evolved from a single-principal platform to multi-principal platform. However, unlike OS which can easily handle multi-user scenarios, web browsers prior to HTML5 postMessage did not have the capability to abstract multi-principal scenarios. Their trust model remained the same as discussed above.

Hence, there is a need for a newer standard supported by browsers, which can securely abstract multiple principals and provide communication between them, thereby improving the trust model (answers 3rd question). There were several recommendations like JSONRequest, Verifiable Origin Policy, CommRequest etc.,as described in the references, for solving these problems and finally, the HTML5 postMessage API came into existence.

//Syntax of HTML5 postMessage
otherwindow.postMessage(message, targetOrigin); //Clearly, the "targetOrigin" parameter improves trust!

The postMessage channel, which is designed for cross site communication, guarantees confidentiality, integrity and authentication and improves trust (A frame can now communicate with a trusted frame by specifying the target). With this standard in place, frames can now be attractive feature to integrate 3rd party content, create widgets with improved trust. It is supported by majority of modern browsers (IE8+, FF3+, Chrome, Safari, Opera 10+).

Hope the article helped in understanding why HTML5 postMessage is needed and possibly pointed out the mistake you are doing by not using it for your requirements. Let us build a more secure and standard compliant web, one website at a time Smile

References:

1. “Securing Frame Communication in Browsers” – by Stanford web security lab

2. “Protection and Communication Abstractions for Web Browsers in MashupOS” – by Microsoft Research & Stanford web sec lab.

TechEd on the road-new features in ECMAScript 5

Happy to say that today I have presented at "TechEd on the road", a developer conference at Microsoft Hyderabad, on "JavaScript APIs and enhancements in ECMAScript 5". It is one of the premier tech events, organized by Microsoft User Group Hyderabad (MUGH) with audience in both developer and IT Pro tracks.

 

As in most of my sessions, I tried to use web based presentation instead of traditional power point. I developed my presentation using HTML5, jQuery and leveraged the new features of ECMAScript5, just to showcase a real time demo.  The response of the audience and fellow speakers was very cool and probably the presentation was worth the effort :)

 

Presentation & Demo: Click here

 

Note that you need ECMAScript5 supported browser to run the slide show. You will get a prompt if your browser doesn’t support ES5. Run it in full screen and use 'right', 'left' keyboard keys to navigate.

 

For the presentation, I have checked several existing solutions like S5, HTML5rocks slides etc., but I wanted inline code snippets as demos . So wrote my own slide show system and it came out well. Probably, I shall write another article on how I have developed it.

 

Have thoughts of generalizing this web based slide show and releasing it on github/codeplex. Play with the presentation and get back with your thoughts :)


Update: You can check about the proceedings and pictures of the event in my friend Phani's blog.

Inspire the web with just 10K!

That was the caption of the 10K coding challenge hosted by An Event Apart, in association with MIX Online. The challenge is to build a web app in less than 10 KiloBytes. The rules are:

  • Total file size, including images, scripts & markup, can’t be over 10K.
  • Apps should work equally well in IE9 Dev preview, Firefox and webkit browsers. HTML5 can be used.
  • jQuery/Prototype/Typekit can be used and they won't be counted against 10K.

It is really amazing to see excellent hacks written under just 10K. One of my favorite geeks from Yahoo, Christian Heilman wrote a World Info hack using free services under 4.83 KB!! It fetches list of all countries in the world & on selection it will fetch the country's map, wikipedia info n stuff. Interesting..isnt it? There are around 400 of interesting ideas/hacks submitted, which are a source of great learning. Most of the prize winners are smart coders of JS based games.

My 10K Hack:

I have submitted a quick, dirty hack - 10K Start page. The idea is fairly simple, to have an ajax start page like iGoogle, PageFlakes, NetVibes but under 10K. Though it is not possible to add all the modules and beautify like the big guys did, I tried to have maximum possible features under 10K. I have used jQuery, HTML5, Yahoo Query Language (YQL), CSS3 to build the app. The app has 4 widgets- Twitter search, Yahoo weather search widget, sticky notes widget and a generic RSS reader widget. New widgets can be added, removed, dragged & dropped.

YQL queries: Thanks to Yahoo! For sure, I cannot think of a way other than YQL to build a mashup so quickly. I used JSON format so that parsing on JS would be optimal and easier. Here are the YQL queries which I used:

Twitter search widget: Click here
Yahoo weather widget: Click here
RSS widget: Click here

So, for the above 3 widgets, all my JS codes involves fetching data from these YQL services in JSON format, parsing them and displaying in corresponding divs using jQuery. 

HTML5 features:

ContentEditable: For sticky notes widget, I just placed a div tag like this: '<div contenteditable="true" class="sticky">Edit this sticky notes...</div>'  The "contenteditable" attribute is a new attribute defined in HTML5 specs, which makes a div editable on click and readonly on mouse out.

LocalStorage: It is a client side key value database, which can be used to store data in user's browser. I'm using this to save the layout on "window.onbeforeunload" event and restore the layout on pageload.

Adding/Removing/Draging widgets: All these operations are simple jQuery based DOM manipulations. For drag & drop, I'm using jQuery's jqDnR plugin.

Participating in such events is real fun, as we don't often try to think in terms of minimalistic code.At the last minute, I had to even do the optimizations like renaming "jQuery.js" to "j.js", just to reduce 5 bytes!! 

Have any suggestions/comments? Please let me know.