Client-Side Scripting CSE 591 – Security and Vulnerability Analysis Spring 2015 Adam Doupé Arizona State University http://adamdoupe.com Content of some slides provided by Giovanni Vigna of UCSB, with approval Overview • So far, we've looked at the technologies of the web – URIs – HTTP – HTML • Then, we looked at how to dynamically generate HTML pages – Server-side code languages – SQL databases Adam Doupé, Security and Vulnerability Analysis HTML • Original HTML had – images – tables – font sizes –… • Content was static Adam Doupé, Security and Vulnerability Analysis https://web.archive.org/web/19961017235908/http://www2.yahoo.com/ Adam Doupé, Security and Vulnerability Analysis Adam Doupé, Security and Vulnerability Analysis https://web.archive.org/web/19961022174810/http://www.altavista.com/ Adam Doupé, Security and Vulnerability Analysis https://web.archive.org/web/19981202230410/http://www.google.com/ Adam Doupé, Security and Vulnerability Analysis HTML Design • HTML designed to describe a text document with hyperlinks to other documents • How to do fancy animations or pretty web pages? Adam Doupé, Security and Vulnerability Analysis Java Applets • A way of including a Java application as part of a web page • Included by Sun in the first version of Java – May 23rd 1995, the same day that MySQL was released • Applet is Java bytecode that is downloaded and run on the client's machine • Because Java is cross-platform, you can now distribute a Java program over the Internet using a web page • The applet runs in a sandbox – Because running arbitrary code from the Internet is a bad idea Adam Doupé, Security and Vulnerability Analysis Java Applets – Java Code • Subclass java.applet.Applet • Applet is a subclass of java.awt.Panel – This means that you can use AWT to draw to the applet • Unlike a Java application, a Java applet has no main method – – – – – init start paint stop destroy Adam Doupé, Security and Vulnerability Analysis Java Applets – HTML • applet element was historically used to include an applet <applet code='Example' archive='Example.jar' width=300 height=300>Shows in case applet not loaded.</applet> – applet is deprecated (too specific) • object element allows to include any type of third-party media/plugin <object type="application/x-java-applet"> <param name="code" value="Example"> <param name="archive" value="Example.jar"> <param name="width" value=300> <param name="height" value=300> Shows in case applet not loaded. </object> • Browser can instantiate JVM and pass parameters Adam Doupé, Security and Vulnerability Analysis HelloWorld.java import java.applet.Applet; import java.awt.*; public class HelloWorld extends Applet { // Print a message on the screen (x=20, y=10). public void paint(Graphics g) { g.drawString("Hello CSE 591!", 20, 10); } } Adam Doupé, Security and Vulnerability Analysis hellojava.html <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Java Applet Example</title> </head> <body> <object type="application/x-java-applet"> <param name="code" value="HelloWorld.class"> <param name="width" value=300> <param name="height" value=300> Shows in case applet not loaded. </object> </body> </html> Adam Doupé, Security and Vulnerability Analysis Java Applets – Example Adam Doupé, Security and Vulnerability Analysis Java Applets – Example Adam Doupé, Security and Vulnerability Analysis Java Applets – Example Adam Doupé, Security and Vulnerability Analysis Java Applets • First approach at adding client-side processing to web pages • Applets are typically ugly – AWT means that applets do not use native lookand-feel • Applets are a security nightmare – Flaw in the sandbox or JVM means attacker can execute arbitrary code on your machine • Severe restrictions in place now – Applet must be signed and the user must trust the applet Adam Doupé, Security and Vulnerability Analysis ActiveX Controls • Binary, OS-specific, programs that are downloaded and executed in the context of a web page • First proposed by Microsoft in 1996 (possibly as a challenge to Java Applets) • Supported by Windows-based browsers only Adam Doupé, Security and Vulnerability Analysis ActiveX Controls • ActiveX evolved out of COM (Component Object Model) and OLE (Object Linking and Embedding) – Allows ActiveX controls to be implemented in any language • Included in HTML using the object tag <object classid="clsid:7A080CC5-26E2-101B-AEBD04021C009402" id="Testing" height=100 width=100> </object> – classid ID references the GUID of the ActiveX control – id gives it a name to be referenced in JavaScript Adam Doupé, Security and Vulnerability Analysis ActiveX Controls • Originally, the browser would download and run the code automatically • Once executed, ActiveX controls have complete access to the client's environment • Eventually, the security problems with automatically downloading and running binary code were realized • Code is signed using the Authenticode mechanism Adam Doupé, Security and Vulnerability Analysis ActiveX Controls • ActiveX is used to implement many browser plug-ins on Windows – Adobe PDF – Adobe Flash – Silverlight – Quicktime – Java applets Adam Doupé, Security and Vulnerability Analysis Adobe Flash • Fundamentally a vector graphics and animation engine • Originally created "SmartSketch" as a way to create animations for pen computing in 1993 • Pen computing and SmartSketch failed • Rewrote and rebranded as "FutureSplash" to work as a Netscape plugin May 1996 • December 1996 sold FutureSplash to Macromedia, and became Macromedia Flash 1.0 • Adobe acquired Macromedia for $3.4 billion, December 2005 Adam Doupé, Security and Vulnerability Analysis Adobe Flash • Used to create animations, videos, or games • Combines vector graphics, animation, video, and scripting language • Scripting language is ActionScript, which is related to JavaScript • Used in the early web to completely write a web page or web site, rather than use HTML • Adobe claims "1 billion connected desktops across browsers and operating systems" Adam Doupé, Security and Vulnerability Analysis Silverlight • Microsoft Flash competitor and replacement/upgrade to ActiveX • First released in 2007 • Idea was to write application in .NET language and the application would run in your browser on the Silverlight run time • Currently deprecated (and basically dead) Adam Doupé, Security and Vulnerability Analysis JavaScript • • • Client-Side scripting language for interacting and manipulating HTML Created by Brendan Eich at Netscape Navigator 2.0 in September 1995 as "LiveScript" Renamed to "JavaScript" in December 1995 and is (from the Netscape Press Release) – "announced JavaScript, an open, cross-platform object scripting language for the creation and customization of applications on enterprise networks and the Internet" • JavaScript is a (from wikipedia) "prototype-based scripting language with dynamic typing and first-class functions" – Does this sound like Java? • Questions over why the name change – Marketing ploy to capitalize on the "hot" Java language? – Collaboration between Sun and Netscape? • By August 1996, Microsoft added support for JavaScript to Internet Explorer – Microsoft later changed the name to JScript to avoid Sun's Java trademark • • Submitted to Ecma International for standardization on November 1996 ECMA-262, on June 1997, standardized first version of ECMAScript Adam Doupé, Security and Vulnerability Analysis JavaScript • Lingua fraca of the web • Eventually supported by all browsers • Language organically evolved along the way Adam Doupé, Security and Vulnerability Analysis JavaScript • Code can be embedded into HTML pages using the script element and (optionally storing the code in HTML comments) <script> <!-var name = prompt('Please enter your name below.', ''); if (name == null) { document.write('Welcome to my site!'); } else { document.write('Welcome to my site ' + name + '!'); } --> </script> <script type="text/javascript"> <script language="javascript"> Adam Doupé, Security and Vulnerability Analysis Adam Doupé, Security and Vulnerability Analysis Adam Doupé, Security and Vulnerability Analysis Adam Doupé, Security and Vulnerability Analysis JavaScript • You can also include external JavaScript files in your HTML – As opposed to the inline JavaScript that we saw in the previous example • <script src="<absolute or relative URL"></script> • When the browser parses this HTML element, it automatically fetches and executes the JavaScript before continuing to parse the rest of the HTML – Semantically equivalent as if the JavaScript was directly in the page Adam Doupé, Security and Vulnerability Analysis Document Object Model (DOM) • The Document Object Model is a programmatic interface in JavaScript to the manipulation of client-side content • Created a globally accessible in JavaScript document object – The document object is used to traverse, query, and manipulate the browser's representation of the HTML page as well as handle events • DOM 0, released in 1995 with original JavaScript – Very basic • Intermediate DOM began in 1997 with Microsoft and Netscape releasing incompatible improvements to DOM • W3C stepped in and started to define standards – – – – DOM 1, October 1998 DOM 2, November 2000 DOM 3, April 2004 DOM is now a W3C Living Standard, and various snapshots of the standard will turn into DOM 4 Adam Doupé, Security and Vulnerability Analysis DOM Example <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>DOM Example</title> </head> <body> <h1>DOM Example</h1> <div id='insert_here'> </div> </body> <script> var hr = document.createElement('HR'); document.getElementById('insert_here').appendChild(hr); </script> </html> Adam Doupé, Security and Vulnerability Analysis Adam Doupé, Security and Vulnerability Analysis Using the DOM • Coding proper DOM access in a cross-browser approach is a nightmare – Some highlights from http://stackoverflow.com/questions/565641/what-crossbrowser-issues-have-you-faced • "Internet Explorer does not replace &nbsp; or HTML char code 160, you need to replace its Unicode equivalent \u00a0" • "In Firefox a dynamically created input field inside a form (created using document.createElement) does not pass its value on form submit." • "document.getElementById in Internet Explorer will return an element even if the element name matches. Mozilla only returns element if id matches." • jQuery is an amazing library that provides a uniform interface and handles all the DOM cross-browser compatibilities Adam Doupé, Security and Vulnerability Analysis Browser Object Model (BOM) • Programmatic interface to everything outside the document (aka the browser) • No complete standard (the term BOM is colloquial) • Examples – window.name = "New name" – window.close() – window.location = "http://example.com" Adam Doupé, Security and Vulnerability Analysis JavaScript vs. DOM and BOM • JavaScript the language is defined separate from the DOM and BOM – DOM has its own specification, and much of the BOM is specified in HTML5 spec • In the web context, these are often confused, because they are used together so often • However, now with JavaScript popping up all over the place, it's an important distinction – – – – – Server-side code using Node.js Database queries (MongoDB) Flash (ActionScript, which has its own DOM-like capabilities) Java applications (javax.script) Windows applications (WinRT) Adam Doupé, Security and Vulnerability Analysis JavaScript – Object-based • Almost everything in JavaScript is an object – Objects are associative arrays (hash tables), and the properties and values can be added and deleted at run-time var object = {test: "foo", num: 50}; object['foo'] = object; console.log(object[object['test']]); object.num = 1000; console.log(object['num']); Adam Doupé, Security and Vulnerability Analysis Adam Doupé, Security and Vulnerability Analysis Live Demo Adam Doupé, Security and Vulnerability Analysis JavaScript – Recursion function factorial(n) { if (n === 0) { return 1; } return n * factorial(n - 1); } console.log(factorial(5)); 120 http://en.wikipedia.org/wiki/JavaScript Adam Doupé, Security and Vulnerability Analysis JavaScript – Anonymous Functions and Closures var createFunction = function() { var count = 0; return function () { return ++count; }; }; var inc = createFunction(); inc(); inc(); inc(); var inc2 = createFunction(); inc2(); http://en.wikipedia.org/wiki/JavaScript Adam Doupé, Security and Vulnerability Analysis Adam Doupé, Security and Vulnerability Analysis JavaScript – Run-Time Evaluation • JavaScript contains features to interpret a string as code and execute it – – – – – eval Function setTimeout setInterval execScript var foo = "bar"; eval("foo = 'adam';"); console.log(foo); var x = "console.log('hello');"; var test = new Function(x); test(); Adam Doupé, Security and Vulnerability Analysis Adam Doupé, Security and Vulnerability Analysis JavaScript Uses – Form Validation • How to validate user input on HTML forms? • Traditionally requires a round-trip to the server, where the server can check the input to make sure that it is valid Adam Doupé, Security and Vulnerability Analysis JavaScript Uses – Form Validation <?php if ($_GET['submit']) { $student = $_GET['student']; $class = $_GET['class']; $grade = $_GET['grade']; if (empty($student) || empty($class) || empty($grade)) { echo "<b>Error, did not fill out all the forms</b>"; } else if (!($grade == 'A' || $grade == 'B' || $grade == 'C' || $grade == 'D' || $grade == 'F')) { echo "<b>Error, grade must be one of A, B, C, D, or F</b>"; } else { echo "<b>Grade successfully submitted!</b>"; } } ?> <form> Student: <input type="text" name="student"><br> Class: <input type="text" name="class"><br> Grade: <input type="text" name="grade"><br> <input type="submit" name="submit"> </form> Adam Doupé, Security and Vulnerability Analysis Adam Doupé, Security and Vulnerability Analysis Adam Doupé, Security and Vulnerability Analysis Adam Doupé, Security and Vulnerability Analysis Adam Doupé, Security and Vulnerability Analysis Adam Doupé, Security and Vulnerability Analysis Adam Doupé, Security and Vulnerability Analysis Adam Doupé, Security and Vulnerability Analysis form_validation_regular.php empty class field wrong grade format correct submission Adam Doupé, Security and Vulnerability Analysis JavaScript Uses – Form Validation <script> function check_form() { var form = document.getElementById("the_form"); if (form.student.value == "" || form.class.value == "" || form["grade"].value == ""){ alert("Error, must fill out all the form"); return false; } var grade = form["grade"].value; if (!(grade == 'A' || grade == 'B' || grade == 'C' || grade == 'D' || grade == 'F')) { alert("Error, grade must be one of A, B, C, D, or F"); return false; } return true; } </script> <form id="the_form" onsubmit="return check_form()"> Student: <input type="text" name="student"><br> Class: <input type="text" name="class"><br> Grade: <input type="text" name="grade"><br> <input type="submit" name="submit"> </form> Adam Doupé, Security and Vulnerability Analysis Adam Doupé, Security and Vulnerability Analysis Adam Doupé, Security and Vulnerability Analysis Adam Doupé, Security and Vulnerability Analysis Adam Doupé, Security and Vulnerability Analysis Adam Doupé, Security and Vulnerability Analysis Adam Doupé, Security and Vulnerability Analysis form_validation_js.php correct submission Adam Doupé, Security and Vulnerability Analysis Client-Side Validation • Now that we're doing validation on the client, can we get rid of all those PHP checks in our server-side code? – No! – No guarantee that client-side validation is performed • User disables JavaScript • Command-line clients (Assignment 1 Part 2, curl) • Otherwise, users could enter arbitrary data that does not conform to your validation – Could lead to a security compromise or not • So the validation must remain on the server-side and the client-side – Brings up another problem, how to perform consist validation when server-side and client-side written in different languages Adam Doupé, Security and Vulnerability Analysis DHTML • Using JavaScript with HTML was called Dynamic HTML (DHTML) – Change images – Validate forms – Hide or add content based on user input • However, all the HTML data was sent to the user in one HTTP request • Had to make additional HTTP requests to load additional data, which would also have to send an entire page Adam Doupé, Security and Vulnerability Analysis The XMLHttpRequest Object • Microsoft developers working on Outlook Web Access for Exchange 2000 – An example is http://ex2010.asu.edu/ • Scalability problems with traditional web application • They created a DHTML version (circa) 1998 using an ActiveX control to fetch bits of data from the server using JavaScript • OWA team got the MSXML team (MSXML is Microsoft's XML library, and it shipped with IE) to include their ActiveX control (hence the XML in the name) – Shipped in IE 5, March 1999 • Exchange 2000 finally released in November 2000, and OWA used the ActiveX Object • Added by Netscape in December 2000 as XMLHttpRequest • Find the full story here: http://www.alexhopmann.com/story-ofxmlhttp/ Adam Doupé, Security and Vulnerability Analysis The XMLHttpRequest Object • Allows JavaScript code to (asynchronously) retrieve data from the server, then process the data and update the DOM • Because of the origin (ActiveX control on windows and included in Netscape's DOM), used to need two different ways to instantiate the control – Most browsers: • http_request = new XMLHttpRequest(); – Internet Explorer • http_request = new ActiveXObject("Microsoft.XMLHTTP"); Adam Doupé, Security and Vulnerability Analysis Creating an XMLHttpRequest • Using the onreadystatechange property of an XMLHttpRequest object one can set the action to be performed when the result of a query is received – http_request.onreadystatechange = function(){ <code here >}; • Then, one can execute the request • http_request.open('GET', 'http://example.com/show.php?keyword=foo', true); • http_request.send(); • Note that the third parameter indicates that the request is asynchronous, that is, the execution of JavaScript will proceed while the requested document is being downloaded Adam Doupé, Security and Vulnerability Analysis XMLHttpRequest Lifecycle • The function specified using the "onreadystatechange" property will be called at any change in the request status – – – – 0 (uninitialized: Object is not initialized with data) 1 (loading: Object is loading its data) 2 (loaded: Object has finished loading its data) 3 (interactive: User can interact with the object even though it is not fully loaded) – 4 (complete: Object is completely initialized) • Usually wait until the status is “complete” – if (http_request.readyState == 4) { operates on data} else { not ready, return} Adam Doupé, Security and Vulnerability Analysis XMLHttpRequest Success • After having received the document (and having checked for a successful return code – 200) the content of the request can be accessed: – As a string by calling: http_request.responseText – As an XMLDocument object: http_request.responseXML • In this case the object can be modified using the JavaScript DOM interface Adam Doupé, Security and Vulnerability Analysis XMLHttpRequest Example <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>AJAX Example</title> </head> <body> <h1>AJAX Example</h1> <div id='insert_here'> </div> <script> … </script> </body> </html> Adam Doupé, Security and Vulnerability Analysis XMLHttpRequest Example if (typeof XMLHttpRequest != "undefined") { var http_request = new XMLHttpRequest(); } else { var http_request = new ActiveXObject("Microsoft.XMLHTTP"); } if (typeof console == "undefined") { console = { "log" : function (text) { alert(text); } }; } http_request.onreadystatechange = function () { console.log(http_request.readyState); if (http_request.readyState === 4) { var text = http_request.responseText; var new_node = document.createTextNode(text); document.getElementById('insert_here').appendChild(new_node); } }; console.log("Before Request"); http_request.open('GET', 'ajax_test.txt', true); http_request.send(); console.log("After Request"); Adam Doupé, Security and Vulnerability Analysis Adam Doupé, Security and Vulnerability Analysis Adam Doupé, Security and Vulnerability Analysis Adam Doupé, Security and Vulnerability Analysis Adam Doupé, Security and Vulnerability Analysis Adam Doupé, Security and Vulnerability Analysis Adam Doupé, Security and Vulnerability Analysis Adam Doupé, Security and Vulnerability Analysis Adam Doupé, Security and Vulnerability Analysis Adam Doupé, Security and Vulnerability Analysis Adam Doupé, Security and Vulnerability Analysis Adam Doupé, Security and Vulnerability Analysis Adam Doupé, Security and Vulnerability Analysis Adam Doupé, Security and Vulnerability Analysis Adam Doupé, Security and Vulnerability Analysis Adam Doupé, Security and Vulnerability Analysis Adam Doupé, Security and Vulnerability Analysis Adam Doupé, Security and Vulnerability Analysis Adam Doupé, Security and Vulnerability Analysis Adam Doupé, Security and Vulnerability Analysis XMLHttpRequest with jQuery <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>AJAX jQuery Example</title> </head> <body> <h1>AJAX jQuery Example</h1> <div id='insert_here'> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"> </script> <script> $.get( "ajax_test.txt", function( data ) { $( "#insert_here" ).html( data ); }); </script> </body> </html> Adam Doupé, Security and Vulnerability Analysis Adam Doupé, Security and Vulnerability Analysis Asynchronous JavaScript and XML – AJAX • Can now make web applications that asynchronously fetch only the required data from the server – Can also respond to user input (clicks, form), and potentially load data • First reference to the term AJAX – https://web.archive.org/web/20050223021343 /http://adaptivepath.com/publications/essays/a rchives/000385.php Adam Doupé, Security and Vulnerability Analysis Client Side Scripting Technologies • • • • • • • Java Applets ActiveX Controls Adobe Flash Silverlight JavaScript JavaScript – DOM JavaScript – XMLHttpRequest Adam Doupé, Security and Vulnerability Analysis Technologies • • • • • • • • • • • • • • • • • • • • • • URI Percent Encoding HTTP Request HTTP Response HTTP Authentication HTML HTML Character References Form Urlencoding Cookies CGI ASP Servlets JSP PHP SQL Java Applets ActiveX Controls Adobe Flash Silverlight JavaScript JavaScript – DOM JavaScript – XMLHttpRequest Adam Doupé, Security and Vulnerability Analysis