xss defense module v6.2.pdf

52
March 2012 XSS Defense v6.2 Eoin Keary and Jim Manico Page 1 XSS Defense Module Eoin Keary Jim Manico

Upload: truongtu

Post on 13-Feb-2017

234 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: XSS Defense Module v6.2.pdf

March 2012 XSS Defense v6.2 Eoin Keary and Jim Manico Page 1

XSS Defense Module

Eoin Keary Jim Manico

Page 2: XSS Defense Module v6.2.pdf

March 2012 XSS Defense v6.2 Eoin Keary and Jim Manico Page 2

What is XSS? Cross-site Scripting (XSS)

Attacker driven JavaScript Most common web vulnerability Easy vulnerability to find via auditing Easy vulnerability to exploit Certain types of XSS are very complex to fix Difficult to fix all XSS for a large app Easy to re-introduce XSS in development Significant business and technical impact

potential

Page 3: XSS Defense Module v6.2.pdf

March 2012 XSS Defense v6.2 Eoin Keary and Jim Manico Page 3

XSS Attack Payload Types Session hijacking

Site defacement potential

Network scanning

Undermining CSRF defenses

Site redirection/phishing

Data theft

Keystroke logging

Loading of remotely hosted scripts

Page 4: XSS Defense Module v6.2.pdf

March 2012 XSS Defense v6.2 Eoin Keary and Jim Manico Page 4

Input Example

Consider the following URL :

www.example.com/saveComment?comment=Great+Site!

How can an attacker misuse this?

Page 5: XSS Defense Module v6.2.pdf

March 2012 XSS Defense v6.2 Eoin Keary and Jim Manico Page 5

XSS Variants

Reflected/Transient Data provided by a client is immediately used

by server-side scripts to generate a page of results for that user.

Search engines

Stored/Persistent Data provided by a client is first stored

persistently on the server (e.g., in a database, filesystem), and later displayed to users

Bulletin Boards, Forums, Blog Comments

Page 6: XSS Defense Module v6.2.pdf

March 2012 XSS Defense v6.2 Eoin Keary and Jim Manico Page 6

XSS Variants

DOM based XSS A page's client-side script itself accesses a URL

request parameter and uses this information to dynamically write some HTML to its own page

DOM XSS is triggered when a victim interacts with a web page directly without causing the page to reload.

Difficult to test with scanners and proxy tools –

why?

Page 7: XSS Defense Module v6.2.pdf

March 2012 XSS Defense v6.2 Eoin Keary and Jim Manico Page 7

Web Serverwith XSS hole

10.0.0.10

Hacker web server

10.0.0.20

Victim

1. Hacker inserts XSS

code into page on target web

server

2. Victim views page with inserted XSS

code

3. Inserted XSS code redirects victim to hacker web server

4. Cookie stolen and available for

hacker to use!

Hacker$$

Reflected XSS

1. Hacker sends link to victim. Link contains XSS payload

2. Victim views page via XSS link supplied

by attacker.

3. XSS code executes

on victims browser and sends cookie to evil

server

4. Cookie is stolen. The Attacker can hijack the

Victims session.

Page 8: XSS Defense Module v6.2.pdf

March 2012 XSS Defense v6.2 Eoin Keary and Jim Manico Page 8

//Search.aspx.cs

public partial class _Default : System.Web.UI.Page

{

Label lblResults;

protected void Page_Load(object sender, EventArgs e)

{

//... doSearch();

this.lblResults.Text = "You Searched For " +

Request.QueryString["query"];

}

OK: http://app.com/Search.aspx?query=soccer

NOT OK: http://app.com/Search.aspx?query=<script>...</script>

Reflected XSS

Page 9: XSS Defense Module v6.2.pdf

March 2012 XSS Defense v6.2 Eoin Keary and Jim Manico Page 9

Reflected XSS Demo - Keylogger

Page 10: XSS Defense Module v6.2.pdf

March 2012 XSS Defense v6.2 Eoin Keary and Jim Manico Page 10

4

Persistent/Stored XSS

Page 11: XSS Defense Module v6.2.pdf

March 2012 XSS Defense v6.2 Eoin Keary and Jim Manico Page 11

//ViewComments.jsp

<%

int id = Integer.parseInt(Request.getParameter(“id”));

Statement stmt = conn.createStatement();

ResultSet rs =

stmt.executeQuery("select * from forum where id=“ + id);

if (rs != null) {

rs.next();

String name = rs.getString(“comment");

%>

User Comment : <%= comment %>

Persistent/Stored XSS

Page 12: XSS Defense Module v6.2.pdf

March 2012 XSS Defense v6.2 Eoin Keary and Jim Manico Page 12

Persistent/Stored XSS – Demo

Page 13: XSS Defense Module v6.2.pdf

March 2012 XSS Defense v6.2 Eoin Keary and Jim Manico Page 13

1

4

DOM-Based XSS

Page 14: XSS Defense Module v6.2.pdf

March 2012 XSS Defense v6.2 Eoin Keary and Jim Manico Page 14

<HTML> <TITLE>Welcome!</TITLE> Hi <SCRIPT> var pos=document.URL.indexOf("name=")+5;

document.write(document.URL.substring(pos,document.URL.length));

</SCRIPT> <BR> Welcome to our system </HTML> OK : http://a.com/page.htm?name=Joe NOT OK: http://a.com/page.htm?name=<script>...</script>

In DOM XSS the attack vector has not rewritten the HTML but is a parameter value

DOM-Based XSS

Page 15: XSS Defense Module v6.2.pdf

March 2012 XSS Defense v6.2 Eoin Keary and Jim Manico Page 15

Test for Cross-Site Scripting Make note of all pages that display input

originating from current or other users. Test by inserting malicious script or characters

to see if they are ultimately displayed back to the user

Examine code to ensure that application data is HTML encoded before being rendered to users

Very easy to discover XSS via dynamic testing More difficult to discover via code review

Page 16: XSS Defense Module v6.2.pdf

March 2012 XSS Defense v6.2 Eoin Keary and Jim Manico Page 16

Test for Cross-Site Scripting Remember the three common types of attacks:

Input parameters that are rendered directly back to the user

Server-Side Client-Side

Input that is rendered within other pages Hidden fields are commonly vulnerable to this

exploit as there is a perception that hidden fields are read-only

Error messages that redisplay user input

Page 17: XSS Defense Module v6.2.pdf

March 2012 XSS Defense v6.2 Eoin Keary and Jim Manico Page 17

Test for Cross-Site Scripting Each input should be tested to see if data gets

rendered back to the user. Break out of another tag by inserting “>

before the malicious script Bypass <script> “tag-hunting” filters

<IMG SRC=“javascript:alert(document.cookie)”>

<p style="left:expression(eval('alert(document.cookie)'))">

\u003Cscript\u003E

May not require tags if the input is inserted into an existing JavaScript routine <- DOM XSS

<SCRIPT> <% = userdata %> </SCRIPT>

Page 18: XSS Defense Module v6.2.pdf

March 2012 XSS Defense v6.2 Eoin Keary and Jim Manico Page 18

Danger: XSS Weak Defense Used

Getting rid of XSS is a difficult task How can we prevent XSS in our web

application Eliminate <, >, &, ", ' characters? Eliminate all special characters? Disallow user input? (not possible) Global filter?

Why won't these strategies work?

Page 19: XSS Defense Module v6.2.pdf

March 2012 XSS Defense v6.2 Eoin Keary and Jim Manico Page 19

XSS Defense: The Solution? Depends on the type of user input

HTML, Strings, Uploaded Files Depends on where user input is displayed in an

HTML document HTML Body HTML Attribute JavaScript Variable Assignment

Several defensive techniques needed depending on context Input Validation Output Encoding Sandboxing

Page 20: XSS Defense Module v6.2.pdf

March 2012 XSS Defense v6.2 Eoin Keary and Jim Manico Page 20

Data Type Context Defense

Numeric, Type safe language Doesn’t Matter Cast to Numeric

String HTML Body HTML Entity Encode

String HTML Attribute, quoted Minimal Attribute Encoding

String HTML Attribute, unquoted

Maximum Attribute Encoding

String GET Parameter URL Encoding

String Untrusted URL URL Validation, avoid javascript: URL’s, Attribute encoding, safe URL verification

String CSS Strict structural validation, CSS Hex encoding, good design

HTML HTML Body HTML Validation (JSoup, AntiSamy, HTML Sanitizer)

Any DOM DOM XSS Cheat sheet

Untrusted JavaScript Any Sandboxing

JSON Client parse time JSON.parse() or json2.js

XSS Defense

Page 21: XSS Defense Module v6.2.pdf

March 2012 XSS Defense v6.2 Eoin Keary and Jim Manico Page 21

String email = request.getParameter("email"); out.println("Your email address is: " + email);

Best Practice: Validate and Encode User Input

String email = request.getParameter("email"); String expression = "^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$"; Pattern pattern = Pattern.compile(expression,Pattern.CASE_INSENSITIVE); Matcher matcher = pattern.matcher(email); if (macher.maches()) { out.println("Your email address is: " + StringEscapeUtils.escapeHtml(email)); } else { //log & throw a specific validation exception and fail safely }

Page 22: XSS Defense Module v6.2.pdf

March 2012 XSS Defense v6.2 Eoin Keary and Jim Manico Page 22

StringBuffer buff = new StringBuffer(); if ( value == null ) { return null; } for(int i=0; i<value.length(); i++) { char ch = value.charAt(i); if ( ch == '&' ) { buff.append("&amp;"); } else if ( ch == '<') { buff.append("&lt;"); } else if ( ch == '>') { buff.append("&gt;"); } else if ( Character.isWhitespace(ch ) ) { buff.append(ch); } else if ( Character.isLetterOrDigit(ch) ) { buff.append(ch); } else if ( Integer.valueOf(ch).intValue() >= 20 && Integer.valueOf(ch).intValue() <= 126 ) { buff.append( "&#" + (int)ch + ";" ); } } return buff.toString();

Simple HTML encoding method

Output Encoding Code Sample

Page 23: XSS Defense Module v6.2.pdf

March 2012 XSS Defense v6.2 Eoin Keary and Jim Manico Page 23

Danger: Multiple Contexts Different encoding and validation techniques

needed for different contexts!

HTML Body

HTML Attributes

<STYLE> Context

<SCRIPT> Context

URL Context

Page 24: XSS Defense Module v6.2.pdf

March 2012 XSS Defense v6.2 Eoin Keary and Jim Manico Page 24

HTML Input • Clients side widgets like TinyMCE and CKEditor

• Users can edit content beyond plain text • Bold, Bullet Points, Color, etc

• These class of widgets submit HTML via request

parameters, simple validation not enough

• Validate user-driven HTML on the server with an HTML policy engine • Java OWASP AntiSamy or HTML Sanitizer • PHP HTML Purifier • Java JSoup

Page 25: XSS Defense Module v6.2.pdf

March 2012 XSS Defense v6.2 Eoin Keary and Jim Manico Page 25

XSS in HTML Body Reflective XSS attack example: example.com/error?error_msg=You cannot access that

file.

Untrusted data may land in a UI snippet like the following:

<div><%= request.getParameter(“error_msg”) %></div>

Sample test attack payload: example.com/error?

error_msg=<script>alert(document.cookie)</script>

HTML Encoding stops XSS in this context!

Page 26: XSS Defense Module v6.2.pdf

March 2012 XSS Defense v6.2 Eoin Keary and Jim Manico Page 26

1. & &amp;

2. < &lt;

3. > &gt;

4. " &quot;

5. ' &#x27;

6. / &#x2F;

HTML Entity Encoding: The Big 6

Page 27: XSS Defense Module v6.2.pdf

March 2012 XSS Defense v6.2 Eoin Keary and Jim Manico Page 27

XSS in HTML Attributes

Where else can XSS go? <input type="text" name="comments" value=""> What could an attacker put in here? <input type="text" name="comments"

value="hello" onmouseover="/*fire attack*/"> Attackers can add event handlers:

onMouseOver onLoad onUnLoad etc…

Page 28: XSS Defense Module v6.2.pdf

March 2012 XSS Defense v6.2 Eoin Keary and Jim Manico Page 28

HTML Attribute Context

Aggressive escaping is needed when placing untrusted data into typical attribute values like width, name, value, etc.

This rule is NOT ok for complex attributes likes href, src, style, or any event handlers like onblur or onclick.

Escape all non alpha-num characters with the &#xHH; format

This rule is so aggressive because developers frequently leave attributes unquoted

<div id=DATA></div>

Page 29: XSS Defense Module v6.2.pdf

March 2012 XSS Defense v6.2 Eoin Keary and Jim Manico Page 29

XSS in Source Attribute

User input often winds up in src attribute Tags such as <img src=""> <iframe src=""> Example Request: http://example.com/viewImage?imagename=mymap.jpg

Attackers can use javascript:/*attack*/ in src attributes

Page 30: XSS Defense Module v6.2.pdf

March 2012 XSS Defense v6.2 Eoin Keary and Jim Manico Page 30

XSS Scripting in Script Tag

http://example.com/viewPage?name=Jerry What attacks would be possible? What would a %0d%0a in the name parameter do

in the output?

Page 31: XSS Defense Module v6.2.pdf

March 2012 XSS Defense v6.2 Eoin Keary and Jim Manico Page 31

Javascript Context

Escape all non alpha-num characters with the \xHH format

<script>var x='DATA';</script> You're now protected from XSS at the time data

is assigned What happens to x after you assign it?

Page 32: XSS Defense Module v6.2.pdf

March 2012 XSS Defense v6.2 Eoin Keary and Jim Manico Page 32

URL Parameter Escaping

Escape all non alpha-num characters with the %HH format

<a href=“/search?data=<%=DATA %>”> Be careful not to allow untrusted data to drive

entire URL’s or URL fragments This encoding only protects you from XSS at the

time of rendering the link Treat DATA as untrusted after submitted

Page 33: XSS Defense Module v6.2.pdf

March 2012 XSS Defense v6.2 Eoin Keary and Jim Manico Page 33

URL parameter written within style tag

Applications sometimes take user data and use it to generate presentation style

Consider this example: http://example.com/viewDocument?background=white

XSS in the Style Tag

Page 34: XSS Defense Module v6.2.pdf

March 2012 XSS Defense v6.2 Eoin Keary and Jim Manico Page 34

CSS Pwnage Test Case

<div style="width: <%=temp3%>;"> Mouse over </div>

temp3 = ESAPI.encoder().encodeForCSS("expression(alert(String.fromCharCode (88,88,88)))");

<div style="width: expression\28 alert\28 String\2e fromCharCode\20 \28 88\2c 88\2c 88\29 \29 \29 ;"> Mouse over </div>

Pops in at least IE6 and IE7. lists.owasp.org/pipermail/owasp-esapi/2009-

February/000405.html

Page 35: XSS Defense Module v6.2.pdf

March 2012 XSS Defense v6.2 Eoin Keary and Jim Manico Page 35

CSS Context: XSS Defense

Escape all non alpha-num characters with the \HH format

<span style=bgcolor:DATA;>text</style> Do not use any escaping shortcuts like \” Strong WhiteHat structural validation is also

required If possible, design around this “feature”

Use trusted CSS files that users can choose from

Use client-side only CSS modification (font size)

Page 36: XSS Defense Module v6.2.pdf

March 2012 XSS Defense v6.2 Eoin Keary and Jim Manico Page 36

Dangerous Contexts

There are just certain places in HTML documents where you cannot place untrusted data Danger: <a $DATA>

There are just certain JavaScript functions that cannot safely handle untrusted data for input Danger: <script>eval($DATA);</script>

Page 37: XSS Defense Module v6.2.pdf

March 2012 XSS Defense v6.2 Eoin Keary and Jim Manico Page 37

DOM Based XSS Defense

DOM Based XSS is a complex risk Suppose that x landed in …

<script>setInterval(x);</script>

For some Javascript functions, even JavaScript encoded untrusted data will still execute!

Page 38: XSS Defense Module v6.2.pdf

March 2012 XSS Defense v6.2 Eoin Keary and Jim Manico Page 38

“Secure” DOM XSS/AJAX Workflow • Initial loaded page should only be static content

• Load JSON data via AJAX

• Only use the following methods to populate the DOM • Node.textContent • document.createTextNode • Element.setAttribute

• Caution: Element.setAttribute is one of the most dangerous JS methods

• Caution: If the first element to setAttribute is any of the JavaScript event handlers or a URL context based attribute ("src", "href", "backgroundImage", "backgound", etc.) then XSS will pop

Page 39: XSS Defense Module v6.2.pdf

March 2012 XSS Defense v6.2 Eoin Keary and Jim Manico Page 39

Best Practice: DOM Based XSS Defense I • Untrusted data should only be treated as

displayable text

• JavaScript encode and delimit untrusted data as quoted strings

• Use document.createElement("…"), element.setAttribute("…","value"), element.appendChild(…), etc. to build dynamic interfaces

• Avoid use of HTML rendering methods

• Make sure that any untrusted data passed to eval() methods is delimited with string delimiters and enclosed within a closure or JavaScript encoded to N-levels based on usage and wrapped in a custom function

Page 40: XSS Defense Module v6.2.pdf

March 2012 XSS Defense v6.2 Eoin Keary and Jim Manico Page 40

Best Practice: DOM Based XSS Defense II • Limit the usage of dynamic untrusted data to right side

operations. And be aware of data which may be passed to the application which look like code (eg. location, eval()).

• When URL encoding in DOM be aware of character set issues as the character set in JavaScript DOM is not clearly defined

• Limit access to properties objects when using object[x] access functions

• Don’t eval() JSON to convert it to native JavaScript objects. Instead use JSON.toJSON() and JSON.parse()

• Run untrusted script in a sandbox (ECMAScript canopy, HTML 5 frame sandbox, etc)

Page 41: XSS Defense Module v6.2.pdf

March 2012 XSS Defense v6.2 Eoin Keary and Jim Manico Page 41

Jquery Encoding with JQencoder

Contextual encoding is the most effective way to combat Cross-Site Scripting (XSS) attacks

jqencoder is a jQuery plugin that allows developers to do contextual encoding to stop DOM-based XSS

http://plugins.jquery.com/plugin-tags/security <script type="text/javascript">

$.post( 'http://site.com/service',

{ parameter1: 'value' }, function(data) {

$('#element').encode('html', cdata);

});

</script>

Page 42: XSS Defense Module v6.2.pdf

March 2012 XSS Defense v6.2 Eoin Keary and Jim Manico Page 42

Jquery Demo

Page 43: XSS Defense Module v6.2.pdf

March 2012 XSS Defense v6.2 Eoin Keary and Jim Manico Page 43

Best Practice: Javascript Sandboxing

Capabilities JavaScript (CAJA) from Google Applies an advanced security

concept, capabilities, to define a version of JavaScript that can be safer than the sandbox

JSReg by Gareth Heyes Javascript sandbox which converts code using

regular expressions The goal is to produce safe Javascript from a

untrusted source

Page 44: XSS Defense Module v6.2.pdf

March 2012 XSS Defense v6.2 Eoin Keary and Jim Manico Page 44

Best Practice: Javascript Sandboxing

ECMAScript 5 Object.seal( obj ) Object.isSealed( obj )

Sealing an object prevents other code from deleting, or changing the descriptors of, any of the object's properties

Page 45: XSS Defense Module v6.2.pdf

March 2012 XSS Defense v6.2 Eoin Keary and Jim Manico Page 45

JSReg: Protecting JavaScript with JavaScript

JavaScript re-writing Parses untrusted HTML and returns trusted

HTML Utilizes the browser JS engine and regular

expressions No third-party code

First layer is an iframe used as a safe throw away box

Page 46: XSS Defense Module v6.2.pdf

March 2012 XSS Defense v6.2 Eoin Keary and Jim Manico Page 46

JSReg: Protecting JavaScript with JavaScript

The entire JavaScript objects/properties list was whitelisted by forcing all methods to use suffix/prefix of "$"

Each variable assignment was then localized using var to force local variables

Each object was also checked to ensure it didn’t contain a window reference

Content Security Policy JavaScript policy standard

Page 47: XSS Defense Module v6.2.pdf

March 2012 XSS Defense v6.2 Eoin Keary and Jim Manico Page 47

Best Practice: Content Security Policy

Externalize all JavaScript within web pages No inline script tag No inline JavaScript for onclick or other

handling events Push all JavaScript to formal .js files using

event binding Define Content Security Policy

Developers define which scripts are valid Browser will only execute supported scripts Inline JavaScript code is ignored

Page 48: XSS Defense Module v6.2.pdf

March 2012 XSS Defense v6.2 Eoin Keary and Jim Manico Page 48

OWASP ESAPI for Java

ESAPI library provides powerful encoding via ESAPI.encoder(): String encodeForHTML(String input) String encodeForHTMLAttribute(String

input) String encodeForJavaScript(String input) String encodeForURL(String input) String encodeForCSS(String input) And more! (LDAP, XML, OS, etc)

Page 49: XSS Defense Module v6.2.pdf

March 2012 XSS Defense v6.2 Eoin Keary and Jim Manico Page 49

ESAPI Output Encoding <style>

bgcolor: <%=ESAPI.encoder().encodeForCSS(data) %>;

</style>

Hello, <%=ESAPI.encoder().encodeForHTML(data) %>!

<script>

var uName='<%=ESAPI.encoder().encodeForJavaScript(data) %>';

</script>

<div id='<%=ESAPI.encoder().encodeForHTMLAttribute(data) %>'>

<a href="/mysite.com/editUser.do?userName=<%= ESAPI.encoder().encodeForURL(data) %>">Please click me!</a>

Page 50: XSS Defense Module v6.2.pdf

March 2012 XSS Defense v6.2 Eoin Keary and Jim Manico Page 50

XSS Defense Lab

Page 51: XSS Defense Module v6.2.pdf

March 2012 XSS Defense v6.2 Eoin Keary and Jim Manico Page 51

XSS Scripting Summary

Cross-Site Scripting (XSS) Harmful JavaScript artificially introduced into

your web app All user input must be validated! All user input must be encoded or sanitized

specific to each context before being displayed back to the browser!

Plenty of Web 2.0 vectors to consider such as JSON parsing and DOM XSS

Page 52: XSS Defense Module v6.2.pdf

March 2012 XSS Defense v6.2 Eoin Keary and Jim Manico Page 52

XSS Scripting Summary Consider automatic protection methodologies

such as HTTP Only Cookies JavaScript sandboxing Content Security Policy Context-aware auto-escaping templates Object sealing HTML5 Frame sandboxing