SlideShare a Scribd company logo
© 2009 Security-Assessment.com Reversing JavaScript Presented By Roberto Suggi Liverani
Who am I? Roberto Suggi Liverani Security Consultant, CISSP - Security-Assessment.com 4+ years in information security, focusing on web application and network security OWASP New Zealand founder/leader
Agenda Introduction Technologies: JavaScript, DOM, Ajax, JSON Security: JavaScript Security Model Practical tips JavaScript Analysis\Debugging Tools Finding vulnerabilities in JavaScript – DOM XSS Reversing JavaScript – Ajax Reversing JavaScript – JSON Obfuscated JavaScript – Deobfuscation techniques Dean Edwards Packer More complex cases
Technology - JavaScript JavaScript JavaScript provides five  primitive  data types: number, string, Boolean, undefined, and null. Number:  var x = 3.14; String:  var string1 = "This is a string"; Boolean:  var a = true Undefined and null do not store data.  var x;  var y = null; Reference  types includes the composite types (objects and arrays) and functions. Arrays and functions are special kinds of objects. Object:  navigator.appVersion  (navigator is an object) Array:  var x = myArray[5]; Each primitive type is associated with an object that provides methods useful for manipulating that kind of data.
Technology - JavaScript JavaScript Operators: Mathematical (+, –, *, and %) Bitwise (&, |, ^, ~, << >> >>> Zero-fill right shift) Comparison (<<, >>, ==, ===, !=, >>=, and <<) Assignment (=, +=, and so on) Logical (&&, ||, and !) Conditional operator (?:)  String concatenation operator (+)
Technology - JavaScript JavaScript Statements: if  (expression)  statement or block else   statement or block switch  (expression) {   case condition 1: statement(s)   break;   default: statement(s) } while  (expression)   statement or block of statements to execute do  {statement(s);} while (expression); for  (initialization; test condition; iteration statement)   loop statement or block with  (object) { statement(s); } Labels can be used with  break  and  continue .
Technology - JavaScript JavaScript functions Function: function functionname(parameter-list)  { statements } function addThree(arg1, arg2, arg3) {  return  (arg1+arg2+arg3); } Function as object:  var sayHello = new Function(&quot;alert('Hello there');&quot;); Functions can be recursive (function within a function) JavaScript Global and local variables var x = 5; //global variable function z() { var x = 3; //local variable }
Technology - JavaScript JavaScript Objects: user-defined, built-in, browser, and document User-defined: custom objects Browser: objects that most browsers support Built-in: Built-in objects are provided by the JavaScript language itself (Array, Boolean, Date, Math, Number and String) Document: objects are part of the Document Object Model (DOM), as defined by the W3C Type Example Implementation Provided By Governing Standard User-defined Programmer-defined Customer or Circle Programmer None Built-in Array, Math The browser via its JavaScript engine ECMA-262 Browser Window, Navigator The browser None (though some portions adhere to an ad hoc standard) Document Image, HTMLInputElement The browser via its DOM engine W3C DOM
Technology - JavaScript JavaScript objects: var myString = new String(&quot;Hello world&quot;); alert(myString.length); x=myString.upperCase(); alert(x); myString is a built-in  String  object.  Length  = the property of the myString object.  Properties that are functions are called methods (such as upperCase(); ). JavaScript Regular expressions are the tool JavaScript provides for matching and manipulating string data based on patterns. var pattern = new RegExp(&quot;http&quot;); pattern.test(&quot;HTTP://WWW.W3C.ORG/&quot;); Test() method returns a Boolean indicating whether the string given as its argument matches the pattern
Technologies - DOM DOM (Document Object Model) Basic Object model for all modern browsers HTML Document model – two basic examples
Technologies - DOM DOM – Object naming, properties, methods and events Naming and references through attribute “id” or “name” <div id=“1”> - <p id=“h”> - <form name=“test”> Object: Properties, methods and events <input  type =“ button ”>  ->  type  is a property,  button  is the value property of  type . Depending on the object, none or multiple methods are available such as submit(), onfocus(), etc. Events -> Events are actions that take place in a document, usually as the result of user activity. <input type=“button”  onclick =“j();”>  - onclick is an event
Technologies - DOM Traversing DOM Reaching Elements in a Document document.getElementById(' id  ’) : Retrieves the element with the given  id  as an object document.getElementsByTagName(' tagname  ') : Retrieves all elements with the tag name  tagname  and stores them in an array-like list Reading Element Attributes, Node Values, and Other Node Data node.getAttribute(' attribute ') : Retrieves the value of the attribute with the name attribute node.setAttribute(' attribute ', 'value') : Sets the value of the attribute with the name attribute to value node.nodeType : Reads the type of the node (1 = element, 3 = text node)
Technologies - DOM node.nodeName : Reads the name of the node (either element name or #textNode) node.nodeValue : Reads or sets the value of the node (the text content in the case of text nodes) Navigating Between Nodes node.previousSibling : Retrieves the previous sibling node and stores it as an object. node.nextSibling : Retrieves the next sibling node and stores it as an object. node.childNodes : Retrieves all child nodes of the object and stores them in an list.  There are shortcuts for the first and last child node, named  node.firstChild  and  node.lastChild . node.parentNode : Retrieves the node containing node.
Technologies - DOM Creating New Nodes document.createElement(element) : Creates a new element node with the name element.  document.createTextNode(string) : Creates a new text node with the node value of string. newNode =node.cloneNode(bool) : Creates newNode as a copy (clone) of node. If bool is true, the clone includes clones of all the child nodes of the original. node.appendChild(newNode) : Adds newNode as a new (last) child node to node. node.insertBefore(newNode,oldNode) : Inserts newNode as a new child node of node before oldNode. node.removeChild(oldNode) : Removes the child oldNode from node.
Technologies - DOM node.replaceChild(newNode, oldNode) : Replaces the child node oldNode of node with newNode. element.innerHTML : Reads or writes the HTML content of the given element as a string— including all child nodes with their attributes and text content
Technologies – JavaScript Security JavaScript comes with some protections and security: Some examples: No direct access to write or delete files or directories No networking primitives of any type Only certain History object methods exposed: back(), forward(), and go(). FileUpload object property value cannot be set.  No form submit() to a mailto: or news: URIs. No browser window closure unless the script opened/created the window itself. No creation of window that is smaller than 100 pixels on a side (other similar actions are forbidden). Event object properties cannot be set.
Technology – JavaScript Security SOP (Same Of Origin Policy) Script can read only the properties of windows and documents that have the same origin as the script itself . The same-origin policy does not actually apply to all properties of all objects in a window from a different origin. Window objects origin-policy exceptions: Location object postMessage()  frames attribute XXX4 method  Document.domain can also be used to relax SOP restrictions aa.domain.com and bb.domain.com can communicate if document.domain = domain.com
Technology – JavaScript Security Some examples of SOP in action URLs Cross – Scripting allowed? Comments http://www.example.com:8080/script1.js NO Port number doesn’t match. http://www.example.com/script2.js http://www.example.com/script1.js NO Protocol type doesn’t match. https://www.example.com/script2.js http://www.example.com/script1.js NO Browser will not perform domain name resolution. http://192.168.0.10/script2.js http://sub.example.com/script1.js NO Subdomains treated as separate domains. http://www.example.com/script2.js http://www.example.com/hello/script1.js YES Domain name is the same. http://www.example.com/bye/script.2.js http://www.example2.com/script1.js NO Different domain names. http://www.example1.com/script2.js
Technologies - Ajax Ajax (Asynchronous Javascript And XML) Ajax = multiple technologies working together  Components: HTML/XHTML Necessary to display the information JavaScript Necessary to initiate the client-server communication and manipulate the DOM to update the web page Document Object Model (DOM) Necessary to change portions of an XHTML page without reloading it. Server-side processing There is no Ajax without a stable, responsive server waiting to send content to the engine
Technologies - Ajax Ajax Components Cascading Style Sheet (CSS) In an Ajax application, the styling of a user interface may be modified interactively through CSS Extensible Markup Language (XML) Data exchange format Extensible Stylesheet Language Transformations (XSLT) Transforms XML to XHTML XMLHttpRequest object XMLHttpRequest object allows retrieving data from the web server as a background activity
Technologies - Ajax Ajax Components – Simple diagram
Technologies - Ajax Traditional web model vs Ajax
Technologies - JSON JSON (JavaScript Object Notation) Simple data transfer format that can be used to serialise arbitrary data Data processed directly by JavaScript interpreters Commonly employed in Ajax applications – (alternative to XML) JSON Message Example - Message is treated as JavaScript array JavaScript constructs the array and then processes its contents JSON – Security implications Same Of Origin (SOP) applies for JavaScript  code  from different domains but not for JavaScript  data  (JSON) from different domains [ [ ‘Jeff’, ‘1741024918’, ‘ginger@microsoft.com’ ], [ ‘C Gillingham’, ‘3885193114’, ‘c2004@symantec.com’ ], [ ‘Mike Kemp’, ‘8041148671’, ‘fkwitt@layerone.com’ ], [ ‘Wade A’, ‘5078782513’, ‘kingofbeef@ngssoftware.com’ ] ]
Practical tips to JavaScript Reversing
Basics JavaScript Analysis/Debugging Tools WebDeveloper Firebug – Debugger, Console, Playing with DOM Venkman – Debugger Basic HTML/DOM/JavaScript analysis Looking at the source code Looking at the DOM Looking at the generated source code Understanding DOM, JavaScript functions and events Traversing DOM – Pay attention to: document.getElementById(“id”) document.getElementsByTagName(“name”)
Reversing – Breakpoint with Firebug
Reversing – Breakpoints and Stack
DOM Analysis
Venkman Debugger
Finding XSS in DOM DOM XSS or Type 0 XSS Find injection point How do we know it’s a DOM XSS? DOM XSS does not appear in “View Source” ;-) Look for the the following methods (from Attacking Rich Internet Application – see references): document.URL document.URLUnencoded document.location (and many of its properties) document.referrer window.location (and many of its properties) Write raw HTML, e.g.:  document.write(…) document.writeln(…) document.body.innerHtml=…
Finding XSS in DOM
Finding XSS in DOM Directly modifying the DOM (including DHTML events), e.g.:  document.forms[0].action=… document.attachEvent(…) document.create…(…) document.execCommand(…) document.body. …  window.attachEvent(…) Replacing the document URL, e.g.:  document.location=…  document.location.hostname=… document.location.replace(…) document.location.assign(…) document.URL=… window.navigate(…)
Finding XSS in DOM Opening/modifying a window, e.g.:  document.open(…) window.open(…) window.location.href=… Directly executing script, e.g.:  eval(…) window.execScript(…) window.setInterval(…) window.setTimeout(…) DOM XSS should not always result in JavaScript execution New DOM XSS attacks might include: Modify/abuse sensitive objects Modify DOM/HTML Objects  Leak and insert cookies (document.cookie) Perform directory traversal with XHR
JavaScript and Ajax Reversing JavaScript – Ajax Intercept XHR (XMLHttpRequest) requests/responses with Firebug (console and profiler) Pay attention to inline JavaScript events – they might trigger XHR (Fire inline addon). Ajax is just a client-side technology – needs to be considered as standard web application. Look for Ajax bridging – this is used to evade SOP between two endpoints on different domains XML and XPath might be used in conjunction with Ajax Understand how Ajax engine constructs the request and interfaces to XPath -> XML file. Ajax can also interface with a database (SQL). Understand how Ajax engine constructs the request and interfaces with the database.
JavaScript and Ajax
JSON Reversing JavaScript – JSON Find the JSON service – check HTTP GET and POST requests Understand what type of JSON data is passed between client and server side – are callback functions used? Like showc(); below: Injection in JSON can lead to JavaScript execution (as in eval()) Check if the JSON comes as JSON label or not (note if brackets are used to wrap JSON data like  ( {&quot;errorsNum&quot;:2,&quot;error&quot;:[&quot;Wrong email!&quot;,&quot;Wrong hobby!&quot;]} ) showC ( [ [ ‘test’, ‘1741024918’, ‘test@test.com’ ], [ ‘test2’, ‘3885193114’, ‘test2@test.com’ ], ]);
JSON
JSON Attacking JSON – another way to do CSRF Use the same JavaScript JSON parser to handle the data from a different domain Exploit CSRF of the victim application Before JavaScript 2.0, override of the Array function was used to handle JSON data as in the following example: Setter needs to be used for objects or arrays to get JSON data under control. JSON hijacking JavaScript code has to be customised for each browser. <script> function array() { var obj = this; var ind = 0; var getNext = function(x) { obj[ind++] setter = getNext; if (x) alert(‘Data stolen from array:’+x.toString()); } this[ind++] setter = getNext; } <script src=‘http://jsonservice’></script>
JSON Attacking JSON In case of callback function: Then, following code can be used in the malicious site to extract data from the JSON service: showC ( [ [ ‘test’, ‘1741024918’, ‘test@test.com’ ], [ ‘test2’, ‘3885193114’, ‘test2@test.com’ ], ]); <script> function showC(a) { alert(a); } </script> <script src=”URLwhichReturnstheJSONabove”></script>
Unpacking/Deofuscating JavaScript deobfuscation/unpacking techniques Dean Edwards simple JavaScript packer Unpacking Dean Edwards with Malzilla (2 clicks) More complex case: Screen shots: 1) Simple analysis of obfuscated JavaScript Deciphering shellcode Use of document.createelement 2) Case of data to be deciphered that is not a part of the script Use of arguments.calle.tostring Data attached to onload event
Unpacking JavaScript
Case I
Case II
Unpacking/Deofuscating Demo 1) JavaScript de-obfuscation and shell code analysis 2) LuckySploit New exploit kit - set of .HTML files Used for spreading the malware with the method of Drive-by-Download Script using RSA algorithm Script only displayed once – if u browse back, the script won’t appear again
Questions? © 2007 Security-Assessment.com http://www.security-assessment.com [email_address]
Resources DebugBar -  http://www.my-debugbar.com/wiki/Doc/DebugbarInstall Firebug -  http://getfirebug.com/docs.html WebDevHelper -  http://projects.nikhilk.net/WebDevHelper/ JavaScript Debugger -  http://www.mozilla.org/projects/venkman/ JavaScript Debugger Tutorial -  http://devedge-temp.mozilla.org/viewsource/2002/venkman/01/index_en.html JSON -  http://directwebremoting.org/blog/joe/2007/03/06/json_is_not_as_safe_as_people_think_it_is_part_2.html JSON/Twitter Example -  http://www.thespanner.co.uk/2009/01/07/i-know-what-your-friends-did-last-summer/ Safety of JSON -  http://ajaxian.com/archives/the-safety-of-json Forum Discussion – JSON -  http://sla.ckers.org/forum/read.php?2,25788
References LuckySploit -  http://evilfingers.blogspot.com/2009/02/luckysploit-right-hand-of-zeus.html AJAX Security - http://www.cgisecurity.com/ajax/ Ajax Security Basics -  http://www.securityfocus.com/infocus/1868/2 JavaScript 2.0: The Complete Reference, Second Edition by Thomas Powell and Fritz Schneider - ISBN:0072253576 JavaScript: The Definitive Guide, 4th Edition By David Flanagan - ISBN : 0-596-00048-0 Pro JavaScript Techniques by John Resig ISBN: 1-59059-727-3 Practical JavaScript™, DOM Scripting, and Ajax Projects by Frank W. Zammett – ISBN:  1-59059-816-4 JavaScript® Bible, Sixth Edition by Danny Goodman – ISBN: 978-0-470-06916-5
Attacking Rich Internet Applications – Stefano Di Paola, Kuza55 -  http://www.ruxcon.org.au/files/2008/Attacking_Rich_Internet_Applications.pdf LuckySploit -  http://novirusthanks.org/blog/2009/03/luckysploit-new-exploit-kit/

More Related Content

What's hot (20)

PPT
JavaScript Basics
Mats Bryntse
 
PDF
JavaScript - Chapter 4 - Types and Statements
WebStackAcademy
 
PDF
The Xtext Grammar Language
Dr. Jan Köhnlein
 
PPT
Ajax
Manav Prasad
 
PDF
javascript objects
Vijay Kalyan
 
PPT
Prototype Utility Methods(1)
mussawir20
 
PPT
Objective c
ricky_chatur2005
 
PDF
Automatically generating-json-from-java-objects-java-objects268
Ramamohan Chokkam
 
PPTX
Javascript Basics
msemenistyi
 
PPTX
Ios development
elnaqah
 
PDF
Google Dart
Eberhard Wolff
 
PPT
Javascript Templating
bcruhl
 
KEY
Parte II Objective C
Paolo Quadrani
 
PPTX
From C++ to Objective-C
corehard_by
 
PDF
3.1 javascript objects_DOM
Jalpesh Vasa
 
PDF
Coding Ajax
Ted Husted
 
PPT
Javascript
Manav Prasad
 
PPT
A Deeper look into Javascript Basics
Mindfire Solutions
 
PDF
JavaScript introduction 1 ( Variables And Values )
Victor Verhaagen
 
KEY
Objective-C Crash Course for Web Developers
Joris Verbogt
 
JavaScript Basics
Mats Bryntse
 
JavaScript - Chapter 4 - Types and Statements
WebStackAcademy
 
The Xtext Grammar Language
Dr. Jan Köhnlein
 
javascript objects
Vijay Kalyan
 
Prototype Utility Methods(1)
mussawir20
 
Objective c
ricky_chatur2005
 
Automatically generating-json-from-java-objects-java-objects268
Ramamohan Chokkam
 
Javascript Basics
msemenistyi
 
Ios development
elnaqah
 
Google Dart
Eberhard Wolff
 
Javascript Templating
bcruhl
 
Parte II Objective C
Paolo Quadrani
 
From C++ to Objective-C
corehard_by
 
3.1 javascript objects_DOM
Jalpesh Vasa
 
Coding Ajax
Ted Husted
 
Javascript
Manav Prasad
 
A Deeper look into Javascript Basics
Mindfire Solutions
 
JavaScript introduction 1 ( Variables And Values )
Victor Verhaagen
 
Objective-C Crash Course for Web Developers
Joris Verbogt
 

Viewers also liked (19)

PDF
Instalar magento
Complethost Soluciones Internet
 
PDF
manual de usuario videograbador 4 canales sinrobos.com
Simon Chaler
 
PDF
Participant Portal - Paperless Grant Management | presentation 1/4
ISERD Israel
 
PDF
Presentación Inner Sense
Victor Angel
 
PDF
De la Agenda 21E al camino escolar - María Sol Mena Rubio
Medi Ambient. Generalitat de Catalunya
 
PPTX
Physiotherapy methods
Sarthy Velayutham
 
PDF
Sunflex Schiebe-Dreh-Systeme SF25 für Terrassenverglasung - jetzt bei Fenster...
Florian Schmidinger
 
PDF
Vortrag "Spend Quality Time with your Data" zum WELT POKAL 2011
Vizlib Ltd.
 
PDF
CIWM-September-2016-Special-Focus
Conversocial
 
PPSX
Mascotas mundialistas
angierir
 
PPTX
Negocios electrónicos
OBS
 
PPTX
C4 parte 1 perugia 2010 11 04
Ivan Stefani
 
PPTX
Hugo0210
hugo0210
 
PDF
Ley 135 11 sobre vih-sida en rd
Miguel Simón
 
PDF
Premio Fonseca formulación magistral 1988
Enrique Alía Fernández-Montes
 
DOCX
Dossierde planificación
Félix Sánchez Paredes
 
PPTX
Socialismo, Socialismo nacional y Facismo
Aaron Flores
 
PDF
Diaz tolerancia a eh en cebada inia 2005
Danioteca Surco
 
PDF
Gazda final
John Hutchison
 
manual de usuario videograbador 4 canales sinrobos.com
Simon Chaler
 
Participant Portal - Paperless Grant Management | presentation 1/4
ISERD Israel
 
Presentación Inner Sense
Victor Angel
 
De la Agenda 21E al camino escolar - María Sol Mena Rubio
Medi Ambient. Generalitat de Catalunya
 
Physiotherapy methods
Sarthy Velayutham
 
Sunflex Schiebe-Dreh-Systeme SF25 für Terrassenverglasung - jetzt bei Fenster...
Florian Schmidinger
 
Vortrag "Spend Quality Time with your Data" zum WELT POKAL 2011
Vizlib Ltd.
 
CIWM-September-2016-Special-Focus
Conversocial
 
Mascotas mundialistas
angierir
 
Negocios electrónicos
OBS
 
C4 parte 1 perugia 2010 11 04
Ivan Stefani
 
Hugo0210
hugo0210
 
Ley 135 11 sobre vih-sida en rd
Miguel Simón
 
Premio Fonseca formulación magistral 1988
Enrique Alía Fernández-Montes
 
Dossierde planificación
Félix Sánchez Paredes
 
Socialismo, Socialismo nacional y Facismo
Aaron Flores
 
Diaz tolerancia a eh en cebada inia 2005
Danioteca Surco
 
Gazda final
John Hutchison
 
Ad

Similar to Reversing JavaScript (20)

PDF
HSC INFORMATION TECHNOLOGY CHAPTER 3 ADVANCED JAVASCRIPT
AAFREEN SHAIKH
 
PPT
JavaScript & Dom Manipulation
Mohammed Arif
 
PPS
Advisor Jumpstart: JavaScript
dominion
 
PDF
22519 - Client-Side Scripting Language (CSS) chapter 1 notes .pdf
sharvaridhokte
 
PPT
Javascript: Ajax & DOM Manipulation v1.2
borkweb
 
PPT
Introduction to Javascript
Amit Tyagi
 
PPT
Java script
vishal choudhary
 
PPTX
Awesomeness of JavaScript…almost
Quinton Sheppard
 
PPTX
Javascript note for engineering notes.pptx
engineeradda55
 
PPT
jQuery with javascript training by Technnovation Labs
Prasad Shende
 
PDF
Basics of JavaScript
Bala Narayanan
 
PPT
JavaScript - An Introduction
Manvendra Singh
 
PPT
Java Script Programming on Web Application
SripathiRavi1
 
PPTX
Cordova training : Day 4 - Advanced Javascript
Binu Paul
 
PPTX
All of Javascript
Togakangaroo
 
PPT
17javascript.ppt
bcanawakadalcollege
 
PPT
17javascript.ppt
PraveenRai90
 
PPT
lecture 6 javascript event and event handling.ppt
ULADATZ
 
PPT
17javascript.ppt17javascript.ppt17javascript.ppt
hodit46
 
HSC INFORMATION TECHNOLOGY CHAPTER 3 ADVANCED JAVASCRIPT
AAFREEN SHAIKH
 
JavaScript & Dom Manipulation
Mohammed Arif
 
Advisor Jumpstart: JavaScript
dominion
 
22519 - Client-Side Scripting Language (CSS) chapter 1 notes .pdf
sharvaridhokte
 
Javascript: Ajax & DOM Manipulation v1.2
borkweb
 
Introduction to Javascript
Amit Tyagi
 
Java script
vishal choudhary
 
Awesomeness of JavaScript…almost
Quinton Sheppard
 
Javascript note for engineering notes.pptx
engineeradda55
 
jQuery with javascript training by Technnovation Labs
Prasad Shende
 
Basics of JavaScript
Bala Narayanan
 
JavaScript - An Introduction
Manvendra Singh
 
Java Script Programming on Web Application
SripathiRavi1
 
Cordova training : Day 4 - Advanced Javascript
Binu Paul
 
All of Javascript
Togakangaroo
 
17javascript.ppt
bcanawakadalcollege
 
17javascript.ppt
PraveenRai90
 
lecture 6 javascript event and event handling.ppt
ULADATZ
 
17javascript.ppt17javascript.ppt17javascript.ppt
hodit46
 
Ad

More from Roberto Suggi Liverani (13)

PDF
I got 99 trends and a # is all of them
Roberto Suggi Liverani
 
PDF
Augmented reality in your web proxy
Roberto Suggi Liverani
 
PPTX
Cross Context Scripting attacks & exploitation
Roberto Suggi Liverani
 
PDF
Window Shopping Browser - Bug Hunting in 2012
Roberto Suggi Liverani
 
PDF
None More Black - the Dark Side of SEO
Roberto Suggi Liverani
 
PDF
Bridging the gap - Security and Software Testing
Roberto Suggi Liverani
 
PDF
Defending Against Application DoS attacks
Roberto Suggi Liverani
 
PDF
Exploiting Firefox Extensions
Roberto Suggi Liverani
 
PPT
Black Energy18 - Russian botnet package analysis
Roberto Suggi Liverani
 
PPT
XPath Injection
Roberto Suggi Liverani
 
PPT
Web Spam Techniques
Roberto Suggi Liverani
 
PPT
Ajax Security
Roberto Suggi Liverani
 
PPT
Browser Security
Roberto Suggi Liverani
 
I got 99 trends and a # is all of them
Roberto Suggi Liverani
 
Augmented reality in your web proxy
Roberto Suggi Liverani
 
Cross Context Scripting attacks & exploitation
Roberto Suggi Liverani
 
Window Shopping Browser - Bug Hunting in 2012
Roberto Suggi Liverani
 
None More Black - the Dark Side of SEO
Roberto Suggi Liverani
 
Bridging the gap - Security and Software Testing
Roberto Suggi Liverani
 
Defending Against Application DoS attacks
Roberto Suggi Liverani
 
Exploiting Firefox Extensions
Roberto Suggi Liverani
 
Black Energy18 - Russian botnet package analysis
Roberto Suggi Liverani
 
XPath Injection
Roberto Suggi Liverani
 
Web Spam Techniques
Roberto Suggi Liverani
 
Ajax Security
Roberto Suggi Liverani
 
Browser Security
Roberto Suggi Liverani
 

Reversing JavaScript

  • 1. © 2009 Security-Assessment.com Reversing JavaScript Presented By Roberto Suggi Liverani
  • 2. Who am I? Roberto Suggi Liverani Security Consultant, CISSP - Security-Assessment.com 4+ years in information security, focusing on web application and network security OWASP New Zealand founder/leader
  • 3. Agenda Introduction Technologies: JavaScript, DOM, Ajax, JSON Security: JavaScript Security Model Practical tips JavaScript Analysis\Debugging Tools Finding vulnerabilities in JavaScript – DOM XSS Reversing JavaScript – Ajax Reversing JavaScript – JSON Obfuscated JavaScript – Deobfuscation techniques Dean Edwards Packer More complex cases
  • 4. Technology - JavaScript JavaScript JavaScript provides five primitive data types: number, string, Boolean, undefined, and null. Number: var x = 3.14; String: var string1 = &quot;This is a string&quot;; Boolean: var a = true Undefined and null do not store data. var x; var y = null; Reference types includes the composite types (objects and arrays) and functions. Arrays and functions are special kinds of objects. Object: navigator.appVersion (navigator is an object) Array: var x = myArray[5]; Each primitive type is associated with an object that provides methods useful for manipulating that kind of data.
  • 5. Technology - JavaScript JavaScript Operators: Mathematical (+, –, *, and %) Bitwise (&, |, ^, ~, << >> >>> Zero-fill right shift) Comparison (<<, >>, ==, ===, !=, >>=, and <<) Assignment (=, +=, and so on) Logical (&&, ||, and !) Conditional operator (?:) String concatenation operator (+)
  • 6. Technology - JavaScript JavaScript Statements: if (expression) statement or block else statement or block switch (expression) { case condition 1: statement(s) break; default: statement(s) } while (expression) statement or block of statements to execute do {statement(s);} while (expression); for (initialization; test condition; iteration statement) loop statement or block with (object) { statement(s); } Labels can be used with break and continue .
  • 7. Technology - JavaScript JavaScript functions Function: function functionname(parameter-list) { statements } function addThree(arg1, arg2, arg3) { return (arg1+arg2+arg3); } Function as object: var sayHello = new Function(&quot;alert('Hello there');&quot;); Functions can be recursive (function within a function) JavaScript Global and local variables var x = 5; //global variable function z() { var x = 3; //local variable }
  • 8. Technology - JavaScript JavaScript Objects: user-defined, built-in, browser, and document User-defined: custom objects Browser: objects that most browsers support Built-in: Built-in objects are provided by the JavaScript language itself (Array, Boolean, Date, Math, Number and String) Document: objects are part of the Document Object Model (DOM), as defined by the W3C Type Example Implementation Provided By Governing Standard User-defined Programmer-defined Customer or Circle Programmer None Built-in Array, Math The browser via its JavaScript engine ECMA-262 Browser Window, Navigator The browser None (though some portions adhere to an ad hoc standard) Document Image, HTMLInputElement The browser via its DOM engine W3C DOM
  • 9. Technology - JavaScript JavaScript objects: var myString = new String(&quot;Hello world&quot;); alert(myString.length); x=myString.upperCase(); alert(x); myString is a built-in String object. Length = the property of the myString object. Properties that are functions are called methods (such as upperCase(); ). JavaScript Regular expressions are the tool JavaScript provides for matching and manipulating string data based on patterns. var pattern = new RegExp(&quot;http&quot;); pattern.test(&quot;HTTP://WWW.W3C.ORG/&quot;); Test() method returns a Boolean indicating whether the string given as its argument matches the pattern
  • 10. Technologies - DOM DOM (Document Object Model) Basic Object model for all modern browsers HTML Document model – two basic examples
  • 11. Technologies - DOM DOM – Object naming, properties, methods and events Naming and references through attribute “id” or “name” <div id=“1”> - <p id=“h”> - <form name=“test”> Object: Properties, methods and events <input type =“ button ”> -> type is a property, button is the value property of type . Depending on the object, none or multiple methods are available such as submit(), onfocus(), etc. Events -> Events are actions that take place in a document, usually as the result of user activity. <input type=“button” onclick =“j();”> - onclick is an event
  • 12. Technologies - DOM Traversing DOM Reaching Elements in a Document document.getElementById(' id ’) : Retrieves the element with the given id as an object document.getElementsByTagName(' tagname ') : Retrieves all elements with the tag name tagname and stores them in an array-like list Reading Element Attributes, Node Values, and Other Node Data node.getAttribute(' attribute ') : Retrieves the value of the attribute with the name attribute node.setAttribute(' attribute ', 'value') : Sets the value of the attribute with the name attribute to value node.nodeType : Reads the type of the node (1 = element, 3 = text node)
  • 13. Technologies - DOM node.nodeName : Reads the name of the node (either element name or #textNode) node.nodeValue : Reads or sets the value of the node (the text content in the case of text nodes) Navigating Between Nodes node.previousSibling : Retrieves the previous sibling node and stores it as an object. node.nextSibling : Retrieves the next sibling node and stores it as an object. node.childNodes : Retrieves all child nodes of the object and stores them in an list. There are shortcuts for the first and last child node, named node.firstChild and node.lastChild . node.parentNode : Retrieves the node containing node.
  • 14. Technologies - DOM Creating New Nodes document.createElement(element) : Creates a new element node with the name element. document.createTextNode(string) : Creates a new text node with the node value of string. newNode =node.cloneNode(bool) : Creates newNode as a copy (clone) of node. If bool is true, the clone includes clones of all the child nodes of the original. node.appendChild(newNode) : Adds newNode as a new (last) child node to node. node.insertBefore(newNode,oldNode) : Inserts newNode as a new child node of node before oldNode. node.removeChild(oldNode) : Removes the child oldNode from node.
  • 15. Technologies - DOM node.replaceChild(newNode, oldNode) : Replaces the child node oldNode of node with newNode. element.innerHTML : Reads or writes the HTML content of the given element as a string— including all child nodes with their attributes and text content
  • 16. Technologies – JavaScript Security JavaScript comes with some protections and security: Some examples: No direct access to write or delete files or directories No networking primitives of any type Only certain History object methods exposed: back(), forward(), and go(). FileUpload object property value cannot be set. No form submit() to a mailto: or news: URIs. No browser window closure unless the script opened/created the window itself. No creation of window that is smaller than 100 pixels on a side (other similar actions are forbidden). Event object properties cannot be set.
  • 17. Technology – JavaScript Security SOP (Same Of Origin Policy) Script can read only the properties of windows and documents that have the same origin as the script itself . The same-origin policy does not actually apply to all properties of all objects in a window from a different origin. Window objects origin-policy exceptions: Location object postMessage() frames attribute XXX4 method Document.domain can also be used to relax SOP restrictions aa.domain.com and bb.domain.com can communicate if document.domain = domain.com
  • 18. Technology – JavaScript Security Some examples of SOP in action URLs Cross – Scripting allowed? Comments http://www.example.com:8080/script1.js NO Port number doesn’t match. http://www.example.com/script2.js http://www.example.com/script1.js NO Protocol type doesn’t match. https://www.example.com/script2.js http://www.example.com/script1.js NO Browser will not perform domain name resolution. http://192.168.0.10/script2.js http://sub.example.com/script1.js NO Subdomains treated as separate domains. http://www.example.com/script2.js http://www.example.com/hello/script1.js YES Domain name is the same. http://www.example.com/bye/script.2.js http://www.example2.com/script1.js NO Different domain names. http://www.example1.com/script2.js
  • 19. Technologies - Ajax Ajax (Asynchronous Javascript And XML) Ajax = multiple technologies working together Components: HTML/XHTML Necessary to display the information JavaScript Necessary to initiate the client-server communication and manipulate the DOM to update the web page Document Object Model (DOM) Necessary to change portions of an XHTML page without reloading it. Server-side processing There is no Ajax without a stable, responsive server waiting to send content to the engine
  • 20. Technologies - Ajax Ajax Components Cascading Style Sheet (CSS) In an Ajax application, the styling of a user interface may be modified interactively through CSS Extensible Markup Language (XML) Data exchange format Extensible Stylesheet Language Transformations (XSLT) Transforms XML to XHTML XMLHttpRequest object XMLHttpRequest object allows retrieving data from the web server as a background activity
  • 21. Technologies - Ajax Ajax Components – Simple diagram
  • 22. Technologies - Ajax Traditional web model vs Ajax
  • 23. Technologies - JSON JSON (JavaScript Object Notation) Simple data transfer format that can be used to serialise arbitrary data Data processed directly by JavaScript interpreters Commonly employed in Ajax applications – (alternative to XML) JSON Message Example - Message is treated as JavaScript array JavaScript constructs the array and then processes its contents JSON – Security implications Same Of Origin (SOP) applies for JavaScript code from different domains but not for JavaScript data (JSON) from different domains [ [ ‘Jeff’, ‘1741024918’, ‘[email protected]’ ], [ ‘C Gillingham’, ‘3885193114’, ‘[email protected]’ ], [ ‘Mike Kemp’, ‘8041148671’, ‘[email protected]’ ], [ ‘Wade A’, ‘5078782513’, ‘[email protected]’ ] ]
  • 24. Practical tips to JavaScript Reversing
  • 25. Basics JavaScript Analysis/Debugging Tools WebDeveloper Firebug – Debugger, Console, Playing with DOM Venkman – Debugger Basic HTML/DOM/JavaScript analysis Looking at the source code Looking at the DOM Looking at the generated source code Understanding DOM, JavaScript functions and events Traversing DOM – Pay attention to: document.getElementById(“id”) document.getElementsByTagName(“name”)
  • 26. Reversing – Breakpoint with Firebug
  • 30. Finding XSS in DOM DOM XSS or Type 0 XSS Find injection point How do we know it’s a DOM XSS? DOM XSS does not appear in “View Source” ;-) Look for the the following methods (from Attacking Rich Internet Application – see references): document.URL document.URLUnencoded document.location (and many of its properties) document.referrer window.location (and many of its properties) Write raw HTML, e.g.: document.write(…) document.writeln(…) document.body.innerHtml=…
  • 32. Finding XSS in DOM Directly modifying the DOM (including DHTML events), e.g.: document.forms[0].action=… document.attachEvent(…) document.create…(…) document.execCommand(…) document.body. …  window.attachEvent(…) Replacing the document URL, e.g.: document.location=…  document.location.hostname=… document.location.replace(…) document.location.assign(…) document.URL=… window.navigate(…)
  • 33. Finding XSS in DOM Opening/modifying a window, e.g.: document.open(…) window.open(…) window.location.href=… Directly executing script, e.g.: eval(…) window.execScript(…) window.setInterval(…) window.setTimeout(…) DOM XSS should not always result in JavaScript execution New DOM XSS attacks might include: Modify/abuse sensitive objects Modify DOM/HTML Objects Leak and insert cookies (document.cookie) Perform directory traversal with XHR
  • 34. JavaScript and Ajax Reversing JavaScript – Ajax Intercept XHR (XMLHttpRequest) requests/responses with Firebug (console and profiler) Pay attention to inline JavaScript events – they might trigger XHR (Fire inline addon). Ajax is just a client-side technology – needs to be considered as standard web application. Look for Ajax bridging – this is used to evade SOP between two endpoints on different domains XML and XPath might be used in conjunction with Ajax Understand how Ajax engine constructs the request and interfaces to XPath -> XML file. Ajax can also interface with a database (SQL). Understand how Ajax engine constructs the request and interfaces with the database.
  • 36. JSON Reversing JavaScript – JSON Find the JSON service – check HTTP GET and POST requests Understand what type of JSON data is passed between client and server side – are callback functions used? Like showc(); below: Injection in JSON can lead to JavaScript execution (as in eval()) Check if the JSON comes as JSON label or not (note if brackets are used to wrap JSON data like ( {&quot;errorsNum&quot;:2,&quot;error&quot;:[&quot;Wrong email!&quot;,&quot;Wrong hobby!&quot;]} ) showC ( [ [ ‘test’, ‘1741024918’, ‘[email protected]’ ], [ ‘test2’, ‘3885193114’, ‘[email protected]’ ], ]);
  • 37. JSON
  • 38. JSON Attacking JSON – another way to do CSRF Use the same JavaScript JSON parser to handle the data from a different domain Exploit CSRF of the victim application Before JavaScript 2.0, override of the Array function was used to handle JSON data as in the following example: Setter needs to be used for objects or arrays to get JSON data under control. JSON hijacking JavaScript code has to be customised for each browser. <script> function array() { var obj = this; var ind = 0; var getNext = function(x) { obj[ind++] setter = getNext; if (x) alert(‘Data stolen from array:’+x.toString()); } this[ind++] setter = getNext; } <script src=‘http://jsonservice’></script>
  • 39. JSON Attacking JSON In case of callback function: Then, following code can be used in the malicious site to extract data from the JSON service: showC ( [ [ ‘test’, ‘1741024918’, ‘[email protected]’ ], [ ‘test2’, ‘3885193114’, ‘[email protected]’ ], ]); <script> function showC(a) { alert(a); } </script> <script src=”URLwhichReturnstheJSONabove”></script>
  • 40. Unpacking/Deofuscating JavaScript deobfuscation/unpacking techniques Dean Edwards simple JavaScript packer Unpacking Dean Edwards with Malzilla (2 clicks) More complex case: Screen shots: 1) Simple analysis of obfuscated JavaScript Deciphering shellcode Use of document.createelement 2) Case of data to be deciphered that is not a part of the script Use of arguments.calle.tostring Data attached to onload event
  • 44. Unpacking/Deofuscating Demo 1) JavaScript de-obfuscation and shell code analysis 2) LuckySploit New exploit kit - set of .HTML files Used for spreading the malware with the method of Drive-by-Download Script using RSA algorithm Script only displayed once – if u browse back, the script won’t appear again
  • 45. Questions? © 2007 Security-Assessment.com http://www.security-assessment.com [email_address]
  • 46. Resources DebugBar - http://www.my-debugbar.com/wiki/Doc/DebugbarInstall Firebug - http://getfirebug.com/docs.html WebDevHelper - http://projects.nikhilk.net/WebDevHelper/ JavaScript Debugger - http://www.mozilla.org/projects/venkman/ JavaScript Debugger Tutorial - http://devedge-temp.mozilla.org/viewsource/2002/venkman/01/index_en.html JSON - http://directwebremoting.org/blog/joe/2007/03/06/json_is_not_as_safe_as_people_think_it_is_part_2.html JSON/Twitter Example - http://www.thespanner.co.uk/2009/01/07/i-know-what-your-friends-did-last-summer/ Safety of JSON - http://ajaxian.com/archives/the-safety-of-json Forum Discussion – JSON - http://sla.ckers.org/forum/read.php?2,25788
  • 47. References LuckySploit - http://evilfingers.blogspot.com/2009/02/luckysploit-right-hand-of-zeus.html AJAX Security - http://www.cgisecurity.com/ajax/ Ajax Security Basics - http://www.securityfocus.com/infocus/1868/2 JavaScript 2.0: The Complete Reference, Second Edition by Thomas Powell and Fritz Schneider - ISBN:0072253576 JavaScript: The Definitive Guide, 4th Edition By David Flanagan - ISBN : 0-596-00048-0 Pro JavaScript Techniques by John Resig ISBN: 1-59059-727-3 Practical JavaScript™, DOM Scripting, and Ajax Projects by Frank W. Zammett – ISBN: 1-59059-816-4 JavaScript® Bible, Sixth Edition by Danny Goodman – ISBN: 978-0-470-06916-5
  • 48. Attacking Rich Internet Applications – Stefano Di Paola, Kuza55 - http://www.ruxcon.org.au/files/2008/Attacking_Rich_Internet_Applications.pdf LuckySploit - http://novirusthanks.org/blog/2009/03/luckysploit-new-exploit-kit/