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-pla orm, 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
• Execu on • Experience • Auto-updates • Link reputa on • Download tain ng • Phishing warnings • Process separa on • 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 Pa erns & Dangerous Territory
8 HTML Injec on (XSS)
• The 20+ year-old vuln that refuses to die. • But JavaScript makes the situa on be er! • No, JavaScript makes the situa on worse! • HTML5 to the rescue!(?)
9 Stop Building HTML on the Server • "String concatenation " + "is an " + $insecure " + "design pattern." • SQL injec on • Command injec on • ... injec on
• JSON messages for a dynamic DOM • DOM node inser on/modifica on isn’t necessarily safer. • .textContent vs. .innerHTML
10 Careful Building HTML in the Browser
• The URL is evil. • h p://web.site/safe.page# • JavaScript func ons are unsafe • document.write(), eval()
11 A ack of the Invisible Fragment
h p://web.site/dynamic#
12 Serialize vs. Sani ze [ h p://bit.ly/amazonxss ]
…>Page 16 ... t {...,"totalResults":4, require spaces to delimit "results":[[...],[...], their attributes. src=\".\"alt=\"\"onerror= JavaScript doesn't have \"alert('zombie') 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 concatena on & JSON injec on • 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\ufffda'; var data4 = '\ufffd-27\ufffda'; var data5 = '\ufffd-25\ufffda';
14 Understanding the Language
• Same Origin Policy • Data access • Context • Percent encoding, HTML en es, a ributes, values • Scope pollu on with misplaced var or shadow variables typeof(null) == "object"; typeof(undefined) == "undefined" null == undefined; null === undefined; // no!
15 Scope of Explora on
16 var BeefJS = { ... }; Scope & Precedence window.beef = BeefJS;
17 JavaScript Everywhere
" }; ...18 H pOnly?
...19 Prototype Chains
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... • O en are... • More op mal • More disparate • More universal • Highly variant in quality • Stylis cally 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 • h p://jslint.com ObjectiveJ Prototype • h p://www.quirksmode.org Pusher Qooxdoo h p://webreflec on.blogspot.com Raphael • Rico Sammy Scriptaculous Socket.io Spine Browser tools improving, but imperfect. Spry • TypeKit twttr • h p://bit.ly/QJ4g0C Underscore JS UIZE YUI YAHOO
24 There’s a Dark Side to Everything
• Poisoning • Cache, CDN • Intermedia on, HTTP & public Wi-Fi
• Func ons for HTML injec on payloads • More bad news for blacklis ng
• Server-side JavaScript • Reimplemen ng HTTP servers with reimplemented bugs • Fingerprint, DoS, directory traversal
25 JavaScript Crypto ☣ • Stanford JS Crypto Library [ h p://crypto.stanford.edu/sjcl/ ] • CryptoCat [ h ps://crypto.cat ] • Shi ed from .js to browser plugin • Use TLS for channel security • Be er yet, use HSTS and DNSSEC. • There is no trusted execu on environment • ...in the current prototype-style language • ...in an HTTP connec on that can be intercepted • ...in a site with an HTML injec on 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
• Sta c code analysis
• New specs
28 Cross Origin Resource Sharing
• Defines read-access trust of another Origin • Expresses trust, not security • But s ll 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 Separa on 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
* (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 • (h p-equiv has lower precedence) • Wai ng for universal implementa on • X-Content-Security-Policy • X-WebKit-CSP • h p://www.w3.org/TR/CSP/
32 Content-Security-Policy
X-CSP: default-src 'self'; frame-src 'none'
33 Content-Security-Policy vs. XSS
X-CSP: default-src 'self'
X-CSP: default-src 'self' 'unsafe-inline'
34 Content-Security-Policy vs. XSS
X-CSP: default-src 'self'
X-CSP: script-src evil.site
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:
37 Careful with those Improvements
• Some trade-offs between more objects, more APIs, and less privacy • WebGL, ba ery status • Browser fingerprin ng • AppCache • Web Storage
38 String Concatena on Checklist
• Normalize the data • Character set conversions (e.g. ⇄ UTF-8, reject or replace bad sequences) • Character encoding conversion (e.g. %xx) • Iden fy the output context • DOM node, a ribute name, a ribute value, script, etc. • Apply controls at security boundaries • Time of Check, Time of Use -- Iden fy where data will be modified, stored, or rendered • Strip characters (carefully! prefer inclusion list to exclusion list) • Replace characters appropriate for context
39 Some Web Security Principles
• Always be suspicious of string concatena on • Abstract development to a more strongly-typed language, compile to JavaScript • Protect Web Storage data • Don’t use it for security-sensi ve data, • Pay a en on to DOM context • HTML en ty, percent encoding, String object, text node • Apply CORS and CSP headers to protect browsers from applica on mistakes • And X-Frame-Op ons
40 JavaScript
• Audit string concatena on • Avoid inline event handlers • $(#id).bind(...) • $(#id).click(...) • $(#id).on(...) • Embrace "use strict"; • Encounter errors more quickly, more loudly • Avoid implicit global scope problems • Remember to apply to each “code unit”
41 Security Loop
• Encourage users to update browsers • Suppor ng old browsers is a pain anyway
• Adopt established JavaScript libraries rather than custom implementa ons • Shi from pure development to patch management
• Adopt HTML5 security features • ...to protect users with HTML5-enabled browsers
42 QUALYS SECURITY CONFERENCE 2012
LAS VEGAS MUNICH LONDON PARIS OCT 25-26 NOV 06 NOV 08 NOV 13
Thank You!
43