HTML5: Attack and Secure

A presentation at Private training for HTML5 Developers in May 2015 in Kochi, Kerala, India by Anant Shrivastava

Slide 1

Slide 1

APPLICATION SECURITY TESTING

Slide 2

Slide 2

WHO AM I Anant Shrivastava Specialize in Web, Mobile and Linux Servers SANS GWAPT, RHCE, CEH Co-Author OWASP Testing Guide Project Lead Android Tamer CodeVigilant

Slide 3

Slide 3

WHO ARE YOU Names or Nicknames What’s your comfort level with HTML5 What do you expect from This course

Slide 4

Slide 4

DAY 1 Understand the latest buzzwords in HTML5 CORS JSON Newer HTML5 tags Local Storage and WebSQL DOM webworker Web API’s WebSockets iframe Sandboxing Understand the general use cases around all HTML5 technologies.

Slide 5

Slide 5

DAY 1 HANDS ON Write simple HTML5 based app/pages covering most of the above listed concepts. This will allow participants to understand how technology is working and clear out the development related queries.

Slide 6

Slide 6

BASIC CONCEPTS

Slide 7

Slide 7

HTML 5 Created by Web Hypertext Application Technology Working Group (WHATWG) and W3C Next generation of HTML (now current generation) On 28 October 2014, HTML5 was released as a stable W3C Recommendation Limelight Point: Can eliminate flash from web Main attraction being interactive

Slide 8

Slide 8

NEW FEATURES OF HTML 5 To understand this we will start with writing our own HTML5 pages. P.S.: The whole presentation is running on a HTML5 based framework.

Slide 9

Slide 9

CORS Cross origin resources sharing Will be covered in detail tomorrow when we play with it fully.

Slide 10

Slide 10

CORS OVERVIEW

Slide 11

Slide 11

WHAT IS ORIGIN http://127.0.0.1/index.html https://127.0.0.1/index.html http://127.0.0.1:8080/index.html http://127.0.0.1/testapp/index.html http://127.0.0.1:8080/testapp/index.html

Slide 12

Slide 12

PURPOSE Relax Same Origin Policies HTTP HEADER Access-Control-Allow-Origin or * Example OPTIONS /usermail HTTP/1.1 Origin: mail.example.com Content-Type: text/html HTTP/1.0 200 OK Access-Control-Allow-Origin: http://www.example.com, https://login.example.com Access-Control-Allow-Methods: POST, GET, OPTIONS Access-Control-Allow-Headers: X-Prototype-Version, X-Requested-With, Content-Type, A ccept Access-Control-Max-Age: 86400 Content-Type: text/html; charset=US-ASCII Connection: keep-alive Content-Length: 0

Slide 13

Slide 13

JSON JAVASCRIPT OBJECT NOTATION To be discussed in details when we do XHR and CORS tomorrow

Slide 14

Slide 14

HTML TAGS Many new tags added, many old tags updated

Slide 15

Slide 15

OLD <!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http:////www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd” >

Slide 16

Slide 16

NEW <!DOCTYPE html>

Slide 17

Slide 17

OLD <img src=”path/to/image” alt=”About image” /> <p>Image of Mars. </p>

Slide 18

Slide 18

NEW <figure> <img src=”path/to/image” alt=”About image” /> <figcaption> <p>This is an image of something interesting. </p> </figcaption> </figure>

Slide 19

Slide 19

OLD <link rel=”stylesheet” href=”path/to/stylesheet.css” type=”text/css” /> <script type=”text/javascript” src=”path/to/script.js”></script>

Slide 20

Slide 20

NEW <link rel=”stylesheet” href=”path/to/stylesheet.css” /> <script src=”path/to/script.js”></script>

Slide 21

Slide 21

NEW elements such as Header footer article Mainly cosmetic / flow element

Slide 22

Slide 22

HTML ELEMENTS

Slide 23

Slide 23

CONTENTEDITABLE <ul contenteditable=true> <li>List item 1</li> </ul> List item 1

Slide 24

Slide 24

INPUT TYPE <form action=”” method=”get”> <label for=”email”>Email:</label> <input id=”email” name=”email” type=”email” /> <input id=”date” name=”date” type=”date” /> <button type=”submit”> Submit Form </button> </form> Email: Date: dd/mm/yyyy Submit Form

Slide 25

Slide 25

VARIOUS TYPES DEFINED tel search email number range date month time url pattern=”[a-z]{3}[0-9]{3}” : 3 alphabet and 3 number

Slide 26

Slide 26

PLACEHOLDER <input name=”email” type=”email” placeholder=”username@website.com” /> username@website.com

Slide 27

Slide 27

MORE API’S

Slide 28

Slide 28

GEO LOCATIONS navigator.geolocation.getCurrentPosition(success, error); navigator.geolocation.watchCurrentPosition(success, error); function success(position) { var lat = position.coords.latitude; var long = position.coords.longitude; … }

Slide 29

Slide 29

LOCAL STORAGE With HTML5, web pages can store data locally within the user’s browser. Earlier, this was done with cookies. Web Storage is more secure and faster. Data not included with every server request, but used ONLY when asked for. It is also possible to store large amounts of data, without affecting the website’s performance. The data is stored in key/value pairs, and a web page can only access data stored by itself All browsers today offering 5-10 MB of storage in every user’s browser.i.e., For each domain 5MB of local storage. sessionStorage similar to localStorage but only available in current browser session.

Slide 30

Slide 30

EXAMPLE Example Of Localstorage <ul id=”present_textarea” contenteditable=”true”> <li>Test1</li> </ul> <input type=”button” id=”clearall” value=”clear Storage” > <script type=”text/javascript”> document.addEventListener(“DOMContentLoaded”, function() { console.log(“Onload fired via DOMContent Loaded”); if (localStorage.getItem(“text”)){ console.log(“text found”); document.getElementById(“present_textarea”).innerHTML = localStorage.getItem(“text”); }}); var textarea=document.getElementById(“present_textarea”); var clearall=document.getElementById(“clearall”); clearall.onclick=function(){ console.log(“onclick”); localStorage.clear(); }; textarea.onblur=function(){ console.log(“onblur”); localStorage.setItem(“text”,document.getElementById(“present_textarea”).innerHTML); }; </script>

Slide 31

Slide 31

WHAT IS APPLICATION CACHE? HTML5 introduces application cache, which means that a web application is cached, and accessible without an internet connection. Application cache gives an application three advantages: Offline browsing - users can use the application when they’re offline Speed - cached resources load faster Reduced server load - the browser will only download updated/changed resources from the server

Slide 32

Slide 32

EXAMPLE Define in HTML page <!DOCTYPE html> <html lang=”en” manifest=”cache.manifest”> cache.manifest (served with Content-Type: text/cache-manifest) CACHE MANIFEST # 2013-07-25 NETWORK: data.php FALLBACK: / /offline.html CACHE: /main/home /main/app.js /settings/home /settings/app.js http://myhost/logo.png http://myhost/check.png http://myhost/cross.png

Slide 33

Slide 33

APP CACHE – WHAT TO CACHE? Fonts Splash image App icon Entry page Fallback bootstrap Never Cache: CSS HTML Javascript

Slide 34

Slide 34

DOM Document Object model P.S. To be discussed in detail tomorrow.

Slide 35

Slide 35

QUESTIONS? 1. can DOM be used to add / delete elements? 2. is Cookie part of DOM or not?

Slide 36

Slide 36

WEB API’S 1. 2. 3. 4. Audio Video SVG and many more

Slide 37

Slide 37

WEBSOCKETS GET /chat HTTP/1.1 Host: server.example.com Upgrade: WebSocket Connection: Upgrade Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ== Origin: http://example.com Sec-WebSocket-Protocol: chat, superchat Sec-WebSocket-Version: 13 And on the server HTTP/1.1 101 Switching Protocols Upgrade: WebSocket Connection: Upgrade Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo= Sec-WebSocket-Protocol: chat

Slide 38

Slide 38

WEBSOCKET ws:// wss://

Slide 39

Slide 39

WEBWORKER When executing scripts in an HTML page, the page becomes unresponsive until the script is finished. A web worker is a JavaScript that runs in the background, independently of other scripts, without affecting the performance of the page. You can continue to do whatever you want: clicking, selecting things, etc., while the web worker runs in the background.

Slide 40

Slide 40

SERVER-SENT EVENTS - ONE WAY MESSAGING A server-sent event is when a web page automatically gets updates from a server. This was also possible before, but the web page would have to ask if any updates were available. With server-sent events, the updates come automatically. Examples: Facebook/Twitter updates, stock price updates, news feeds, sport results, etc.

Slide 41

Slide 41

IFRAME SANDBOXING

Slide 42

Slide 42

JAVASCRIPT FRAME BUSTING if( self == top ) { document.documentElement.style.display = ‘block’ ; } else { top.location = self.location ; }

Slide 43

Slide 43

EXAMPLE FRAMEBUSTING Open link

Slide 44

Slide 44

FRAMEBUSTING BYPASS <iframe sandbox src=”/examples/framebuster.html” /> I can never be framed

Slide 45

Slide 45

EXERCISES 1. Convert html4 to html5 2. write a program with following objectives 1. webpage take input from user (use HTML5 validation where applicable) Username nickname Full Name Date of Birth Email address 2. store all of them in localstorage except his nickname which is stored in session storage, 3. and option to clear the storage 3. Iframe a content page which has framebusting javascript code.

Slide 46

Slide 46

WHAT WE LEARNED 1. 2. 3. 4. How HTML5 differs from HTML4 How to convert HTML4 to HTML5 how to bypass framebusting code How CORS work conceptually

Slide 47

Slide 47

DAY 2 1. Attacking CORS and XHR 2. Exploiting DOM

Slide 48

Slide 48

ATTACKING XHR AND CORS

Slide 49

Slide 49

XHR XML HTTP REQUEST

Slide 50

Slide 50

SAMPLE XHR REQUEST function reqListener () { console.log(this.responseText); } var oReq = new XMLHttpRequest(); oReq.onload = reqListener; oReq.open(“get”, “yourFile.txt”, true); oReq.send(); GET Request yourFile.txt is fetched true means its async call reqlistener is callback function So XHR allows me to fetch content and get response too so what’s the problem

Slide 51

Slide 51

XHR NOT A SILVER BULLET

Slide 52

Slide 52

XHR MEET CORS Cross Origin Resource Sharing Relax same origin policy and allow third party read

Slide 53

Slide 53

CROSS ORIGIN NETWORK ACCESS Origin is permitted to send data to another origin but not read Interactions between origins are placed in three categories: Cross origin writes (redirects, links, form action etc.) Cross origin embedding (html tag with src/hrefs) Cross origin reads (not allowed without CORS etc.)

Slide 54

Slide 54

CROSS ORIGIN EMBEDDING JavaScript <script src=”…”></script>. CSS with <link rel=”stylesheet” href=”…”>. Images with <img>. Media files with <video> and <audio> tags. Plug-ins with <object>, <embed> and <applet>. Fonts with @font-face. Anything with <frame> and <iframe>.

Slide 55

Slide 55

CROSS ORIGIN POLICY

Slide 56

Slide 56

WHY IS CORS NEEDED? For legitimate and trusted requests to gain access to authorized data from other domains Think cross application data sharing models Allows data to be exchanged with trusted sites while using a relaxed Same Origin policy mode. Application APIs exposed via web services and trusted domains require CORS to be accessible over the SOP

Slide 57

Slide 57

CORS – SIMPLE REQUESTS Preflight is not needed if Request is a HEAD/GET/POST via XHR – No Custom headers Body is text/plain Server responds with a CORS header Browser determines access Neither the request, nor response contain cookies

Slide 58

Slide 58

CORS HEADERS – SIMPLE REQUEST Origin Header set by the client for every CORS request Value is the current domain that made the request Access-Control-Allow-Origin Set by the server and used by the browser to determine if the response is to be allowed or not. Can be set to * to make resources public (bad practice!)

Slide 59

Slide 59

CORS – REQUESTS WITH PREFLIGHT Preflight requests are made if Request is a method other than HEAD/GET/POST via XHR (PUT, DELETE etc.) Custom headers are present (X-PINGBACK etc.) Content-Type other than application/x-www- form-urlencoded, multipart/form-data, or text/plain A transparent request is made to the server requesting access information using OPTIONS

Slide 60

Slide 60

EXAMPLE FROM YESTERDAY OPTIONS /usermail HTTP/1.1 Origin: mail.example.com Content-Type: text/html HTTP/1.0 200 OK Access-Control-Allow-Origin: http://www.example.com, https://login.example.com Access-Control-Allow-Methods: POST, GET, OPTIONS Access-Control-Allow-Headers: X-Prototype-Version, X-Requested-With, Content-Type, Accept Access-Control-Max-Age: 86400 Content-Type: text/html; charset=US-ASCII Connection: keep-aliv e Content-Length: 0

Slide 61

Slide 61

EXAMPLE: CUSTOM HEADERS xmlhttp.open(“POST”,”ajax_test.php”,true); xmlhttp.setRequestHeader(“Content-type”,”application/x-www-form-urlencoded”); xmlhttp.send(“fname=Henry&lname=Ford”);

Slide 62

Slide 62

CORS – REQUESTS WITH PREFLIGHT Browser sends Origin header Access-Control-Request-Method Access-Control-Request-Headers – (Optional) Server sends set of CORS headers that the browser uses to determine if the actual request has to be made or not

Slide 63

Slide 63

CORS HEADERS – REQUEST WITH PREFLIGHT (PREFLIGHT BROWSER REQUEST) Origin Header set by the client for every CORS request Value is the current domain that made the request Access-Control-Request-Method: Set by the browser, along with Origin. Value is the method that the request wants to use Access-Control-Request-Headers(Optional): A comma separated list of the custom headers being used.

Slide 64

Slide 64

CORS HEADERS – REQUEST WITH PREFLIGHT (PREFLIGHT SERVER RESPONSE) Access-Control-Allow-Origin – Same as in Simple requests Access-Control-Allow-Methods: a comma separated list of allowed methods Access-Control-Allow-Headers: a comma separated list of headers that the server will allow. Access-Control-Max-Age: the amount of time in seconds that this preflight request should be cached for.

Slide 65

Slide 65

CORS INSECURITIES

Slide 66

Slide 66

CORS SECURITY - UNIVERSAL ALLOW Setting the ‘Access-Control-Allow-Origin’ header to * Effectively turns the content into a public resource, allowing access from any domain Scenarios? An attacker can steal data from an intranet site that has set this header to * by enticing a user to visit an attacker controlled site on the Internet. An attacker can perform attacks on other remote apps via a victim’s browser when the victim navigates to an attacker controlled site.

Slide 67

Slide 67

CORS – ACCESS CONTROL BASED ON ORIGIN The Origin header indicates that the request is from a particular domain, but does not guarantee it Spoofing the Origin header allows access to the page if access is based on this header Scenarios? An attacker sets the Origin header to view sensitive information that is restricted Attacker uses cURL to set a custom origin header curl —header ‘origin:http://someserver.com’ http://myserver.com:90/demo/origin_spoof.p hp

Slide 68

Slide 68

CORS – CACHING OF PREFLIGHT RESPONSES The Access-Control-Max-Age header is set to a high value, allowing browsers to cache Preflight responses Caching the preflight response for longer duration can pose a security risk. If the COR access-control policy is changed on the server the browser would still follow the old policy available in the Preflight Result Cache

Slide 69

Slide 69

CORS SECURITY – MISPLACED TRUST Data exchange between two domains is based on trust If one of the servers involved in the exchange of data is compromised then the model of CORS is put at risk Scenarios? An attacker can compromise site A and host malicious content knowing site B trusts the data that site A sends to site B via CORS request resulting in XSS and other attacks. An attacker can compromise site B and use the exposed CORS functionality in site A to attack users in site A

Slide 70

Slide 70

CSRF WITH CORS Server may process client request to change server side data while verifying that the Origin header was set An attacker can use the .withCredentials = “true” property of XHR to replay any cookies to the application on which the victim is logged in Scenarios? An attacker sets the Origin header or uses a trusted site A to send a non idempotent request to site B The victim who is logged into site B when he is viewing the trusted site A causes site B to create a user account without his knowledge via a CSRF attack

Slide 71

Slide 71

PREVENTIVE CHECKS Have only one and non empty instance of the origin header, Have only one and non empty instance of the host header, The value of the origin header is present in a internal allowed domains list (white list). As we act before the step 2 of the CORS HTTP requests/responses exchange process, allowed domains list is yet provided to client, Cache IP of the sender for 1 hour. If the sender send one time a origin domain that is not in the white list then all is requests will return an HTTP 403 response (protract allowed domain guessing).

Slide 72

Slide 72

MORE PREVENTIVE CHECKS if its B2B then a strict IP filtering. Custom Permission set per origin can be configured at the application end. (might result in massive overhead for large application with varied origin’s of access)

Slide 73

Slide 73

EXPLOITING DOM

Slide 74

Slide 74

DOM DOCUMENT OBJECT MODEL interface that allows you to programmatically access and manipulate the contents of a web page (or document) It provides a structured, object-oriented representation of the individual elements and content in a page with methods for retrieving and setting the properties of those objects It also provides methods for adding and removing such objects, allowing you to create dynamic content Document is arranged in hierarchy of nodes.

Slide 75

Slide 75

DOM NODES NodeA.firstChild = NodeA1 NodeA.lastChild = NodeA3 NodeA.childNodes.length = 3 NodeA.childNodes[0] = NodeA1 NodeA1.nextSibling = NodeA2 NodeA1.parentNode = NodeA NodeA3b.parentNode.parentNode = NodeA

Slide 76

Slide 76

DOM SOURCE Cookies document.cookie Window Name windows.name Everything taken from the URL document.URL document.URLUnencoded document.location(.pathname|.href|.search|.hash) window.location(.pathname|.href|.search|.hash) The Referrer document.referrer

Slide 77

Slide 77

SINKS HTML Element creator innerHTML outerHTML document.write user input parsing eval execScript function setTimeout setInterval script.src iframe.src location.(replace|assign)

Slide 78

Slide 78

WHAT IS DOMXSS http://www.webappsec.org/projects/articles/071105.html https://code.google.com/p/domxsswiki/wiki/Introduction

Slide 79

Slide 79

HOW TO EXPLOIT DOMXSS

Slide 80

Slide 80

HOW TO FIND DOM-XSS Finding All Sources /(location\s*[[.])|([.[]\s*[“’]?\s*(arguments|dialogArguments|innerHTML|write(ln)?|open(Dia log)?|showModalDialog|cookie|URL|documentURI|baseURI|referrer|name|opener|parent|top|content| self|frames)\W)|(localStorage|sessionStorage|Database)/ Finding Sinks /((src|href|data|location|code|value|action)\s*[“’]]\s+?\s*=)|((replace|assign|navigate|g etResponseHeader|open(Dialog)?|showModalDialog|eval|evaluate|execCommand|execScript|setTimeou t|setInterval)\s*[“’]]\s()/ Finding Sink (Jquery) /after(|.append(|.before(|.html(|.prepend(|.replaceWith(|.wrap(|.wrapAll(|$( |.globalEval(|.add(|jQUery(|$(|.parseHTML(/

Slide 81

Slide 81

USEFUL SOURCES FOR DOMXSS EXPLOITATION andlabs.org Domsnitch RA2 Dominator