Ga!Ng Javascript Mistakes Using HTML5
Total Page:16
File Type:pdf, Size:1020Kb
QUALYS SECURITY CONFERENCE 2012 LAS VEGAS MUNICH LONDON PARIS OCT 25-26 NOV 06 NOV 08 NOV 13 Mi#ga#ng JavaScript Mistakes Using HTML5 Mike Shema Qualys, Inc. Aria Resort & Casino, Las Vegas, October 25th 1 JavaScript, JScript, ECMAScript, *.exe • Cross-plaMorm, vendor-neutral liability • Easy to use, easier to misuse • Challenging to maintain • Achieving peace of mind from piece of code 2 QUALYS SECURITY CONFERENCE 2012 LAS VEGAS MUNICH LONDON PARIS OCT 25-26 NOV 06 NOV 08 NOV 13 try { security() } catch(err) { } 3 let me = count(ways); jsfunfuzz -- “It has found about 280 bugs in Firefox's JavaScript engine... About two dozen were memory safety bugs that we believe were likely to be exploitable to run arbitrary code.” http://www.squarefree.com/2007/08/02/introducing-jsfunfuzz/ 4 { var Pwn2Own = $money; } 5 MS12-063 Event-Driven, Non-Blocking Vulns <script> var arrr = new Array(); arrr[0] = window.document.createElement("img"); arrr[0]["src"] = "L"; </script> <iframe src="child.html"> <head><script> functionfuncB() { document.execCommand("selectAll"); }; functionfuncA() { document.write("L"); parent.arrr[0].src="YMjf\\u0c08\ \u0c0cKDogjsiIejengNEkoPDjfiJDIWUAzdfghjAAuUFGGBSIPPPUDFJKS OQJGH"; } </script></head> <body onload='funcB();' onselect='funcA()'> <div contenteditable='true'>a</div> 6 For#fying the User Agent • Execuon • Experience • Auto-updates • Link reputaon • Download tainGng • Phishing warnings • Process separaon • SSL/TLS indicators • Sandboxed plugins • XSS auditors 7 QUALYS SECURITY CONFERENCE 2012 LAS VEGAS MUNICH LONDON PARIS OCT 25-26 NOV 06 NOV 08 NOV 13 Design Paerns & Dangerous Territory 8 HTML Injec#on (XSS) • The 20+ year-old vuln that refuses to die. • But JavaScript makes the situaon beer! • No, JavaScript makes the situaon worse! • HTML5 to the rescue!(?) 9 Stop Building HTML on the Server • "String concatenation " + "is an " + $insecure " + "design pattern." • SQL injecon • Command injecGon • ... injecon • JSON messages for a dynamic DOM • DOM node inserGon/modificaon isn’t necessarily safer. • .textContent vs. .innerHTML 10 Careful Building HTML in the Browser • The URL is evil. • hZp://web.site/safe.page#<script>alert(9)</script> • JavaScript funcons are unsafe • document.write(), eval() 11 Aack of the Invisible Fragment hZp://web.site/dynamic#<img/src=""onerror=alert(9)> <script type="text/javascript"> $(document).ready(function() { var x = (window.location.hash.match(/^#([^\/].+)$/)||[])[1]; var w = $('a[name="' + x + '"], [id="' + x + '"]'); }); </script> 12 Serialize vs. Sanize [ hZp://bit.ly/amazonxss ] …>Page 16</span> ... t {...,"totalResults":4, require spaces to delimit "results":[[...],[...], their attributes. <img [33,"Page 16","... t src="." alt="" require spaces to delimit onerror="alert('<b> their attributes. <img/ zombie</b>')"> src=\".\"alt=\"\"onerror= JavaScript doesn't have \"alert('<b>zombie</b>') to… \"/> JavaScript doesnt have to rely on quotes to establish strings, nor do ...",...]]} 13 NoSQL/Comand Injec#on, Parsing • Using JavaScript to create queries, filters, etc. • String concatenaon & JSON injecGon • Server-side JavaScript requires server-side security principles. http://web.site/calendar?year=1984’;while(1);var%20foo=‘bar var data1 = '\ufffd1\ufffda'; var data2 = '\ufffd-1\ufffdhello'; var data3 = '\ufffd1<script>alert(9)</script>\ufffda'; var data4 = '\ufffd-27<script>alert(9)</script>\ufffda'; var data5 = '\ufffd-25\ufffda<script>alert(9)</script>'; 14 Understanding the Language • Same Origin Policy • Data access • Context • Percent encoding, HTML enGGes, aributes, values • Scope polluon with misplaced var or shadow variables typeof(null) == "object"; typeof(undefined) == "undefined" null == undefined; null === undefined; // no! 15 Scope of Exploraon <head> <script> var x = 1; (function(){ var x = 2; }); var y = 1; function scopeBar() { doSomething(x); } function scopeBaz() { var x = 0; doSomething(x); } </script> </head> <body> <script> var z = 3 function scopeFoo() { doSomething(y); } var x = 4; scopeBar(); </script> </body> 16 var BeefJS = { ... }; Scope & Precedence window.beef = BeefJS; <html> <html> <head> <body> <script> ...[ hook.js ]... BeefJS = {}; ... </script> <script> </head> beef.execute = <body> function(fn){ ... alert(n); ...[ hook.js ]... } ... </script> </body> </body> </html> </html> 17 JavaScript Everywhere <head> <script> BeefJS = { commands: new Array(), execute: function() {}, regCmp: function() {}, version: "<script>alert(9)</script>" }; </script> </head> ... 18 HpOnly? <head> <script> document.cookie = "BEEFHOOK="; </script> </head> ... 19 Prototype Chains <script> WebSocket.prototype._s = WebSocket.prototype.send; WebSocket.prototype.send = function(data) { // data = "."; console.log("\u2192 " + data); this._s(data); this.addEventListener('message', function(msg) { console.log("\u2190 " + msg.data); }, false); this.send = function(data) { this._s(data); console.log("\u2192 " + data); }; } </script> 20 data = "."; [22:49:57][*] BeEF server started (press control+c to stop) /opt/local/lib/ruby1.9/gems/1.9.1/ gems/json-1.7.5/lib/json/common.rb: 155:in `initialize': A JSON text must at least contain two octets! (JSON::ParserError) 21 QUALYS SECURITY CONFERENCE 2012 LAS VEGAS MUNICH LONDON PARIS OCT 25-26 NOV 06 NOV 08 NOV 13 JavaScript Libraries 22 JavaScript Libraries • Should be... • Oen are... • More opGmal • More disparate • More universal • Highly variant in quality • StylisGcally different • Shi security burden to • Have to... patch management • Play nice with others • Clear APIs (variable scope, • Auto versioning prototype chains) Hosted on CDNs • Balance performance • with style 23 Angular Developing With JavaScript Batman JS Closure CoffeeScript Dojo Ember JS • Challenges of an interpreted language Ext JS Facebook Connect jQuery jsmd Knockout Midori JS • Simple language, complex behaviors Modernizr MooTools MooTools More • hZp://jslint.com ObjectiveJ Prototype • hp://www.quirksmode.org Pusher Qooxdoo hZp://webreflecGon.blogspot.com Raphael • Rico Sammy Scriptaculous Socket.io Spine Browser tools improving, but imperfect. Spry • TypeKit twttr • hZp://bit.ly/QJ4g0C Underscore JS UIZE YUI YAHOO 24 There’s a Dark Side to Everything • Poisoning • Cache, CDN • Intermediaon, HTTP & public Wi-Fi • Func#ons for HTML injec#on payloads • More bad news for blacklisGng • Server-side JavaScript • ReimplemenGng HTTP servers with reimplemented bugs • Fingerprint, DoS, directory traversal 25 JavaScript Crypto ☣ • Stanford JS Crypto Library [ hZp://crypto.stanford.edu/sjcl/ ] • CryptoCat [ hZps://crypto.cat ] • Shied from .js to browser plugin • Use TLS for channel security • BeZer yet, use HSTS and DNSSEC. • There is no trusted execuon environment • ...in the current prototype-style language • ...in an HTTP connecGon that can be intercepted • ...in a site with an HTML injecGon vuln 26 QUALYS SECURITY CONFERENCE 2012 LAS VEGAS MUNICH LONDON PARIS OCT 25-26 NOV 06 NOV 08 NOV 13 HTML5 & Countermeasures 27 Programming • Abstrac#ng development to another language • Closure • Emscripten, compile C & C++ to JavaScript • TypeScript • Stac code analysis • New specs 28 Cross Origin Resource Sharing • Defines read-access trust of another Origin • Expresses trust, not security • But sGll contributes to secure design • Principle of Least Privilege • Beware of Access-Control-Allow-Origin: * • Short Access-Control-Max-Age • Minimal Access-Control-Allow-{Methods | Headers} • Check the Origin • Prevent CSRF from this browser 29 Domain-Based Separaon of Trust • Leverage the Same Origin Policy • Use one domain for trusted content • Use another domain for user content • Another for ads • etc. 30 HTML5 Sandboxes <iframe * src="infected.html"> * (empty) sandbox JavaScript not executed JavaScript executed sandbox="allow-scripts" document.cookie Set-Cookie header text/html-sandboxed Waiting for browser support 31 Content-Security-Policy • Provide granular access control to SOP • Choose monitor or enforce • Header only • Probably few code changes required, or unsafe-eval • (hZp-equiv has lower precedence) • Wai#ng for universal implementa#on • X-Content-Security-Policy • X-WebKit-CSP • hUp://www.w3.org/TR/CSP/ 32 Content-Security-Policy X-CSP: default-src 'self'; frame-src 'none' <!doctype html> <html> <body> <iframe src="./infected.html"></iframe> </body> </html> 33 Content-Security-Policy vs. XSS X-CSP: default-src 'self' <input type="text" name="q" value="foo" autofocus onfocus=alert(9)//""> X-CSP: default-src 'self' 'unsafe-inline' <input type="text" name="q" value="foo" autofocus onfocus=alert(9)//""> 34 Content-Security-Policy vs. XSS X-CSP: default-src 'self' <!doctype html><html><body> <iframe src="./infected.html"></iframe> </body></html> X-CSP: script-src evil.site <!doctype html><html><head> <script src="http://evil.site:3000/ hook.js"></script> </head></html> 35 Content-Security-Policy vs. DOM XSS $(document).ready(function() { var x = (window.location.hash.match(/^#([^\/].+)$/)||[])[1]; var w = $('a[name="' + x + '"], [id="' + x + '"]'); }); // This is an unsafe inline event handler var click = $('#main').attr('onclick', 'alert(9)'); // doesn't trigger unsafe-inline var click = $('#main').click(function(e) { alert(9) }); // doesn't trigger unsafe-inline ]var click = $('#main').bind("click", function(e) { alert(9) }); 36 On the Other Hand... • Awesome DoS if CSP headers are absent and XSS vuln is present: <meta http-equiv="X-WebKit-CSP" content="default-src 'none'"> 37 Careful with those Improvements • Some trade-offs between more objects, more APIs,