SlideShare a Scribd company logo
XSS Attack & Defense
Eoin Keary
CTO BCC Risk Advisory
www.bccriskadvisory.com
www.edgescan.com
@eoinkeary
What is XSS?
Attacker driven JavaScript or JavaScript Injection
Most common web vulnerability
Easy vulnerability to find via auditing
Easy vulnerability to exploit
Certain types of XSS are very complex to fix
Significant business and technical impact potential
XSS Attack Payload Types
Session hijacking
Site defacement
Network scanning
Undermining CSRF defenses
Site redirection/phishing
Data theft
Keystroke logging
Loading of remotely hosted scripts
Input Example
Consider the following URL :
www.example.com/saveComment?comment=Great+Site!
How can an attacker misuse this?
XSS Variants
Data provided by a client is immediately used by server-side
scripts to generate a page of results for that user.
Search engines
Reflected/
Transient
A page's client-side script itself accesses a URL request
parameter and uses this information to dynamically write some
HTML to its own page
DOM XSS is triggered when a victim interacts with a web page
directly without causing the page to reload.
Difficult to test with scanners and proxy tools – why?
DOM based
XSS
Data provided by a client is first stored persistently on the server
(e.g., in a database, filesystem), and later displayed to users
Bulletin Boards, Forums, Blog Comments
Stored/
Persistent
Reflected XSS
1. Hacker sends link to
victim.
Link contains XSS
payload
2. Victim views page via
XSS link supplied by
attacker.
3. XSS code executes on victims
browser and sends cookie to
evil server
4. Cookie is stolen. The
Attacker can hijack the
Victims session.
Victim
Hackler
Reflected XSS Code Sample
//Search.aspx.cs
public partial class _Default : System.Web.UI.Page
{
Label lblResults;
protected void Page_Load(object sender, EventArgs e)
{
//... doSearch();
this.lblResults.Text = "You Searched For " +
Request.QueryString["query"];
}
OK: http://app.com/Search.aspx?query=soccer
NOT OK: http://app.com/Search.aspx?query=<script>...</script>
Persistent/Stored XSS
2
3
4
Persistent/Stored XSS Code Sample
<%
int id = Integer.parseInt(request.getParameter("id"));
String query = "select * from forum where id=" + id;
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
if (rs != null) {
rs.next ();
String comment = rs.getString ("comment");
%>
User Comment : <%= comment %>
<%
}
%>
DOM-Based XSS (Client-side XSS)
2
3
1
4
DOM-Based XSS
http://www.com/index.jsp#name=<script>alert(document.cookie)<script>
<HTML>
<TITLE>Welcome!</TITLE>
Hi
<SCRIPT>
var pos=document.URL.indexOf("name=")+5;
document.write(document.URL.substring(pos,document.URL.length));
</SCRIPT>
<BR>
Welcome to our system
</HTML>
OK : http://a.com/page.htm#name=Joe
NOT OK: http://a.com/page.htm#name=<script>...</script>
In DOM XSS the attack is NOT
embedded in the HTML
Test for Cross-Site Scripting
Make note of all pages that display input originating from current or other
users
Test by inserting malicious script or characters to see if they are ultimately
displayed back to the user
Very easy to discover XSS via dynamic testing
More difficult to discover via code review
Examine code to ensure that application data is HTML encoded before being
rendered to users
Test for Cross-Site Scripting
Remember the three common types of attacks:
Input parameters that are rendered directly back to the user
Server-Side
Client-Side
Input that is rendered within other pages
Hidden fields are commonly vulnerable to this exploit as there is a
perception that hidden fields are read-only
Error messages that redisplay user input
Test for Cross-Site Scripting
Each input should be tested to see if data gets rendered back to the user.
Break out of another tag by inserting "> before the malicious script
Bypass <script> "tag-hunting" filters
May not require tags if the input is inserted into an existing JavaScript
routine <- DOM XSS
<IMG SRC="javascript:alert(document.cookie)">
<p style="left:expression(eval('alert(document.cookie)'))">
u003Cscriptu003E
<SCRIPT> <%= userdata %> </SCRIPT>
Why won't these strategies work?
Danger: XSS Weak Defense Used
Getting rid of XSS is a difficult task
Eliminate <, >, &, ", ' characters?
Eliminate all special characters?
Disallow user input? (not possible)
Global filter?
How can we prevent XSS in our web application
XSS Defense: The Solution?
Depends on the type of user input
 HTML, Strings, Uploaded Files
Depends on where user input is displayed in an HTML document
 HTML Body
 HTML Attribute
 JavaScript Variable Assignment
Several defensive techniques needed depending on context
 Input Validation (raw HTML input)
 Output Encoding (Strings)
 Sandboxing (3rd party JavaScript like ads)
Other 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.introducti
on.html
• Java (Updated February 2014)
• 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/
• Reform Project
• .NET v1/v2, Classic ASP, Python, Perl, JavaScript
• https://www.owasp.org/index.php/Category:OWASP_Encoding_Project
&lt;
HTML Entity Encoding: The Big 6
1. & &amp;
2. < &lt;
3. > &gt;
4. " &quot;
5. ' &#x27;
6. / &#x2F;
Output Encoding Code Sample
StringBuffer buff = new StringBuffer();
if ( value == null ) {
return null;
}
for(int i=0; i<value.length(); i++) {
char ch = value.charAt(i);
if ( ch == '&' ) {
buff.append("&amp;");
} else if ( ch == '<') {
buff.append("&lt;");
} else if ( ch == '>') {
buff.append("&gt;");
} else if ( Character.isWhitespace(ch ) ) {
buff.append(ch);
} else if ( Character.isLetterOrDigit(ch) ) {
buff.append(ch);
} else if ( Integer.valueOf(ch).intValue() >= 20 &&
Integer.valueOf(ch).intValue() <= 126 ) {
buff.append( "&#" + (int)ch + ";" );
}
}
return buff.toString();
Simple HTML
encoding method
for HTML context
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 (macher.maches())
{
out.println("Your email address is: " + Encoder.HtmlEncode(email));
}
else
{
//log & throw a specific validation exception and fail safely
}
Danger: Multiple Contexts
HTML Body
HTML
Attributes
<STYLE>
Context
<SCRIPT>
Context
URL Context
Different encoding and validation techniques needed for different contexts!
HTML Encoding:
Certain sets of characters mean something special in HTML. For instance ‘<’ is used to open and
HTML tag and ‘&’ is used to and the beginning of a sequence of characters to define special symbols
like the copy write symbol. (htmlentities in PHP)
HttpUtility.HtmlEncode(“<script>alert(‘&’);</script>”)
&lt;script&gt;alert(&#39;&amp;&#39;);&lt;/script&gt;
Attribute Encoding:
Attribute encoding replaces three characters that are not valid to use inside attribute values in
HTML. Those characters are ampersand ‘&’, less-than ‘<’, and quotation marks ‘”’
HttpUtility.HtmlAttributeEncode(“<script>alert(”&”);</script>”)
&lt;script>alert(&quot;&amp;&quot;);&lt;/script>
URL Encoding
URL encoding used when you have some data that you would like to pass in the URL and that data
contains some reserved or invalid characters (&/<space>) – (urlencode() in php)
HttpUtility.UrlEncode(“Some Special Information / That needs to be in the URL”)
Some+Special+Information+%2f+That+needs+to+be+in+the+URL
OR
Some%20Special%20Information%20%2f%20That%20needs%20to%20be%20in%20t
he%20URL
XSS Defense by Data Type and Context
Data Type Context Defense
String HTML Body/Attribute HTML Entity Encode/HTML Attribute Encoder
String Java String Java String Encoding
String JavaScript Variable JavaScript Hex Encoding
String GET Parameter URL Encoding
String Untrusted URL URL Validation, avoid javascript: URL’s, Attribute encoding,
safe URL verification
String CSS Value Strict structural validation, CSS Hex encoding, good design
HTML HTML Body HTML Validation (JSoup, AntiSamy, HTML Sanitizer)
Any DOM DOM XSS Cheat sheet
Untrusted
JavaScript
Any Sandboxing
JSON Client parse time JSON.parse() or json2.js
Safe HTML Attributes include: align, alink, alt, bgcolor, border, cellpadding, cellspacing, class, color,
cols, colspan, coords, dir, face, height, hspace, ismap, lang, marginheight, marginwidth, multiple,
nohref, noresize, noshade, nowrap, ref, rel, rev, rows, rowspan, scrolling, shape, span, summary,
tabindex, title, usemap, valign, value, vlink, vspace, width
XSS Defense by Data Type and Context
Context Encoding OWASP Java Encoder
HTML Body HTML Entity Encode Encoder.forHtmlContent
HTML Attribute HTML Entity Encode Encoder.forHtmlAttribute
Java String Java String Encoding Encoder.forJava
JavaScript Variable JavaScript Hex Encoding Encoder.forJavaScript
Encoder.forJavaScriptBlock
Encoder.forJavaScriptAttribute
GET Parameter URL Encoding
Encoder.forUriComponent
Untrusted URL URL Validation, avoid javascript: URL’s,
attribute encoding, safe URL
verification
Encoder.forUri
CSS Value Strict structural validation, CSS Hex
encoding, good design
Encoder.forCssString
Encoder.forCssUrl
OWASP Java Encoder Project
https://www.owasp.org/index.php/OWASP_Java_Encoder_Project
• No third party libraries or configuration necessary.
• This code was designed for high-availability/high-
performance encoding functionality. Redesigned for
performance.
• Simple drop-in encoding functionality
• More complete API (uri and uri component
encoding, etc) in some regards.
• This is a Java 1.5 project.
• Last updated February 4, 2014 (version 1.1.1)
The Problem
Web Page built in Java JSP is vulnerable to XSS
The Solution
<%-- Basic HTML Context --%>
<body><b><%= Encode.forHtml(UNTRUSTED) %>" /></b></body>
<%-- HTML Attribute Context --%>
<input type="text" name="data" value="<%= Encode.forHtmlAttribute(UNTRUSTED) %>" />
<%-- Javascript Block context --%>
<script type="text/javascript">
var msg = "<%= Encode.forJavaScriptBlock(UNTRUSTED) %>"; alert(msg);
</script>
<%-- Javascript Variable context --%>
<button onclick="alert('<%= Encode.forJavaScriptAttribute(UNTRUSTED) %>');">click
me</button>
OWASP Java Encoder Project
https://www.owasp.org/index.php/OWASP_Java_Encoder_Project
OWASP Java Encoder Project
https://www.owasp.org/index.php/OWASP_Java_Encoder_Project
HTML Contexts
Encode#forHtml(String)
Encode#forHtmlContent(String)
Encode#forHtmlAttribute(String)
Encode#forHtmlUnquotedAttribute
(String)
XML Contexts
Encode#forXml(String)
Encode#forXmlContent(String)
Encode#forXmlAttribute(String)
Encode#forXmlComment(String)
Encode#forCDATA(String)
CSS Contexts
Encode#forCssString(String)
Encode#forCssUrl(String)
JavaScript Contexts
Encode#forJavaScript(String)
Encode#forJavaScriptAttribute(String)
Encode#forJavaScriptBlock(String)
Encode#forJavaScriptSource(String)
URI/URL contexts
Encode#forUriComponent(String)
Microsoft Encoder and AntiXSS Library
• System.Web.Security.AntiXSS
• Microsoft.Security.Application
. AntiXSS
• Can encode for HTML, HTML
attributes, XML, CSS and
JavaScript.
• Native .NET Library
• Very powerful well written
library
• For use in your User Interface
code to defuse script in output
HTML Encoding stops XSS in this context!
Sample test attack payload:
Reflective XSS attack example:
Untrusted data may land in a UI snippet like the following:
<div><%= request.getParameter("error_msg") %></div>
http://example.com/error? error_msg=
<script>alert(document.cookie)</script>
XSS in HTML Body
example.com/error?error_msg=You cannot access that file.
HTML Body Escaping Examples
OWASP Java Encoder
<b><%= Encode.forHtml(UNTRUSTED)%></b>
<p>Title:<%= Encode.forHtml(UNTRUSTED)%></p>
<textarea name="text">
<%= Encode.forHtmlContent(UNTRUSTED) %>
</textarea>
AntiXSS .NET
Encoder.HtmlEncode(UNTRUSTED)
XSS in HTML Attributes
 Where else can XSS go?
 <input type="text" name="comments" value="">
 What could an attacker put in here?
 <input type="text" name="comments"
 value="hello" onmouseover="/*fire attack*/">
 Attackers can add event handlers:
 onMouseOver
 onLoad
 onUnLoad
 etc…
HTML Attribute Context
 Aggressive escaping is needed when placing untrusted data into typical attribute
values like width, name, value, etc.
 This rule is NOT ok for complex attributes likes href, src, style, or any event handlers
like onblur or onclick.
 Escape all non alpha-num characters with the &#xHH; format
 This rule is so aggressive because developers frequently leave attributes unquoted
 <div id=DATA></div>
HTML Attribute Escaping Examples
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)
URL Parameter Escaping
36
Escape all non alpha-num characters with the %HH format
<a href="/search?data=<%=DATA %>">
Be careful not to allow untrusted data to drive entire URL’s or URL fragments
This encoding only protects you from XSS at the time of rendering
the link
Treat DATA as untrusted after submitted
URL Parameter Escaping Examples
OWASP Java Encoder
<%-- Encode URL parameter values --%>
<a href="/search?value=
<%=Encode.forUriComponent(parameterValue)%>&order=1#top">
<%-- Encode REST URL parameters --%>
<a href="http://www.codemagi.com/page/
<%=Encode.forUriComponent(restUrlParameter)%>">
AntiXSS .NET
Encoder.UrlEncode(untrustedUrlFragment)
Handling Untrusted
URL’s
1) First validate to ensure the string is a valid URL
2) Avoid Javascript: URL’s
3) Only allow HTTP or HTTPS only
4) Check the URL for malware inbound and outbound
5) Encode URL in the right context of display
<a href="UNTRUSTED URL">UNTRUSTED URL</a>
Escaping when managing complete URL’s
Assuming the untrusted URL has been properly validated....
OWASP Java Encoder
<a href="<%= Encode.forHTMLAttribute(untrustedURL) %>">
Encode.forHtmlContent(untrustedURL)
</a>
AntiXSS .NET
<a href="<%= Encoder.HtmlAttributeEncode(untrustedURL) %>">
Encoder.HtmlEncode(untrustedURL)
</a>
XSS in JavaScript Context
http://example.com/viewPage?name=Jerry
 What attacks would be possible?
 What would a %0d%0a in the name parameter do in the output?
JavaScript Escaping Examples
OWASP Java Encoder
<button
onclick="alert('<%= Encode.forJavaScript(alertMsg) %>');">
click me</button>
<button
onclick="alert('<%= Encode.forJavaScriptAttribute(alertMsg)
%>');">click me</button>
<script type="text/javascript">
var msg = "<%= Encode.forJavaScriptBlock(alertMsg) %>";
alert(msg);
</script>
AntiXSS .NET
Encoder.JavaScriptEncode(alertMsg)
XSS in the Style Tag
42
Applications sometimes take user data and use it to generate presentation style
Consider this example:
http://example.com/viewDocument?background=white
URL parameter written within style tag
CSS Context: XSS Defense
43
Escape all non alpha-num characters with the HH format
<span style=bgcolor:DATA;>text</style>
Do not use any escaping shortcuts like "
Strong positive structural validation is also required
If possible, design around this “feature”
 Use trusted CSS files that users can choose from
 Use client-side only CSS modification (font size)
XSS in CSS String Context Examples
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)
Dangerous Contexts
45
There are just certain places in HTML documents where you cannot place untrusted
data
Danger: <a $DATA> $DATA onblur="attack"
There are just certain JavaScript functions that cannot safely handle untrusted data
for input
Danger: <script>eval($DATA);</script>
XSS Defense by Data Type and Context
Data Type Context Defense
String
HTML
Body/Attribute
HTML Entity Encode
String JavaScript Variable JavaScript Hex encoding
String GET Parameter URL Encoding
String Untrusted URL
URL Validation, avoid javascript: URL’s, Attribute encoding,
safe URL verification
String CSS Strict structural validation, CSS Hex encoding, good design
HTML HTML Body HTML Validation (JSoup, AntiSamy, HTML Sanitizer)
Any DOM DOM XSS Cheat sheet
Untrusted JavaScript Any Sandboxing
JSON Client parse time JSON.parse() or json2.js
Safe HTML Attributes include: align, alink, alt, bgcolor, border, cellpadding, cellspacing, class, color,
cols, colspan, coords, dir, face, height, hspace, ismap, lang, marginheight, marginwidth, multiple,
nohref, noresize, noshade, nowrap, ref, rel, rev, rows, rowspan, scrolling, shape, span, summary,
tabindex, title, usemap, valign, value, vlink, vspace, width
HTML Sanitization and XSS
What is HTML Sanitization
• HTML sanitization takes markup as input, outputs “safe” markup
• Different from encoding
• URLEncoding, HTMLEncoding, will not help you here!
• HTML sanitization is everywhere
• TinyMCE/CKEditor Widgets
• Web forum posts w/markup
• Javascript-based Windows 8 Store apps
• Outlook.com
• Advertisements
Why are HTML sanitization bugs important?
• Worst case scenario
• Script running from a mail message executes within the security
context of the mail application
• …from the preview pane that appears automatically
• Attacker could set up auto-forwarding, impersonate you, steal all your
mail, etc.
• Yet, HTML sanitization bugs are pervasive
• Fuzzing? Can be helpful, but difficult
• Threat modeling? Not so relevant…
• Smart hackers with some free time – very relevant
And the underlying platforms continue to change. All of them.
This is a hard problem.
HTML Sanitization Bug #1
• Sanitizer Bypass in validator Node.js Module by @NealPoole
(https://t.co/5omk5ec2UD)
• Nesting
• Input: <scrRedirecRedirect 302 302ipt
type="text/javascript">prompt(1);</scrRedirecRedirect 302
302ipt>
• Output: <script
type="text/javascript">prompt(1);</script>
• Observation: Removing data from markup can create XSS where
it didn’t previously exist!
HTML Sanitization Bug #2
• CVE-2011-1252 / MS11-074
• SharePoint / SafeHTML (UnsafeHTMLWhenUsingIE(String))
• Input:
<style>div{color:rgb(0,0,0)&a=expression(alert(1))}
</style>
• &  &amp; (HTML Encode)
• Output:
<style>div{color:rgb(0,0,0)&amp;a=expression(alert(
1))}</style>
• Observations:
• Sanitizer created a delimiter (the semi-colon)
• Legacy IE CSS expression syntax required to execute script
• Sanitizer: “expression” is considered to be in a benign location
• Browser: “expression” is considered to be the RHS of a CSS property set
operation
HTML Sanitization Bug #3
• Wordpress 3.0.3 (kses.php)
• Credit: Mauro Gentile (@sneak_)
• Thx @superevr!
• Input and Output:
<a HREF="javascript:alert(0)">click me</a>
• Observations:
• No content modification required to trigger the vulnerability
• Sanitizer: Only lower case “href” recognized as an attribute
• Browser: HREF attribute recognized, javascript: URL executes on click
• Sanitizer and browser don’t agree on what constitutes an attribute name
OWASP
OWASP HTML Sanitizer Project
https://www.owasp.org/index.php/OWASP_Java_HTML_Sanitizer_Project
• HTML Sanitizer written in Java which lets you include HTML
authored by third-parties in your web application while protecting
against XSS.
• This code was written with security best practices in mind, has an
extensive test suite, and has undergone adversarial security
review
• https://code.google.com/p/owasp-java-html-sanitizer/
• Very easy to use.
• It allows for simple programmatic POSITIVE policy configuration.
No XML config.
• Actively maintained by Mike Samuel from Google's AppSec team!
• This is code from the Caja project that was donated by Google. It
is rather high performance and low memory utilization.
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);
• Pure JavaScript, client side HTML Sanitization with CAJA!
• http://code.google.com/p/google-caja/wiki/JsHtmlSanitizer
• https://code.google.com/p/google-
caja/source/browse/trunk/src/com/google/caja/plugin/html-sanitizer.js
• Python
• https://pypi.python.org/pypi/bleach
• PHP
• http://htmlpurifier.org/
• http://www.bioinformatics.org/phplabware/internal_utilities/htmLawed/
• .NET AntiXSS Library (v4.3 released June 2, 2014)
• http://www.nuget.org/packages/AntiXss/ (encoding)
• https://github.com/mganss/HtmlSanitizer (HTML Sanitization)
• Ruby on Rails
• https://rubygems.org/gems/loofah
• http://api.rubyonrails.org/classes/HTML.html
• Java
• https://www.owasp.org/index.php/OWASP_Java_HTML_Sanitizer_Project
HTML Sanitizers by Language
DOM Based XSS Defense
57
DOM Based XSS is a complex risk
Suppose that x landed in …
<script>setInterval(x, 2000);</script>
For some Javascript functions, even JavaScript that is
properly encoded will still execute!
Direct
execution
 eval()
 window.execScript()/function()/setInterval()/setTimeout(),
requestAnimationFrame()
 script.src(), iframe.src()
Build HTML/
JavaScript
 document.write(), document.writeln()
 elem.innerHTML = danger, elem.outerHTML = danger
 elem.setAttribute("dangerous attribute", danger) – attributes
like: href, src, onclick, onload, onblur, etc.
Within
execution
context
 onclick()
 onload()
 onblur(), etc
Source: https://www.owasp.org/index.php/DOM_based_XSS_Prevention_Cheat_Sheet
Dangerous JavaScript Sinks
Some Safe JavaScript Sinks
Setting a
value
 elem.innerText = "danger";
 formfield.value = "danger";
Safe JSON
parsing
 JSON.parse() (rather than eval())
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/
jQuery API’s and XSS
Dangerous jQuery 1.7.2 Data Types
CSS Some Attribute Settings
HTML URL (Potential Redirect)
jQuery methods that directly update DOM or can execute JavaScript
$() or jQuery() .attr()
.add() .css()
.after() .html()
.animate() .insertAfter()
.append() .insertBefore()
.appendTo() Note: .text() updates DOM, but is safe.
jQuery methods that accept URLs to potentially unsafe content
jQuery.ajax() jQuery.post()
jQuery.get() load()
jQuery.getScript()
Don’t send untrusted data to these methods,
or properly escape the data before doing so
jQuery – But there’s more…
More danger
 jQuery(danger) or $(danger)
 This immediately evaluates the input!!
 E.g., $("<img src=x onerror=alert(1)>")
 jQuery.globalEval()
 All event handlers: .bind(events), .bind(type, [,data], handler()), .on(), .add(html)
Safe examples
 .text(danger), .val(danger)
Some serious research needs to be done to identify all the safe vs. unsafe methods
 There are about 300 methods in jQuery
Source: http://code.google.com/p/domxsswiki/wiki/jQuery
Client Side Context Sensitive Output
Escaping
Context Escaping Scheme Example
HTML Element ( &, <, >, " )  &entity; ( ', / )
 &#xHH;
$ESAPI.encoder().
encodeForHTML()
HTML Attribute All non-alphanumeric
< 256  &#xHH
$ESAPI.encoder().
encodeForHTMLAttribute()
JavaScript All non-alphanumeric
< 256  xHH
$ESAPI.encoder().
encodeForJavaScript()
HTML Style All non-alphanumeric
< 256  HH
$ESAPI.encoder().
encodeForCSS()
URI Attribute All non-alphanumeric
< 256  %HH
$ESAPI.encoder().
encodeForURL()
Encoding methods built into a jquery-encoder:
https://github.com/chrisisbeef/jquery-encoder
JQuery Encoding with JQencoder
Contextual encoding is a crucial technique needed to stop all types of XSS
jqencoder is a jQuery plugin that allows developers to do contextual encoding in
JavaScript to stop DOM-based XSS
 http://plugins.jquery.com/plugin-tags/security
 $('#element').encode('html', UNTRUSTED-DATA);
Should you trust all JSON?
"user":
{
"name": "Jameson",
"occupation": "Distiller",
"location": (function() { alert("XSS 1!"); return "somewhere"})(),
"_location_comment": "Once parsed unsafely, the location XSS will
run automatically, as a self-executing function. JSON.parse can help with
this, and jQuery's $.parseJSON uses it by default (as do $.ajax, etc)",
"bio": "<script type='text/javascript'>alert('XSS!');</script>",
"_bio_comment": "This XSS will execute once it is added to the DOM,
if not properly escaped before adding it. This is more of a persistent kind
of XSS attack."
}
OWASP JSON Sanitizer Project
https://www.owasp.org/index.php/OWASP_JSON_Sanitizer
• Given JSON-like content, converts it to valid JSON.
• This can be attached at either end of a data-pipeline
to help satisfy Postel's principle: Be conservative in
what you do, be liberal in what you accept from
others.
• Applied to JSON-like content from others, it will
produce well-formed JSON that should satisfy any
parser you use.
• Applied to your output before you send, it will coerce
minor mistakes in encoding and make it easier to
embed your JSON in HTML and XML.
OWASP JSON Sanitizer Project
https://www.owasp.org/index.php/OWASP_JSON_Sanitizer
Server Side JSON Sanitization
The Problem
Web Page is vulnerable to XSS because of parsing of untrusted JSON incorrectly
The Solution
JSON Sanitizer can help with two use cases.
1) Sanitizing untrusted JSON on the server that is submitted from the browser in
standard AJAX communication
2) Sanitizing potentially untrusted JSON server-side before sending it to the browser.
The output is a valid Javascript expression, so can be parsed by Javascript's eval
or by JSON.parse.
Best Practice: Sandboxing
 Object.seal( obj )
 Object.isSealed( obj )
 Sealing an object prevents other
code from deleting, or changing the
descriptors of, any of the object's
properties
JavaScript Sandboxing
(ECMAScript 5)
iFrame Sandboxing (HTML5)
 <iframe
src="demo_iframe_sandbox.jsp"
sandbox=""></iframe>
 Allow-same-origin, allow-top-
navigation, allow-forms, allow-scripts
More Later in HTML 5 considerations
Best Practice: X-Xss-Protection
•Use the browser’s built in XSS Auditor
•X-Xss-Protection:
•[0-1] (mode=block)
•X-Xss-Protection:
•1; mode=block
Best Practice: Content Security Policy
Anti-XSS W3C standard
Must move all inline script and style into external scripts
Add the Content-Security-Policy response header to instruct the browser that CSP is in
use.
 The CSP standard and browser support is still emerging
 Do not depend on CSP yet
 True standard browser support is 1 years off
CSP 2.0 Working Draft Last Call published July 2014
 http://www.w3.org/TR/CSP2/
Best Practice: Content Security Policy
Externalize all
Java-Script
within web
pages
No inline script tag
No inline JavaScript for onclick, onblur or other inline
events handling
Push all JavaScript to formal .js files using event binding
Define
Content
Security Policy
Developers define which scripts/directories are valid
Browser will only execute supported scripts
Inline JavaScript code will be ignored
When should you apply CSP?
• It is a great ideas when building a new web application to apply CSP
from day 1.
• CSP should be on 100% of html endpoints.
• It is often non-trivial to apply CSP to an existing app, so start from
the beginning!
This is an unrealistic policy
default-src ‘self’; object-src ‘none’
XSS eliminated √
Flashed disabled √
Mixed content disallowed √
Third party content not allowed √
https://developer.mozilla.org/en-US/docs/Web/Security/CSP/CSP_policy_directives
The default-src directive defines the security policy for types of content which are not
expressly called out by more specific directives.
This is a common policy
default-src ‘self’;
img-src https://mycdn.com;
script-src ‘unsafe-inline’ https://mycdn.com;
style-src ‘unsafe-inline’ https://mycdn.com
object-src ‘none’;
XSS eliminated X
Flash disabled √
Mixed content disallowed √
Third party content not allowed √
This is a useless policy
default-src *;
script-src * ‘unsafe-inline’ ‘unsafe-eval’;
style-src * ‘unsafe-inline’;
XSS eliminated X
Flash disabled X
Mixed content disallowed X
Third party content not allowed X

More Related Content

What's hot

OWASP API Security Top 10 - API World
OWASP API Security Top 10 - API WorldOWASP API Security Top 10 - API World
OWASP API Security Top 10 - API World
42Crunch
 
Waf bypassing Techniques
Waf bypassing TechniquesWaf bypassing Techniques
Waf bypassing Techniques
Avinash Thapa
 
SQL Injection and Clickjacking Attack in Web security
SQL Injection and Clickjacking Attack in Web securitySQL Injection and Clickjacking Attack in Web security
SQL Injection and Clickjacking Attack in Web security
Moutasm Tamimi
 
Cross site scripting attacks and defenses
Cross site scripting attacks and defensesCross site scripting attacks and defenses
Cross site scripting attacks and defenses
Mohammed A. Imran
 
API Security Best Practices & Guidelines
API Security Best Practices & GuidelinesAPI Security Best Practices & Guidelines
API Security Best Practices & Guidelines
Prabath Siriwardena
 
The Cross Site Scripting Guide
The Cross Site Scripting GuideThe Cross Site Scripting Guide
The Cross Site Scripting Guide
Daisuke_Dan
 
Cross site scripting (xss) attacks issues and defense - by sandeep kumbhar
Cross site scripting (xss) attacks issues and defense - by sandeep kumbharCross site scripting (xss) attacks issues and defense - by sandeep kumbhar
Cross site scripting (xss) attacks issues and defense - by sandeep kumbhar
Sandeep Kumbhar
 
Cross Site Scripting ( XSS)
Cross Site Scripting ( XSS)Cross Site Scripting ( XSS)
Cross Site Scripting ( XSS)
Amit Tyagi
 
Secure coding-guidelines
Secure coding-guidelinesSecure coding-guidelines
Secure coding-guidelines
Trupti Shiralkar, CISSP
 
OWASP Top 10 API Security Risks
OWASP Top 10 API Security RisksOWASP Top 10 API Security Risks
OWASP Top 10 API Security Risks
IndusfacePvtLtd
 
Cross site scripting (xss)
Cross site scripting (xss)Cross site scripting (xss)
Cross site scripting (xss)
Manish Kumar
 
Vulnerabilities in modern web applications
Vulnerabilities in modern web applicationsVulnerabilities in modern web applications
Vulnerabilities in modern web applications
Niyas Nazar
 
CSRF, ClickJacking & Open Redirect
CSRF, ClickJacking & Open RedirectCSRF, ClickJacking & Open Redirect
CSRF, ClickJacking & Open Redirect
Blueinfy Solutions
 
Neat tricks to bypass CSRF-protection
Neat tricks to bypass CSRF-protectionNeat tricks to bypass CSRF-protection
Neat tricks to bypass CSRF-protection
Mikhail Egorov
 
Sql injection attack
Sql injection attackSql injection attack
Sql injection attack
RajKumar Rampelli
 
OWASP Top 10 Web Application Vulnerabilities
OWASP Top 10 Web Application VulnerabilitiesOWASP Top 10 Web Application Vulnerabilities
OWASP Top 10 Web Application Vulnerabilities
Software Guru
 
Cross Site Scripting: Prevention and Detection(XSS)
Cross Site Scripting: Prevention and Detection(XSS)Cross Site Scripting: Prevention and Detection(XSS)
Cross Site Scripting: Prevention and Detection(XSS)
Aman Singh
 
Insecure Java Deserialization
Insecure Java DeserializationInsecure Java Deserialization
Insecure Java Deserialization
Shiv Sahni
 
Cross Site Scripting Defense Presentation
Cross Site Scripting Defense Presentation Cross Site Scripting Defense Presentation
Cross Site Scripting Defense Presentation
Ikhade Maro Igbape
 
How to Prevent RFI and LFI Attacks
How to Prevent RFI and LFI AttacksHow to Prevent RFI and LFI Attacks
How to Prevent RFI and LFI Attacks
Imperva
 

What's hot (20)

OWASP API Security Top 10 - API World
OWASP API Security Top 10 - API WorldOWASP API Security Top 10 - API World
OWASP API Security Top 10 - API World
 
Waf bypassing Techniques
Waf bypassing TechniquesWaf bypassing Techniques
Waf bypassing Techniques
 
SQL Injection and Clickjacking Attack in Web security
SQL Injection and Clickjacking Attack in Web securitySQL Injection and Clickjacking Attack in Web security
SQL Injection and Clickjacking Attack in Web security
 
Cross site scripting attacks and defenses
Cross site scripting attacks and defensesCross site scripting attacks and defenses
Cross site scripting attacks and defenses
 
API Security Best Practices & Guidelines
API Security Best Practices & GuidelinesAPI Security Best Practices & Guidelines
API Security Best Practices & Guidelines
 
The Cross Site Scripting Guide
The Cross Site Scripting GuideThe Cross Site Scripting Guide
The Cross Site Scripting Guide
 
Cross site scripting (xss) attacks issues and defense - by sandeep kumbhar
Cross site scripting (xss) attacks issues and defense - by sandeep kumbharCross site scripting (xss) attacks issues and defense - by sandeep kumbhar
Cross site scripting (xss) attacks issues and defense - by sandeep kumbhar
 
Cross Site Scripting ( XSS)
Cross Site Scripting ( XSS)Cross Site Scripting ( XSS)
Cross Site Scripting ( XSS)
 
Secure coding-guidelines
Secure coding-guidelinesSecure coding-guidelines
Secure coding-guidelines
 
OWASP Top 10 API Security Risks
OWASP Top 10 API Security RisksOWASP Top 10 API Security Risks
OWASP Top 10 API Security Risks
 
Cross site scripting (xss)
Cross site scripting (xss)Cross site scripting (xss)
Cross site scripting (xss)
 
Vulnerabilities in modern web applications
Vulnerabilities in modern web applicationsVulnerabilities in modern web applications
Vulnerabilities in modern web applications
 
CSRF, ClickJacking & Open Redirect
CSRF, ClickJacking & Open RedirectCSRF, ClickJacking & Open Redirect
CSRF, ClickJacking & Open Redirect
 
Neat tricks to bypass CSRF-protection
Neat tricks to bypass CSRF-protectionNeat tricks to bypass CSRF-protection
Neat tricks to bypass CSRF-protection
 
Sql injection attack
Sql injection attackSql injection attack
Sql injection attack
 
OWASP Top 10 Web Application Vulnerabilities
OWASP Top 10 Web Application VulnerabilitiesOWASP Top 10 Web Application Vulnerabilities
OWASP Top 10 Web Application Vulnerabilities
 
Cross Site Scripting: Prevention and Detection(XSS)
Cross Site Scripting: Prevention and Detection(XSS)Cross Site Scripting: Prevention and Detection(XSS)
Cross Site Scripting: Prevention and Detection(XSS)
 
Insecure Java Deserialization
Insecure Java DeserializationInsecure Java Deserialization
Insecure Java Deserialization
 
Cross Site Scripting Defense Presentation
Cross Site Scripting Defense Presentation Cross Site Scripting Defense Presentation
Cross Site Scripting Defense Presentation
 
How to Prevent RFI and LFI Attacks
How to Prevent RFI and LFI AttacksHow to Prevent RFI and LFI Attacks
How to Prevent RFI and LFI Attacks
 

Similar to 04. xss and encoding

XSS Primer - Noob to Pro in 1 hour
XSS Primer - Noob to Pro in 1 hourXSS Primer - Noob to Pro in 1 hour
XSS Primer - Noob to Pro in 1 hour
snoopythesecuritydog
 
Owasp Top 10 - Owasp Pune Chapter - January 2008
Owasp Top 10 - Owasp Pune Chapter - January 2008Owasp Top 10 - Owasp Pune Chapter - January 2008
Owasp Top 10 - Owasp Pune Chapter - January 2008
abhijitapatil
 
Intro to Web Application Security
Intro to Web Application SecurityIntro to Web Application Security
Intro to Web Application Security
Rob Ragan
 
Session7-XSS & CSRF
Session7-XSS & CSRFSession7-XSS & CSRF
Session7-XSS & CSRF
zakieh alizadeh
 
xss-100908063522-phpapp02.pdf
xss-100908063522-phpapp02.pdfxss-100908063522-phpapp02.pdf
xss-100908063522-phpapp02.pdf
yashvirsingh48
 
Understanding dom based xss
Understanding dom based xssUnderstanding dom based xss
Understanding dom based xss
Potato
 
Attackers Vs Programmers
Attackers Vs ProgrammersAttackers Vs Programmers
Attackers Vs Programmers
robin_bene
 
Securing Java EE Web Apps
Securing Java EE Web AppsSecuring Java EE Web Apps
Securing Java EE Web Apps
Frank Kim
 
Web application attacks
Web application attacksWeb application attacks
Web application attacks
hruth
 
Complete xss walkthrough
Complete xss walkthroughComplete xss walkthrough
Complete xss walkthrough
Ahmed Elhady Mohamed
 
4.Xss
4.Xss4.Xss
4.Xss
phanleson
 
Introduction to Cross Site Scripting ( XSS )
Introduction to Cross Site Scripting ( XSS )Introduction to Cross Site Scripting ( XSS )
Introduction to Cross Site Scripting ( XSS )
Irfad Imtiaz
 
Security Tech Talk
Security Tech TalkSecurity Tech Talk
Security Tech Talk
Mallikarjun Reddy
 
Rich Web App Security - Keeping your application safe
Rich Web App Security - Keeping your application safeRich Web App Security - Keeping your application safe
Rich Web App Security - Keeping your application safe
Jeremiah Grossman
 
Web 2.0 Application Kung-Fu - Securing Ajax & Web Services
Web 2.0 Application Kung-Fu - Securing Ajax & Web ServicesWeb 2.0 Application Kung-Fu - Securing Ajax & Web Services
Web 2.0 Application Kung-Fu - Securing Ajax & Web Services
Shreeraj Shah
 
Application Security
Application SecurityApplication Security
Application Security
nirola
 
API SECURITY
API SECURITYAPI SECURITY
Manindra kishore _incident_handling_n_log_analysis - ClubHack2009
Manindra kishore _incident_handling_n_log_analysis - ClubHack2009Manindra kishore _incident_handling_n_log_analysis - ClubHack2009
Manindra kishore _incident_handling_n_log_analysis - ClubHack2009
ClubHack
 
XSS
XSSXSS
Top 10 Security Vulnerabilities (2006)
Top 10 Security Vulnerabilities (2006)Top 10 Security Vulnerabilities (2006)
Top 10 Security Vulnerabilities (2006)
Susam Pal
 

Similar to 04. xss and encoding (20)

XSS Primer - Noob to Pro in 1 hour
XSS Primer - Noob to Pro in 1 hourXSS Primer - Noob to Pro in 1 hour
XSS Primer - Noob to Pro in 1 hour
 
Owasp Top 10 - Owasp Pune Chapter - January 2008
Owasp Top 10 - Owasp Pune Chapter - January 2008Owasp Top 10 - Owasp Pune Chapter - January 2008
Owasp Top 10 - Owasp Pune Chapter - January 2008
 
Intro to Web Application Security
Intro to Web Application SecurityIntro to Web Application Security
Intro to Web Application Security
 
Session7-XSS & CSRF
Session7-XSS & CSRFSession7-XSS & CSRF
Session7-XSS & CSRF
 
xss-100908063522-phpapp02.pdf
xss-100908063522-phpapp02.pdfxss-100908063522-phpapp02.pdf
xss-100908063522-phpapp02.pdf
 
Understanding dom based xss
Understanding dom based xssUnderstanding dom based xss
Understanding dom based xss
 
Attackers Vs Programmers
Attackers Vs ProgrammersAttackers Vs Programmers
Attackers Vs Programmers
 
Securing Java EE Web Apps
Securing Java EE Web AppsSecuring Java EE Web Apps
Securing Java EE Web Apps
 
Web application attacks
Web application attacksWeb application attacks
Web application attacks
 
Complete xss walkthrough
Complete xss walkthroughComplete xss walkthrough
Complete xss walkthrough
 
4.Xss
4.Xss4.Xss
4.Xss
 
Introduction to Cross Site Scripting ( XSS )
Introduction to Cross Site Scripting ( XSS )Introduction to Cross Site Scripting ( XSS )
Introduction to Cross Site Scripting ( XSS )
 
Security Tech Talk
Security Tech TalkSecurity Tech Talk
Security Tech Talk
 
Rich Web App Security - Keeping your application safe
Rich Web App Security - Keeping your application safeRich Web App Security - Keeping your application safe
Rich Web App Security - Keeping your application safe
 
Web 2.0 Application Kung-Fu - Securing Ajax & Web Services
Web 2.0 Application Kung-Fu - Securing Ajax & Web ServicesWeb 2.0 Application Kung-Fu - Securing Ajax & Web Services
Web 2.0 Application Kung-Fu - Securing Ajax & Web Services
 
Application Security
Application SecurityApplication Security
Application Security
 
API SECURITY
API SECURITYAPI SECURITY
API SECURITY
 
Manindra kishore _incident_handling_n_log_analysis - ClubHack2009
Manindra kishore _incident_handling_n_log_analysis - ClubHack2009Manindra kishore _incident_handling_n_log_analysis - ClubHack2009
Manindra kishore _incident_handling_n_log_analysis - ClubHack2009
 
XSS
XSSXSS
XSS
 
Top 10 Security Vulnerabilities (2006)
Top 10 Security Vulnerabilities (2006)Top 10 Security Vulnerabilities (2006)
Top 10 Security Vulnerabilities (2006)
 

More from Eoin Keary

IISF-March2023.pptx
IISF-March2023.pptxIISF-March2023.pptx
IISF-March2023.pptx
Eoin Keary
 
Validation of vulnerabilities.pdf
Validation of vulnerabilities.pdfValidation of vulnerabilities.pdf
Validation of vulnerabilities.pdf
Eoin Keary
 
Does a Hybrid model for vulnerability Management Make Sense.pdf
Does a Hybrid model for vulnerability Management Make Sense.pdfDoes a Hybrid model for vulnerability Management Make Sense.pdf
Does a Hybrid model for vulnerability Management Make Sense.pdf
Eoin Keary
 
Edgescan 2022 Vulnerability Statistics Report
Edgescan 2022 Vulnerability Statistics ReportEdgescan 2022 Vulnerability Statistics Report
Edgescan 2022 Vulnerability Statistics Report
Eoin Keary
 
Edgescan 2021 Vulnerability Stats Report
Edgescan 2021 Vulnerability Stats ReportEdgescan 2021 Vulnerability Stats Report
Edgescan 2021 Vulnerability Stats Report
Eoin Keary
 
One login enemy at the gates
One login enemy at the gatesOne login enemy at the gates
One login enemy at the gates
Eoin Keary
 
Edgescan vulnerability stats report 2020
Edgescan vulnerability stats report 2020Edgescan vulnerability stats report 2020
Edgescan vulnerability stats report 2020
Eoin Keary
 
edgescan vulnerability stats report (2018)
 edgescan vulnerability stats report (2018)  edgescan vulnerability stats report (2018)
edgescan vulnerability stats report (2018)
Eoin Keary
 
edgescan vulnerability stats report (2019)
edgescan vulnerability stats report (2019) edgescan vulnerability stats report (2019)
edgescan vulnerability stats report (2019)
Eoin Keary
 
Full stack vulnerability management at scale
Full stack vulnerability management at scaleFull stack vulnerability management at scale
Full stack vulnerability management at scale
Eoin Keary
 
Vulnerability Intelligence - Standing Still in a world full of change
Vulnerability Intelligence - Standing Still in a world full of changeVulnerability Intelligence - Standing Still in a world full of change
Vulnerability Intelligence - Standing Still in a world full of change
Eoin Keary
 
Edgescan vulnerability stats report 2019 - h-isac-2-2-2019
Edgescan   vulnerability stats report 2019 - h-isac-2-2-2019Edgescan   vulnerability stats report 2019 - h-isac-2-2-2019
Edgescan vulnerability stats report 2019 - h-isac-2-2-2019
Eoin Keary
 
Hide and seek - Attack Surface Management and continuous assessment.
Hide and seek - Attack Surface Management and continuous assessment.Hide and seek - Attack Surface Management and continuous assessment.
Hide and seek - Attack Surface Management and continuous assessment.
Eoin Keary
 
Online Gaming Cyber security and Threat Model
Online Gaming Cyber security and Threat ModelOnline Gaming Cyber security and Threat Model
Online Gaming Cyber security and Threat Model
Eoin Keary
 
Keeping the wolf from 1000 doors.
Keeping the wolf from 1000 doors.Keeping the wolf from 1000 doors.
Keeping the wolf from 1000 doors.
Eoin Keary
 
Security by the numbers
Security by the numbersSecurity by the numbers
Security by the numbers
Eoin Keary
 
Web security – everything we know is wrong cloud version
Web security – everything we know is wrong   cloud versionWeb security – everything we know is wrong   cloud version
Web security – everything we know is wrong cloud version
Eoin Keary
 
Cybersecurity by the numbers
Cybersecurity by the numbersCybersecurity by the numbers
Cybersecurity by the numbers
Eoin Keary
 
Ebu class edgescan-2017
Ebu class edgescan-2017Ebu class edgescan-2017
Ebu class edgescan-2017
Eoin Keary
 
Vulnerability management and threat detection by the numbers
Vulnerability management and threat detection by the numbersVulnerability management and threat detection by the numbers
Vulnerability management and threat detection by the numbers
Eoin Keary
 

More from Eoin Keary (20)

IISF-March2023.pptx
IISF-March2023.pptxIISF-March2023.pptx
IISF-March2023.pptx
 
Validation of vulnerabilities.pdf
Validation of vulnerabilities.pdfValidation of vulnerabilities.pdf
Validation of vulnerabilities.pdf
 
Does a Hybrid model for vulnerability Management Make Sense.pdf
Does a Hybrid model for vulnerability Management Make Sense.pdfDoes a Hybrid model for vulnerability Management Make Sense.pdf
Does a Hybrid model for vulnerability Management Make Sense.pdf
 
Edgescan 2022 Vulnerability Statistics Report
Edgescan 2022 Vulnerability Statistics ReportEdgescan 2022 Vulnerability Statistics Report
Edgescan 2022 Vulnerability Statistics Report
 
Edgescan 2021 Vulnerability Stats Report
Edgescan 2021 Vulnerability Stats ReportEdgescan 2021 Vulnerability Stats Report
Edgescan 2021 Vulnerability Stats Report
 
One login enemy at the gates
One login enemy at the gatesOne login enemy at the gates
One login enemy at the gates
 
Edgescan vulnerability stats report 2020
Edgescan vulnerability stats report 2020Edgescan vulnerability stats report 2020
Edgescan vulnerability stats report 2020
 
edgescan vulnerability stats report (2018)
 edgescan vulnerability stats report (2018)  edgescan vulnerability stats report (2018)
edgescan vulnerability stats report (2018)
 
edgescan vulnerability stats report (2019)
edgescan vulnerability stats report (2019) edgescan vulnerability stats report (2019)
edgescan vulnerability stats report (2019)
 
Full stack vulnerability management at scale
Full stack vulnerability management at scaleFull stack vulnerability management at scale
Full stack vulnerability management at scale
 
Vulnerability Intelligence - Standing Still in a world full of change
Vulnerability Intelligence - Standing Still in a world full of changeVulnerability Intelligence - Standing Still in a world full of change
Vulnerability Intelligence - Standing Still in a world full of change
 
Edgescan vulnerability stats report 2019 - h-isac-2-2-2019
Edgescan   vulnerability stats report 2019 - h-isac-2-2-2019Edgescan   vulnerability stats report 2019 - h-isac-2-2-2019
Edgescan vulnerability stats report 2019 - h-isac-2-2-2019
 
Hide and seek - Attack Surface Management and continuous assessment.
Hide and seek - Attack Surface Management and continuous assessment.Hide and seek - Attack Surface Management and continuous assessment.
Hide and seek - Attack Surface Management and continuous assessment.
 
Online Gaming Cyber security and Threat Model
Online Gaming Cyber security and Threat ModelOnline Gaming Cyber security and Threat Model
Online Gaming Cyber security and Threat Model
 
Keeping the wolf from 1000 doors.
Keeping the wolf from 1000 doors.Keeping the wolf from 1000 doors.
Keeping the wolf from 1000 doors.
 
Security by the numbers
Security by the numbersSecurity by the numbers
Security by the numbers
 
Web security – everything we know is wrong cloud version
Web security – everything we know is wrong   cloud versionWeb security – everything we know is wrong   cloud version
Web security – everything we know is wrong cloud version
 
Cybersecurity by the numbers
Cybersecurity by the numbersCybersecurity by the numbers
Cybersecurity by the numbers
 
Ebu class edgescan-2017
Ebu class edgescan-2017Ebu class edgescan-2017
Ebu class edgescan-2017
 
Vulnerability management and threat detection by the numbers
Vulnerability management and threat detection by the numbersVulnerability management and threat detection by the numbers
Vulnerability management and threat detection by the numbers
 

Recently uploaded

Search Result Showing My Post is Now Buried
Search Result Showing My Post is Now BuriedSearch Result Showing My Post is Now Buried
Search Result Showing My Post is Now Buried
Trish Parr
 
办理毕业证(UPenn毕业证)宾夕法尼亚大学毕业证成绩单快速办理
办理毕业证(UPenn毕业证)宾夕法尼亚大学毕业证成绩单快速办理办理毕业证(UPenn毕业证)宾夕法尼亚大学毕业证成绩单快速办理
办理毕业证(UPenn毕业证)宾夕法尼亚大学毕业证成绩单快速办理
uehowe
 
成绩单ps(UST毕业证)圣托马斯大学毕业证成绩单快速办理
成绩单ps(UST毕业证)圣托马斯大学毕业证成绩单快速办理成绩单ps(UST毕业证)圣托马斯大学毕业证成绩单快速办理
成绩单ps(UST毕业证)圣托马斯大学毕业证成绩单快速办理
ysasp1
 
manuaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaal
manuaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaalmanuaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaal
manuaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaal
wolfsoftcompanyco
 
重新申请毕业证书(RMIT毕业证)皇家墨尔本理工大学毕业证成绩单精仿办理
重新申请毕业证书(RMIT毕业证)皇家墨尔本理工大学毕业证成绩单精仿办理重新申请毕业证书(RMIT毕业证)皇家墨尔本理工大学毕业证成绩单精仿办理
重新申请毕业证书(RMIT毕业证)皇家墨尔本理工大学毕业证成绩单精仿办理
vmemo1
 
学位认证网(DU毕业证)迪肯大学毕业证成绩单一比一原版制作
学位认证网(DU毕业证)迪肯大学毕业证成绩单一比一原版制作学位认证网(DU毕业证)迪肯大学毕业证成绩单一比一原版制作
学位认证网(DU毕业证)迪肯大学毕业证成绩单一比一原版制作
zyfovom
 
Meet up Milano 14 _ Axpo Italia_ Migration from Mule3 (On-prem) to.pdf
Meet up Milano 14 _ Axpo Italia_ Migration from Mule3 (On-prem) to.pdfMeet up Milano 14 _ Axpo Italia_ Migration from Mule3 (On-prem) to.pdf
Meet up Milano 14 _ Axpo Italia_ Migration from Mule3 (On-prem) to.pdf
Florence Consulting
 
不能毕业如何获得(USYD毕业证)悉尼大学毕业证成绩单一比一原版制作
不能毕业如何获得(USYD毕业证)悉尼大学毕业证成绩单一比一原版制作不能毕业如何获得(USYD毕业证)悉尼大学毕业证成绩单一比一原版制作
不能毕业如何获得(USYD毕业证)悉尼大学毕业证成绩单一比一原版制作
bseovas
 
国外证书(Lincoln毕业证)新西兰林肯大学毕业证成绩单不能毕业办理
国外证书(Lincoln毕业证)新西兰林肯大学毕业证成绩单不能毕业办理国外证书(Lincoln毕业证)新西兰林肯大学毕业证成绩单不能毕业办理
国外证书(Lincoln毕业证)新西兰林肯大学毕业证成绩单不能毕业办理
zoowe
 
一比一原版(SLU毕业证)圣路易斯大学毕业证成绩单专业办理
一比一原版(SLU毕业证)圣路易斯大学毕业证成绩单专业办理一比一原版(SLU毕业证)圣路易斯大学毕业证成绩单专业办理
一比一原版(SLU毕业证)圣路易斯大学毕业证成绩单专业办理
keoku
 
Gen Z and the marketplaces - let's translate their needs
Gen Z and the marketplaces - let's translate their needsGen Z and the marketplaces - let's translate their needs
Gen Z and the marketplaces - let's translate their needs
Laura Szabó
 
Discover the benefits of outsourcing SEO to India
Discover the benefits of outsourcing SEO to IndiaDiscover the benefits of outsourcing SEO to India
Discover the benefits of outsourcing SEO to India
davidjhones387
 
Should Repositories Participate in the Fediverse?
Should Repositories Participate in the Fediverse?Should Repositories Participate in the Fediverse?
Should Repositories Participate in the Fediverse?
Paul Walk
 
假文凭国外(Adelaide毕业证)澳大利亚国立大学毕业证成绩单办理
假文凭国外(Adelaide毕业证)澳大利亚国立大学毕业证成绩单办理假文凭国外(Adelaide毕业证)澳大利亚国立大学毕业证成绩单办理
假文凭国外(Adelaide毕业证)澳大利亚国立大学毕业证成绩单办理
cuobya
 
Explore-Insanony: Watch Instagram Stories Secretly
Explore-Insanony: Watch Instagram Stories SecretlyExplore-Insanony: Watch Instagram Stories Secretly
Explore-Insanony: Watch Instagram Stories Secretly
Trending Blogers
 
Ready to Unlock the Power of Blockchain!
Ready to Unlock the Power of Blockchain!Ready to Unlock the Power of Blockchain!
Ready to Unlock the Power of Blockchain!
Toptal Tech
 
制作原版1:1(Monash毕业证)莫纳什大学毕业证成绩单办理假
制作原版1:1(Monash毕业证)莫纳什大学毕业证成绩单办理假制作原版1:1(Monash毕业证)莫纳什大学毕业证成绩单办理假
制作原版1:1(Monash毕业证)莫纳什大学毕业证成绩单办理假
ukwwuq
 
留学学历(UoA毕业证)奥克兰大学毕业证成绩单官方原版办理
留学学历(UoA毕业证)奥克兰大学毕业证成绩单官方原版办理留学学历(UoA毕业证)奥克兰大学毕业证成绩单官方原版办理
留学学历(UoA毕业证)奥克兰大学毕业证成绩单官方原版办理
bseovas
 
存档可查的(USC毕业证)南加利福尼亚大学毕业证成绩单制做办理
存档可查的(USC毕业证)南加利福尼亚大学毕业证成绩单制做办理存档可查的(USC毕业证)南加利福尼亚大学毕业证成绩单制做办理
存档可查的(USC毕业证)南加利福尼亚大学毕业证成绩单制做办理
fovkoyb
 
一比一原版(LBS毕业证)伦敦商学院毕业证成绩单专业办理
一比一原版(LBS毕业证)伦敦商学院毕业证成绩单专业办理一比一原版(LBS毕业证)伦敦商学院毕业证成绩单专业办理
一比一原版(LBS毕业证)伦敦商学院毕业证成绩单专业办理
eutxy
 

Recently uploaded (20)

Search Result Showing My Post is Now Buried
Search Result Showing My Post is Now BuriedSearch Result Showing My Post is Now Buried
Search Result Showing My Post is Now Buried
 
办理毕业证(UPenn毕业证)宾夕法尼亚大学毕业证成绩单快速办理
办理毕业证(UPenn毕业证)宾夕法尼亚大学毕业证成绩单快速办理办理毕业证(UPenn毕业证)宾夕法尼亚大学毕业证成绩单快速办理
办理毕业证(UPenn毕业证)宾夕法尼亚大学毕业证成绩单快速办理
 
成绩单ps(UST毕业证)圣托马斯大学毕业证成绩单快速办理
成绩单ps(UST毕业证)圣托马斯大学毕业证成绩单快速办理成绩单ps(UST毕业证)圣托马斯大学毕业证成绩单快速办理
成绩单ps(UST毕业证)圣托马斯大学毕业证成绩单快速办理
 
manuaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaal
manuaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaalmanuaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaal
manuaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaal
 
重新申请毕业证书(RMIT毕业证)皇家墨尔本理工大学毕业证成绩单精仿办理
重新申请毕业证书(RMIT毕业证)皇家墨尔本理工大学毕业证成绩单精仿办理重新申请毕业证书(RMIT毕业证)皇家墨尔本理工大学毕业证成绩单精仿办理
重新申请毕业证书(RMIT毕业证)皇家墨尔本理工大学毕业证成绩单精仿办理
 
学位认证网(DU毕业证)迪肯大学毕业证成绩单一比一原版制作
学位认证网(DU毕业证)迪肯大学毕业证成绩单一比一原版制作学位认证网(DU毕业证)迪肯大学毕业证成绩单一比一原版制作
学位认证网(DU毕业证)迪肯大学毕业证成绩单一比一原版制作
 
Meet up Milano 14 _ Axpo Italia_ Migration from Mule3 (On-prem) to.pdf
Meet up Milano 14 _ Axpo Italia_ Migration from Mule3 (On-prem) to.pdfMeet up Milano 14 _ Axpo Italia_ Migration from Mule3 (On-prem) to.pdf
Meet up Milano 14 _ Axpo Italia_ Migration from Mule3 (On-prem) to.pdf
 
不能毕业如何获得(USYD毕业证)悉尼大学毕业证成绩单一比一原版制作
不能毕业如何获得(USYD毕业证)悉尼大学毕业证成绩单一比一原版制作不能毕业如何获得(USYD毕业证)悉尼大学毕业证成绩单一比一原版制作
不能毕业如何获得(USYD毕业证)悉尼大学毕业证成绩单一比一原版制作
 
国外证书(Lincoln毕业证)新西兰林肯大学毕业证成绩单不能毕业办理
国外证书(Lincoln毕业证)新西兰林肯大学毕业证成绩单不能毕业办理国外证书(Lincoln毕业证)新西兰林肯大学毕业证成绩单不能毕业办理
国外证书(Lincoln毕业证)新西兰林肯大学毕业证成绩单不能毕业办理
 
一比一原版(SLU毕业证)圣路易斯大学毕业证成绩单专业办理
一比一原版(SLU毕业证)圣路易斯大学毕业证成绩单专业办理一比一原版(SLU毕业证)圣路易斯大学毕业证成绩单专业办理
一比一原版(SLU毕业证)圣路易斯大学毕业证成绩单专业办理
 
Gen Z and the marketplaces - let's translate their needs
Gen Z and the marketplaces - let's translate their needsGen Z and the marketplaces - let's translate their needs
Gen Z and the marketplaces - let's translate their needs
 
Discover the benefits of outsourcing SEO to India
Discover the benefits of outsourcing SEO to IndiaDiscover the benefits of outsourcing SEO to India
Discover the benefits of outsourcing SEO to India
 
Should Repositories Participate in the Fediverse?
Should Repositories Participate in the Fediverse?Should Repositories Participate in the Fediverse?
Should Repositories Participate in the Fediverse?
 
假文凭国外(Adelaide毕业证)澳大利亚国立大学毕业证成绩单办理
假文凭国外(Adelaide毕业证)澳大利亚国立大学毕业证成绩单办理假文凭国外(Adelaide毕业证)澳大利亚国立大学毕业证成绩单办理
假文凭国外(Adelaide毕业证)澳大利亚国立大学毕业证成绩单办理
 
Explore-Insanony: Watch Instagram Stories Secretly
Explore-Insanony: Watch Instagram Stories SecretlyExplore-Insanony: Watch Instagram Stories Secretly
Explore-Insanony: Watch Instagram Stories Secretly
 
Ready to Unlock the Power of Blockchain!
Ready to Unlock the Power of Blockchain!Ready to Unlock the Power of Blockchain!
Ready to Unlock the Power of Blockchain!
 
制作原版1:1(Monash毕业证)莫纳什大学毕业证成绩单办理假
制作原版1:1(Monash毕业证)莫纳什大学毕业证成绩单办理假制作原版1:1(Monash毕业证)莫纳什大学毕业证成绩单办理假
制作原版1:1(Monash毕业证)莫纳什大学毕业证成绩单办理假
 
留学学历(UoA毕业证)奥克兰大学毕业证成绩单官方原版办理
留学学历(UoA毕业证)奥克兰大学毕业证成绩单官方原版办理留学学历(UoA毕业证)奥克兰大学毕业证成绩单官方原版办理
留学学历(UoA毕业证)奥克兰大学毕业证成绩单官方原版办理
 
存档可查的(USC毕业证)南加利福尼亚大学毕业证成绩单制做办理
存档可查的(USC毕业证)南加利福尼亚大学毕业证成绩单制做办理存档可查的(USC毕业证)南加利福尼亚大学毕业证成绩单制做办理
存档可查的(USC毕业证)南加利福尼亚大学毕业证成绩单制做办理
 
一比一原版(LBS毕业证)伦敦商学院毕业证成绩单专业办理
一比一原版(LBS毕业证)伦敦商学院毕业证成绩单专业办理一比一原版(LBS毕业证)伦敦商学院毕业证成绩单专业办理
一比一原版(LBS毕业证)伦敦商学院毕业证成绩单专业办理
 

04. xss and encoding

  • 1. XSS Attack & Defense Eoin Keary CTO BCC Risk Advisory www.bccriskadvisory.com www.edgescan.com @eoinkeary
  • 2. What is XSS? Attacker driven JavaScript or JavaScript Injection Most common web vulnerability Easy vulnerability to find via auditing Easy vulnerability to exploit Certain types of XSS are very complex to fix Significant business and technical impact potential
  • 3. XSS Attack Payload Types Session hijacking Site defacement Network scanning Undermining CSRF defenses Site redirection/phishing Data theft Keystroke logging Loading of remotely hosted scripts
  • 4. Input Example Consider the following URL : www.example.com/saveComment?comment=Great+Site! How can an attacker misuse this?
  • 5. XSS Variants Data provided by a client is immediately used by server-side scripts to generate a page of results for that user. Search engines Reflected/ Transient A page's client-side script itself accesses a URL request parameter and uses this information to dynamically write some HTML to its own page DOM XSS is triggered when a victim interacts with a web page directly without causing the page to reload. Difficult to test with scanners and proxy tools – why? DOM based XSS Data provided by a client is first stored persistently on the server (e.g., in a database, filesystem), and later displayed to users Bulletin Boards, Forums, Blog Comments Stored/ Persistent
  • 6. Reflected XSS 1. Hacker sends link to victim. Link contains XSS payload 2. Victim views page via XSS link supplied by attacker. 3. XSS code executes on victims browser and sends cookie to evil server 4. Cookie is stolen. The Attacker can hijack the Victims session. Victim Hackler
  • 7. Reflected XSS Code Sample //Search.aspx.cs public partial class _Default : System.Web.UI.Page { Label lblResults; protected void Page_Load(object sender, EventArgs e) { //... doSearch(); this.lblResults.Text = "You Searched For " + Request.QueryString["query"]; } OK: http://app.com/Search.aspx?query=soccer NOT OK: http://app.com/Search.aspx?query=<script>...</script>
  • 9. Persistent/Stored XSS Code Sample <% int id = Integer.parseInt(request.getParameter("id")); String query = "select * from forum where id=" + id; Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(query); if (rs != null) { rs.next (); String comment = rs.getString ("comment"); %> User Comment : <%= comment %> <% } %>
  • 12. Test for Cross-Site Scripting Make note of all pages that display input originating from current or other users Test by inserting malicious script or characters to see if they are ultimately displayed back to the user Very easy to discover XSS via dynamic testing More difficult to discover via code review Examine code to ensure that application data is HTML encoded before being rendered to users
  • 13. Test for Cross-Site Scripting Remember the three common types of attacks: Input parameters that are rendered directly back to the user Server-Side Client-Side Input that is rendered within other pages Hidden fields are commonly vulnerable to this exploit as there is a perception that hidden fields are read-only Error messages that redisplay user input
  • 14. Test for Cross-Site Scripting Each input should be tested to see if data gets rendered back to the user. Break out of another tag by inserting "> before the malicious script Bypass <script> "tag-hunting" filters May not require tags if the input is inserted into an existing JavaScript routine <- DOM XSS <IMG SRC="javascript:alert(document.cookie)"> <p style="left:expression(eval('alert(document.cookie)'))"> u003Cscriptu003E <SCRIPT> <%= userdata %> </SCRIPT>
  • 15. Why won't these strategies work? Danger: XSS Weak Defense Used Getting rid of XSS is a difficult task Eliminate <, >, &, ", ' characters? Eliminate all special characters? Disallow user input? (not possible) Global filter? How can we prevent XSS in our web application
  • 16. XSS Defense: The Solution? Depends on the type of user input  HTML, Strings, Uploaded Files Depends on where user input is displayed in an HTML document  HTML Body  HTML Attribute  JavaScript Variable Assignment Several defensive techniques needed depending on context  Input Validation (raw HTML input)  Output Encoding (Strings)  Sandboxing (3rd party JavaScript like ads)
  • 17. Other 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.introducti on.html • Java (Updated February 2014) • 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/ • Reform Project • .NET v1/v2, Classic ASP, Python, Perl, JavaScript • https://www.owasp.org/index.php/Category:OWASP_Encoding_Project
  • 18.
  • 19. &lt;
  • 20. HTML Entity Encoding: The Big 6 1. & &amp; 2. < &lt; 3. > &gt; 4. " &quot; 5. ' &#x27; 6. / &#x2F;
  • 21. Output Encoding Code Sample StringBuffer buff = new StringBuffer(); if ( value == null ) { return null; } for(int i=0; i<value.length(); i++) { char ch = value.charAt(i); if ( ch == '&' ) { buff.append("&amp;"); } else if ( ch == '<') { buff.append("&lt;"); } else if ( ch == '>') { buff.append("&gt;"); } else if ( Character.isWhitespace(ch ) ) { buff.append(ch); } else if ( Character.isLetterOrDigit(ch) ) { buff.append(ch); } else if ( Integer.valueOf(ch).intValue() >= 20 && Integer.valueOf(ch).intValue() <= 126 ) { buff.append( "&#" + (int)ch + ";" ); } } return buff.toString(); Simple HTML encoding method for HTML context
  • 22. 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 (macher.maches()) { out.println("Your email address is: " + Encoder.HtmlEncode(email)); } else { //log & throw a specific validation exception and fail safely }
  • 23. Danger: Multiple Contexts HTML Body HTML Attributes <STYLE> Context <SCRIPT> Context URL Context Different encoding and validation techniques needed for different contexts!
  • 24. HTML Encoding: Certain sets of characters mean something special in HTML. For instance ‘<’ is used to open and HTML tag and ‘&’ is used to and the beginning of a sequence of characters to define special symbols like the copy write symbol. (htmlentities in PHP) HttpUtility.HtmlEncode(“<script>alert(‘&’);</script>”) &lt;script&gt;alert(&#39;&amp;&#39;);&lt;/script&gt; Attribute Encoding: Attribute encoding replaces three characters that are not valid to use inside attribute values in HTML. Those characters are ampersand ‘&’, less-than ‘<’, and quotation marks ‘”’ HttpUtility.HtmlAttributeEncode(“<script>alert(”&”);</script>”) &lt;script>alert(&quot;&amp;&quot;);&lt;/script> URL Encoding URL encoding used when you have some data that you would like to pass in the URL and that data contains some reserved or invalid characters (&/<space>) – (urlencode() in php) HttpUtility.UrlEncode(“Some Special Information / That needs to be in the URL”) Some+Special+Information+%2f+That+needs+to+be+in+the+URL OR Some%20Special%20Information%20%2f%20That%20needs%20to%20be%20in%20t he%20URL
  • 25. XSS Defense by Data Type and Context Data Type Context Defense String HTML Body/Attribute HTML Entity Encode/HTML Attribute Encoder String Java String Java String Encoding String JavaScript Variable JavaScript Hex Encoding String GET Parameter URL Encoding String Untrusted URL URL Validation, avoid javascript: URL’s, Attribute encoding, safe URL verification String CSS Value Strict structural validation, CSS Hex encoding, good design HTML HTML Body HTML Validation (JSoup, AntiSamy, HTML Sanitizer) Any DOM DOM XSS Cheat sheet Untrusted JavaScript Any Sandboxing JSON Client parse time JSON.parse() or json2.js Safe HTML Attributes include: align, alink, alt, bgcolor, border, cellpadding, cellspacing, class, color, cols, colspan, coords, dir, face, height, hspace, ismap, lang, marginheight, marginwidth, multiple, nohref, noresize, noshade, nowrap, ref, rel, rev, rows, rowspan, scrolling, shape, span, summary, tabindex, title, usemap, valign, value, vlink, vspace, width
  • 26. XSS Defense by Data Type and Context Context Encoding OWASP Java Encoder HTML Body HTML Entity Encode Encoder.forHtmlContent HTML Attribute HTML Entity Encode Encoder.forHtmlAttribute Java String Java String Encoding Encoder.forJava JavaScript Variable JavaScript Hex Encoding Encoder.forJavaScript Encoder.forJavaScriptBlock Encoder.forJavaScriptAttribute GET Parameter URL Encoding Encoder.forUriComponent Untrusted URL URL Validation, avoid javascript: URL’s, attribute encoding, safe URL verification Encoder.forUri CSS Value Strict structural validation, CSS Hex encoding, good design Encoder.forCssString Encoder.forCssUrl
  • 27. OWASP Java Encoder Project https://www.owasp.org/index.php/OWASP_Java_Encoder_Project • No third party libraries or configuration necessary. • This code was designed for high-availability/high- performance encoding functionality. Redesigned for performance. • Simple drop-in encoding functionality • More complete API (uri and uri component encoding, etc) in some regards. • This is a Java 1.5 project. • Last updated February 4, 2014 (version 1.1.1)
  • 28. The Problem Web Page built in Java JSP is vulnerable to XSS The Solution <%-- Basic HTML Context --%> <body><b><%= Encode.forHtml(UNTRUSTED) %>" /></b></body> <%-- HTML Attribute Context --%> <input type="text" name="data" value="<%= Encode.forHtmlAttribute(UNTRUSTED) %>" /> <%-- Javascript Block context --%> <script type="text/javascript"> var msg = "<%= Encode.forJavaScriptBlock(UNTRUSTED) %>"; alert(msg); </script> <%-- Javascript Variable context --%> <button onclick="alert('<%= Encode.forJavaScriptAttribute(UNTRUSTED) %>');">click me</button> OWASP Java Encoder Project https://www.owasp.org/index.php/OWASP_Java_Encoder_Project
  • 29. OWASP Java Encoder Project https://www.owasp.org/index.php/OWASP_Java_Encoder_Project HTML Contexts Encode#forHtml(String) Encode#forHtmlContent(String) Encode#forHtmlAttribute(String) Encode#forHtmlUnquotedAttribute (String) XML Contexts Encode#forXml(String) Encode#forXmlContent(String) Encode#forXmlAttribute(String) Encode#forXmlComment(String) Encode#forCDATA(String) CSS Contexts Encode#forCssString(String) Encode#forCssUrl(String) JavaScript Contexts Encode#forJavaScript(String) Encode#forJavaScriptAttribute(String) Encode#forJavaScriptBlock(String) Encode#forJavaScriptSource(String) URI/URL contexts Encode#forUriComponent(String)
  • 30. Microsoft Encoder and AntiXSS Library • System.Web.Security.AntiXSS • Microsoft.Security.Application . AntiXSS • Can encode for HTML, HTML attributes, XML, CSS and JavaScript. • Native .NET Library • Very powerful well written library • For use in your User Interface code to defuse script in output
  • 31. HTML Encoding stops XSS in this context! Sample test attack payload: Reflective XSS attack example: Untrusted data may land in a UI snippet like the following: <div><%= request.getParameter("error_msg") %></div> http://example.com/error? error_msg= <script>alert(document.cookie)</script> XSS in HTML Body example.com/error?error_msg=You cannot access that file.
  • 32. HTML Body Escaping Examples OWASP Java Encoder <b><%= Encode.forHtml(UNTRUSTED)%></b> <p>Title:<%= Encode.forHtml(UNTRUSTED)%></p> <textarea name="text"> <%= Encode.forHtmlContent(UNTRUSTED) %> </textarea> AntiXSS .NET Encoder.HtmlEncode(UNTRUSTED)
  • 33. XSS in HTML Attributes  Where else can XSS go?  <input type="text" name="comments" value="">  What could an attacker put in here?  <input type="text" name="comments"  value="hello" onmouseover="/*fire attack*/">  Attackers can add event handlers:  onMouseOver  onLoad  onUnLoad  etc…
  • 34. HTML Attribute Context  Aggressive escaping is needed when placing untrusted data into typical attribute values like width, name, value, etc.  This rule is NOT ok for complex attributes likes href, src, style, or any event handlers like onblur or onclick.  Escape all non alpha-num characters with the &#xHH; format  This rule is so aggressive because developers frequently leave attributes unquoted  <div id=DATA></div>
  • 35. HTML Attribute Escaping Examples 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)
  • 36. URL Parameter Escaping 36 Escape all non alpha-num characters with the %HH format <a href="/search?data=<%=DATA %>"> Be careful not to allow untrusted data to drive entire URL’s or URL fragments This encoding only protects you from XSS at the time of rendering the link Treat DATA as untrusted after submitted
  • 37. URL Parameter Escaping Examples OWASP Java Encoder <%-- Encode URL parameter values --%> <a href="/search?value= <%=Encode.forUriComponent(parameterValue)%>&order=1#top"> <%-- Encode REST URL parameters --%> <a href="http://www.codemagi.com/page/ <%=Encode.forUriComponent(restUrlParameter)%>"> AntiXSS .NET Encoder.UrlEncode(untrustedUrlFragment)
  • 38. Handling Untrusted URL’s 1) First validate to ensure the string is a valid URL 2) Avoid Javascript: URL’s 3) Only allow HTTP or HTTPS only 4) Check the URL for malware inbound and outbound 5) Encode URL in the right context of display <a href="UNTRUSTED URL">UNTRUSTED URL</a>
  • 39. Escaping when managing complete URL’s Assuming the untrusted URL has been properly validated.... OWASP Java Encoder <a href="<%= Encode.forHTMLAttribute(untrustedURL) %>"> Encode.forHtmlContent(untrustedURL) </a> AntiXSS .NET <a href="<%= Encoder.HtmlAttributeEncode(untrustedURL) %>"> Encoder.HtmlEncode(untrustedURL) </a>
  • 40. XSS in JavaScript Context http://example.com/viewPage?name=Jerry  What attacks would be possible?  What would a %0d%0a in the name parameter do in the output?
  • 41. JavaScript Escaping Examples OWASP Java Encoder <button onclick="alert('<%= Encode.forJavaScript(alertMsg) %>');"> click me</button> <button onclick="alert('<%= Encode.forJavaScriptAttribute(alertMsg) %>');">click me</button> <script type="text/javascript"> var msg = "<%= Encode.forJavaScriptBlock(alertMsg) %>"; alert(msg); </script> AntiXSS .NET Encoder.JavaScriptEncode(alertMsg)
  • 42. XSS in the Style Tag 42 Applications sometimes take user data and use it to generate presentation style Consider this example: http://example.com/viewDocument?background=white URL parameter written within style tag
  • 43. CSS Context: XSS Defense 43 Escape all non alpha-num characters with the HH format <span style=bgcolor:DATA;>text</style> Do not use any escaping shortcuts like " Strong positive structural validation is also required If possible, design around this “feature”  Use trusted CSS files that users can choose from  Use client-side only CSS modification (font size)
  • 44. XSS in CSS String Context Examples 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)
  • 45. Dangerous Contexts 45 There are just certain places in HTML documents where you cannot place untrusted data Danger: <a $DATA> $DATA onblur="attack" There are just certain JavaScript functions that cannot safely handle untrusted data for input Danger: <script>eval($DATA);</script>
  • 46. XSS Defense by Data Type and Context Data Type Context Defense String HTML Body/Attribute HTML Entity Encode String JavaScript Variable JavaScript Hex encoding String GET Parameter URL Encoding String Untrusted URL URL Validation, avoid javascript: URL’s, Attribute encoding, safe URL verification String CSS Strict structural validation, CSS Hex encoding, good design HTML HTML Body HTML Validation (JSoup, AntiSamy, HTML Sanitizer) Any DOM DOM XSS Cheat sheet Untrusted JavaScript Any Sandboxing JSON Client parse time JSON.parse() or json2.js Safe HTML Attributes include: align, alink, alt, bgcolor, border, cellpadding, cellspacing, class, color, cols, colspan, coords, dir, face, height, hspace, ismap, lang, marginheight, marginwidth, multiple, nohref, noresize, noshade, nowrap, ref, rel, rev, rows, rowspan, scrolling, shape, span, summary, tabindex, title, usemap, valign, value, vlink, vspace, width
  • 48. What is HTML Sanitization • HTML sanitization takes markup as input, outputs “safe” markup • Different from encoding • URLEncoding, HTMLEncoding, will not help you here! • HTML sanitization is everywhere • TinyMCE/CKEditor Widgets • Web forum posts w/markup • Javascript-based Windows 8 Store apps • Outlook.com • Advertisements
  • 49.
  • 50. Why are HTML sanitization bugs important? • Worst case scenario • Script running from a mail message executes within the security context of the mail application • …from the preview pane that appears automatically • Attacker could set up auto-forwarding, impersonate you, steal all your mail, etc. • Yet, HTML sanitization bugs are pervasive • Fuzzing? Can be helpful, but difficult • Threat modeling? Not so relevant… • Smart hackers with some free time – very relevant And the underlying platforms continue to change. All of them. This is a hard problem.
  • 51. HTML Sanitization Bug #1 • Sanitizer Bypass in validator Node.js Module by @NealPoole (https://t.co/5omk5ec2UD) • Nesting • Input: <scrRedirecRedirect 302 302ipt type="text/javascript">prompt(1);</scrRedirecRedirect 302 302ipt> • Output: <script type="text/javascript">prompt(1);</script> • Observation: Removing data from markup can create XSS where it didn’t previously exist!
  • 52. HTML Sanitization Bug #2 • CVE-2011-1252 / MS11-074 • SharePoint / SafeHTML (UnsafeHTMLWhenUsingIE(String)) • Input: <style>div{color:rgb(0,0,0)&a=expression(alert(1))} </style> • &  &amp; (HTML Encode) • Output: <style>div{color:rgb(0,0,0)&amp;a=expression(alert( 1))}</style> • Observations: • Sanitizer created a delimiter (the semi-colon) • Legacy IE CSS expression syntax required to execute script • Sanitizer: “expression” is considered to be in a benign location • Browser: “expression” is considered to be the RHS of a CSS property set operation
  • 53. HTML Sanitization Bug #3 • Wordpress 3.0.3 (kses.php) • Credit: Mauro Gentile (@sneak_) • Thx @superevr! • Input and Output: <a HREF="javascript:alert(0)">click me</a> • Observations: • No content modification required to trigger the vulnerability • Sanitizer: Only lower case “href” recognized as an attribute • Browser: HREF attribute recognized, javascript: URL executes on click • Sanitizer and browser don’t agree on what constitutes an attribute name
  • 54. OWASP OWASP HTML Sanitizer Project https://www.owasp.org/index.php/OWASP_Java_HTML_Sanitizer_Project • HTML Sanitizer written in Java which lets you include HTML authored by third-parties in your web application while protecting against XSS. • This code was written with security best practices in mind, has an extensive test suite, and has undergone adversarial security review • https://code.google.com/p/owasp-java-html-sanitizer/ • Very easy to use. • It allows for simple programmatic POSITIVE policy configuration. No XML config. • Actively maintained by Mike Samuel from Google's AppSec team! • This is code from the Caja project that was donated by Google. It is rather high performance and low memory utilization.
  • 55. 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);
  • 56. • Pure JavaScript, client side HTML Sanitization with CAJA! • http://code.google.com/p/google-caja/wiki/JsHtmlSanitizer • https://code.google.com/p/google- caja/source/browse/trunk/src/com/google/caja/plugin/html-sanitizer.js • Python • https://pypi.python.org/pypi/bleach • PHP • http://htmlpurifier.org/ • http://www.bioinformatics.org/phplabware/internal_utilities/htmLawed/ • .NET AntiXSS Library (v4.3 released June 2, 2014) • http://www.nuget.org/packages/AntiXss/ (encoding) • https://github.com/mganss/HtmlSanitizer (HTML Sanitization) • Ruby on Rails • https://rubygems.org/gems/loofah • http://api.rubyonrails.org/classes/HTML.html • Java • https://www.owasp.org/index.php/OWASP_Java_HTML_Sanitizer_Project HTML Sanitizers by Language
  • 57. DOM Based XSS Defense 57 DOM Based XSS is a complex risk Suppose that x landed in … <script>setInterval(x, 2000);</script> For some Javascript functions, even JavaScript that is properly encoded will still execute!
  • 58. Direct execution  eval()  window.execScript()/function()/setInterval()/setTimeout(), requestAnimationFrame()  script.src(), iframe.src() Build HTML/ JavaScript  document.write(), document.writeln()  elem.innerHTML = danger, elem.outerHTML = danger  elem.setAttribute("dangerous attribute", danger) – attributes like: href, src, onclick, onload, onblur, etc. Within execution context  onclick()  onload()  onblur(), etc Source: https://www.owasp.org/index.php/DOM_based_XSS_Prevention_Cheat_Sheet Dangerous JavaScript Sinks
  • 59. Some Safe JavaScript Sinks Setting a value  elem.innerText = "danger";  formfield.value = "danger"; Safe JSON parsing  JSON.parse() (rather than eval())
  • 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/
  • 61. jQuery API’s and XSS Dangerous jQuery 1.7.2 Data Types CSS Some Attribute Settings HTML URL (Potential Redirect) jQuery methods that directly update DOM or can execute JavaScript $() or jQuery() .attr() .add() .css() .after() .html() .animate() .insertAfter() .append() .insertBefore() .appendTo() Note: .text() updates DOM, but is safe. jQuery methods that accept URLs to potentially unsafe content jQuery.ajax() jQuery.post() jQuery.get() load() jQuery.getScript() Don’t send untrusted data to these methods, or properly escape the data before doing so
  • 62. jQuery – But there’s more… More danger  jQuery(danger) or $(danger)  This immediately evaluates the input!!  E.g., $("<img src=x onerror=alert(1)>")  jQuery.globalEval()  All event handlers: .bind(events), .bind(type, [,data], handler()), .on(), .add(html) Safe examples  .text(danger), .val(danger) Some serious research needs to be done to identify all the safe vs. unsafe methods  There are about 300 methods in jQuery Source: http://code.google.com/p/domxsswiki/wiki/jQuery
  • 63. Client Side Context Sensitive Output Escaping Context Escaping Scheme Example HTML Element ( &, <, >, " )  &entity; ( ', / )  &#xHH; $ESAPI.encoder(). encodeForHTML() HTML Attribute All non-alphanumeric < 256  &#xHH $ESAPI.encoder(). encodeForHTMLAttribute() JavaScript All non-alphanumeric < 256  xHH $ESAPI.encoder(). encodeForJavaScript() HTML Style All non-alphanumeric < 256  HH $ESAPI.encoder(). encodeForCSS() URI Attribute All non-alphanumeric < 256  %HH $ESAPI.encoder(). encodeForURL() Encoding methods built into a jquery-encoder: https://github.com/chrisisbeef/jquery-encoder
  • 64. JQuery Encoding with JQencoder Contextual encoding is a crucial technique needed to stop all types of XSS jqencoder is a jQuery plugin that allows developers to do contextual encoding in JavaScript to stop DOM-based XSS  http://plugins.jquery.com/plugin-tags/security  $('#element').encode('html', UNTRUSTED-DATA);
  • 65. Should you trust all JSON? "user": { "name": "Jameson", "occupation": "Distiller", "location": (function() { alert("XSS 1!"); return "somewhere"})(), "_location_comment": "Once parsed unsafely, the location XSS will run automatically, as a self-executing function. JSON.parse can help with this, and jQuery's $.parseJSON uses it by default (as do $.ajax, etc)", "bio": "<script type='text/javascript'>alert('XSS!');</script>", "_bio_comment": "This XSS will execute once it is added to the DOM, if not properly escaped before adding it. This is more of a persistent kind of XSS attack." }
  • 66. OWASP JSON Sanitizer Project https://www.owasp.org/index.php/OWASP_JSON_Sanitizer • Given JSON-like content, converts it to valid JSON. • This can be attached at either end of a data-pipeline to help satisfy Postel's principle: Be conservative in what you do, be liberal in what you accept from others. • Applied to JSON-like content from others, it will produce well-formed JSON that should satisfy any parser you use. • Applied to your output before you send, it will coerce minor mistakes in encoding and make it easier to embed your JSON in HTML and XML.
  • 67. OWASP JSON Sanitizer Project https://www.owasp.org/index.php/OWASP_JSON_Sanitizer
  • 68. Server Side JSON Sanitization The Problem Web Page is vulnerable to XSS because of parsing of untrusted JSON incorrectly The Solution JSON Sanitizer can help with two use cases. 1) Sanitizing untrusted JSON on the server that is submitted from the browser in standard AJAX communication 2) Sanitizing potentially untrusted JSON server-side before sending it to the browser. The output is a valid Javascript expression, so can be parsed by Javascript's eval or by JSON.parse.
  • 69. Best Practice: Sandboxing  Object.seal( obj )  Object.isSealed( obj )  Sealing an object prevents other code from deleting, or changing the descriptors of, any of the object's properties JavaScript Sandboxing (ECMAScript 5) iFrame Sandboxing (HTML5)  <iframe src="demo_iframe_sandbox.jsp" sandbox=""></iframe>  Allow-same-origin, allow-top- navigation, allow-forms, allow-scripts More Later in HTML 5 considerations
  • 70. Best Practice: X-Xss-Protection •Use the browser’s built in XSS Auditor •X-Xss-Protection: •[0-1] (mode=block) •X-Xss-Protection: •1; mode=block
  • 71. Best Practice: Content Security Policy Anti-XSS W3C standard Must move all inline script and style into external scripts Add the Content-Security-Policy response header to instruct the browser that CSP is in use.  The CSP standard and browser support is still emerging  Do not depend on CSP yet  True standard browser support is 1 years off CSP 2.0 Working Draft Last Call published July 2014  http://www.w3.org/TR/CSP2/
  • 72. Best Practice: Content Security Policy Externalize all Java-Script within web pages No inline script tag No inline JavaScript for onclick, onblur or other inline events handling Push all JavaScript to formal .js files using event binding Define Content Security Policy Developers define which scripts/directories are valid Browser will only execute supported scripts Inline JavaScript code will be ignored
  • 73. When should you apply CSP? • It is a great ideas when building a new web application to apply CSP from day 1. • CSP should be on 100% of html endpoints. • It is often non-trivial to apply CSP to an existing app, so start from the beginning!
  • 74. This is an unrealistic policy default-src ‘self’; object-src ‘none’ XSS eliminated √ Flashed disabled √ Mixed content disallowed √ Third party content not allowed √ https://developer.mozilla.org/en-US/docs/Web/Security/CSP/CSP_policy_directives The default-src directive defines the security policy for types of content which are not expressly called out by more specific directives.
  • 75. This is a common policy default-src ‘self’; img-src https://mycdn.com; script-src ‘unsafe-inline’ https://mycdn.com; style-src ‘unsafe-inline’ https://mycdn.com object-src ‘none’; XSS eliminated X Flash disabled √ Mixed content disallowed √ Third party content not allowed √
  • 76. This is a useless policy default-src *; script-src * ‘unsafe-inline’ ‘unsafe-eval’; style-src * ‘unsafe-inline’; XSS eliminated X Flash disabled X Mixed content disallowed X Third party content not allowed X

Editor's Notes

  1. 1
  2. “That is, the page itself (the HTTP response that is) does not change, but the client side code contained in the page executes differently due to the malicious modifications that have occurred in the DOM environment.” – OWASP.org
  3. A Sample Attack Scenario A web application accepts user comment submissions for administrators Administrators view the comments from a web-based interface within the application An attacker submits a comment along with the malicious JavaScript line shown in the previous slide The administrator views the attackers comment, and the administrator’s SessionID is sent within the image tag and recorded in the attacker’s web server access log
  4. September 22, 2016
  5. From @randomdross
  6. Is replace() safe or unsafe?
  7. http://tech.blog.box.com/2013/08/securing-jquery-against-unintended-xss/
  8. CREDIT THIS TO DAVE WICHERS. Note: The issue with $() is being worked on and will hopefully be much harder to exploit in jQuery 1.8
  9. "user": { "name": "Johnny Walker", "occupation": "Distiller", "location": (function() { alert("XSS 1!"); return "somewhere"})(), "_location_comment": "Once parsed unsafely, the location XSS will run automatically, as a self-executing function. JSON.parse can help with this, and jQuery's $.parseJSON uses it by default (as do $.ajax, etc)", "bio": "<script type='text/javascript'>alert('XSS 2!');</script>", "_bio_comment": "This XSS will execute once it is added to the DOM, if not properly escaped before adding it. This is more of a persistent kind of XSS attack, typically from poor input validation on server side." }
  10. The browser will only execute script in source files from the white-listed domains and will disregard everything else, including inline scripts and event-handling HTML attributes. Note: event-handling is still enabled in CSP without using HTML attributes. Sites that never want to have JavaScript included in their pages can choose to globally disallow script.