SlideShare a Scribd company logo
1 of 67
Download to read offline
Berlin, 2018-01-01
JavaScript Security
Mastering Cross Domain Communications
in complex JS applications
Grill.js Wrocław, 2018-08-18, 7pm
<thomas.witt@infopark.com>
@thomas_witt
linkedin.com/in/thomaswitt
Thomas Witt
Co-Founder
@thomas_witt
We're hiring!
Boston · Berlin · Wrocław
The Problem
JS Applications
need to exchange data with
Backend APIs
running on domains other than your own
SECURELY
Challange
Only load code from trusted origins,
don't execute malicious JS code,
don't let people steal your data.
Same Origin Policy
For security reasons, browsers restrict cross-
origin HTTP requests initiated from within
scripts.
For example, XMLHttpRequest and the Fetch
API follow the same-origin policy. This means
that a web application using those APIs can
only request HTTP resources from the same
origin the application was loaded from.
– https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
“
How to …
Exchange data
from JS applications with backend APIs
Two ways how to talk to other services
CORS postMessage
#1: CORS
Cross-Origin Resource Sharing
Same Origin Policy
A web application using those APIs can only
request HTTP resources from the same origin
the application was loaded from, unless the
response from the other origin includes
the right CORS headers.
– https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
“
The easy one:
Simple Requests
Simple GET request via CORS
var req = new XMLHttpRequest();
var url = 'http://bar.other/resources/public-data/';
function callOtherDomain() {
if(req) {
req.open('GET', url, true);
req.onreadystatechange = handler;
req.send();
}
}
Simple GET request via CORS
var req = new XMLHttpRequest();
var url = 'http://bar.other/resources/public-data/';
function callOtherDomain() {
if(req) {
req.open('GET', url, true);
req.onreadystatechange = handler;
req.send();
}
}
GET /resources/public-data/ HTTP/1.1
Origin: http://foo.example
HTTP/1.1 200 OK
Access-Control-Allow-Origin: *
Client (foo.example) Server (bar.other)
The uglyness:
Preflight Requests
aka not-so-simple-requests
Preflighted POST request via CORS
var invocation = new XMLHttpRequest();
var url = 'http://bar.other/resources/post-here/';
var body = '<?xml version="1.0"?><person><name>Thomas Witt</name></person>';
function callOtherDomain(){
if(invocation)
{
invocation.open('POST', url, true);
invocation.setRequestHeader('Content-Type', 'application/xml');
invocation.onreadystatechange = handler;
invocation.send(body);
}
}
Preflighted POST request via CORS - Overview
Client (foo.example) Server (bar.other)
OPTIONS /resources/post-here/ HTTP/1.1
Origin: http://foo.example
Access-Control-Request-Method: POST
Access-Control-Request-Headers: Content-Type
HTTP/1.1 200 OK
Access-Control-Allow-Origin: http://foo.example
Access-Control-Allow-Methods: POST, GET
Access-Control-Allow-Headers: Content-Type
Access-Control-Max-Age: 86400
var invocation = new XMLHttpRequest();
var url = 'http://bar.other/resources/post-here/';
var body = '<?xml version="1.0"?><person><name>Thomas Witt</name></person>';
function callOtherDomain(){
if(invocation)
{
invocation.open('POST', url, true);
invocation.setRequestHeader('Content-Type', 'application/xml');
invocation.onreadystatechange = handler;
invocation.send(body);
}
}
POST /resources/post-here/ HTTP/1.1
Content-Type: text/xml; charset=UTF-8
Origin: http://foo.example
HTTP/1.1 200 OK
Access-Control-Allow-Origin: http://foo.example
PreflightPhaseMainRequestPhase
For every new resource accessed,

a preflight request will be issued.
CORS Security
Introducing CSP
CORS vs CSP
CORS
CORS allows a server (bar.other) to give
permission to a site (foo.example) to read
(potentially private) data from a server
(bar.other), using the visitor's browser and
credentials.
CSP
CSP allows a site (foo.example) to prevent itself
from loading (potentially malicious) content
from unexpected sources (e.g. against XSS).
GET /resources/public-data/ HTTP/1.1
Origin: http://foo.example
HTTP/1.1 200 OK
Access-Control-Allow-Origin: *
Content-Security-Policy: base-uri 'none'; default-
src 'self' 'unsafe-inline' data: https: wss:; object-
src 'none'; script-src 'self' https://beta-
api.scrivito.com; upgrade-insecure-requests;
0,133%
of all 1M Alexa sites implement a CSP
June 2015, "CSP adoption: current status and future prospects", Ming Ying / Shu Qin Li
Example Response: www.scrivito.com (shortened)
HTTP/1.1 200 OK
Connection: keep-alive
Content-Encoding: gzip
Content-Security-Policy: base-uri 'none'; default-src 'self' 'unsafe-inline' data: https: wss:;
object-src 'none'; script-src 'self' https://assets.scrivito.com https://beta-api.scrivito.com https://
maps.googleapis.com https://www.google-analytics.com; upgrade-insecure-requests;
Content-Type: text/html; charset=UTF-8
Date: Wed, 18 Aug 2018 19:00:00 GMT
Implementation
A closer look
CSP Directives
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src
<script>
<img>
<link rel="stylesheet"> <style>
<audio> <video>
<iframe>
@font-face
WebSocket, XMLHttpRequest, EventSource
<embed> <object>
script-src Values
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src
self
unsafe-inline
unsafe-eval
*
none
my.url.com
<script src="/public/mylib.js" />
<script>
alert('Hello JavaScript!');
</script>
setTimeout();
eval();
All of it
None of it
Space-separated (*.js.com | api.js.com | https: | https://api.js.com | data:)
Examples
default-src 'none';
Examples
default-src *;
Examples
default-src 'self';
Our typical CSP
Content-Security-Policy:
base-uri 'none';
default-src 'self' https: wss:;
script-src 'self'
https://api.scrivito.com
https://assets.scrivito.com
https://www.google-analytics.com
https://maps.googleapis.com
https://whatever.service.you.need.com;
object-src 'none';
upgrade-insecure-requests;
CSP Key Takeaways
Every JavaScript application

should have a CSP.
It will most likely break your site
At the first try
script-src is most important
Always set default-src
Test it!
CSP v1 Browser Support
https://caniuse.com/#search=csp
CSP - further reading
developer.mozilla.org/docs/Web/HTTP/CSP
content-security-policy.com
csp-evaluator.withgoogle.com
cspvalidator.org
caniuse.com/#feat=contentsecuritypolicy
#2: postMessage
via iFrame
Cross-domain communication via window.postMessage
<iframe name="receiver"
src="https://bar.other/my.js">
<script>
let win = window.frames.receiver;
win.postMessage("message",
"https://bar.other");
</script>
window.addEventListener("message",
function(event) {
if (event.origin !=
'https://foo.example') {
// Unknown domain? Ignore!
return;
}
alert( "Rcvd: " + event.data );
});
Sender (foo.example) Receiver (bar.other)
That's it
window.postMessage vs CORS/CSP
Advantages
CORS is not very simple, postMessage is
No pre-flight requests
No need to modify HTTP headers
Not convinced?
Google uses it as well in it's Google API JS SDK
<iframe name="receiver"
src="https://bar.other/my.js">
<script>
let win = window.frames.receiver;
win.postMessage("message",
"https://bar.other");
</script>
window.addEventListener("message",
function(event) {
if (event.origin !=
'https://foo.example') {
// Unknown domain? Ignore!
return;
}
alert( "Rcvd: " + event.data );
});
window.postMessage Security
Security caveats
No side can figure out whether malicious code
has been inserted via XSS!
Check-List
Does the browser support postMessage?
Is the message origin correct and known?
Is the message data sanitized and validated?
Are origins matched using strict equality

(no indexOf(".foo.com") > 0)?
Are messages sent without using wildcards in the
origin?
<iframe name="receiver"
src="https://bar.other/my.js">
<script>
let win = window.frames.receiver;
win.postMessage("message",
"https://bar.other");
</script>
window.addEventListener("message",
function(event) {
if (event.origin !=
'https://foo.example') {
// Unknown domain? Ignore!
return;
}
alert( "Rcvd: " + event.data );
});
Bonus Tip:
github.com/jpillora/xdomain
Xdomain
A pure JavaScript CORS alternative.
No server configuration required - just add a
proxy.html on the domain you wish to
communicate with.
– https://github.com/jpillora/xdomain
“
window.postMessage - further reading
developer.mozilla.org/docs/Web/API/Window/postMessage
seclab.stanford.edu/websec/frames/post-message.pdf
labs.detectify.com/2016/12/08/the-pitfalls-of-postmessage/
caniuse.com/#feat=x-doc-messaging
Summary
Always have a CSP!
Use postMessage instead of CORS
when implementing Cross Domain Communication.
There's one more thing…
Bonus Tip #2:
HSTS
(You use TLS, right?)
Example Response: www.scrivito.com
HTTP/1.1 200 OK
Age: 83186
Cache-Control: public, max-age=0, must-revalidate
Connection: keep-alive
Content-Encoding: gzip
Content-Length: 1313
Content-Security-Policy: base-uri 'none'; default-src 'self' 'unsafe-inline' data: https: wss:;
object-src 'none'; script-src 'self' https://assets.scrivito.com https://beta-api.scrivito.com https://
maps.googleapis.com https://www.google-analytics.com; upgrade-insecure-requests;
Content-Type: text/html; charset=UTF-8
Date: Wed, 15 Aug 2018 12:59:51 GMT
Etag: "7cbc5a14104f9d58b476b606e830533b-ssl-df"
Server: Netlify
Strict-Transport-Security: max-age=31536000
Vary: Accept-Encoding
We're hiring.
In Wroclaw!
Your questions?
Can I haz question, please?
JavaScript Security: Mastering Cross Domain Communications in complex JS applications
JavaScript Security: Mastering Cross Domain Communications in complex JS applications
JavaScript Security: Mastering Cross Domain Communications in complex JS applications
JavaScript Security: Mastering Cross Domain Communications in complex JS applications
JavaScript Security: Mastering Cross Domain Communications in complex JS applications
JavaScript Security: Mastering Cross Domain Communications in complex JS applications
JavaScript Security: Mastering Cross Domain Communications in complex JS applications
JavaScript Security: Mastering Cross Domain Communications in complex JS applications
JavaScript Security: Mastering Cross Domain Communications in complex JS applications

More Related Content

What's hot

Evolution Of The Web Platform & Browser Security
Evolution Of The Web Platform & Browser SecurityEvolution Of The Web Platform & Browser Security
Evolution Of The Web Platform & Browser SecuritySanjeev Verma, PhD
 
Understanding REST
Understanding RESTUnderstanding REST
Understanding RESTNitin Pande
 
REST API Design for JAX-RS And Jersey
REST API Design for JAX-RS And JerseyREST API Design for JAX-RS And Jersey
REST API Design for JAX-RS And JerseyStormpath
 
Client sidesec 2013-intro
Client sidesec 2013-introClient sidesec 2013-intro
Client sidesec 2013-introTal Be'ery
 
Rest presentation
Rest  presentationRest  presentation
Rest presentationsrividhyau
 
Web Security - Cookies, Domains and CORS
Web Security - Cookies, Domains and CORSWeb Security - Cookies, Domains and CORS
Web Security - Cookies, Domains and CORSPerfectial, LLC
 
Scalable Reliable Secure REST
Scalable Reliable Secure RESTScalable Reliable Secure REST
Scalable Reliable Secure RESTguestb2ed5f
 
Cross site calls with javascript - the right way with CORS
Cross site calls with javascript - the right way with CORSCross site calls with javascript - the right way with CORS
Cross site calls with javascript - the right way with CORSMichael Neale
 
Representational State Transfer (REST) and HATEOAS
Representational State Transfer (REST) and HATEOASRepresentational State Transfer (REST) and HATEOAS
Representational State Transfer (REST) and HATEOASGuy K. Kloss
 
Rest & RESTful WebServices
Rest & RESTful WebServicesRest & RESTful WebServices
Rest & RESTful WebServicesPrateek Tandon
 
MITM Attacks on HTTPS: Another Perspective
MITM Attacks on HTTPS: Another PerspectiveMITM Attacks on HTTPS: Another Perspective
MITM Attacks on HTTPS: Another PerspectiveGreenD0g
 
Build a Node.js Client for Your REST+JSON API
Build a Node.js Client for Your REST+JSON APIBuild a Node.js Client for Your REST+JSON API
Build a Node.js Client for Your REST+JSON APIStormpath
 
Proxy log review and use cases
Proxy log review and use casesProxy log review and use cases
Proxy log review and use casesMostafa Yahia
 
CSRF: ways to exploit, ways to prevent
CSRF: ways to exploit, ways to preventCSRF: ways to exploit, ways to prevent
CSRF: ways to exploit, ways to preventPaulius Leščinskas
 
CORS - Enable Alfresco for CORS
CORS - Enable Alfresco for CORSCORS - Enable Alfresco for CORS
CORS - Enable Alfresco for CORSJared Ottley
 
DEF CON 27 - BEN SADEGHIPOUR - owning the clout through ssrf and pdf generators
DEF CON 27 - BEN SADEGHIPOUR  - owning the clout through ssrf and pdf generatorsDEF CON 27 - BEN SADEGHIPOUR  - owning the clout through ssrf and pdf generators
DEF CON 27 - BEN SADEGHIPOUR - owning the clout through ssrf and pdf generatorsFelipe Prado
 

What's hot (20)

Evolution Of The Web Platform & Browser Security
Evolution Of The Web Platform & Browser SecurityEvolution Of The Web Platform & Browser Security
Evolution Of The Web Platform & Browser Security
 
Understanding REST
Understanding RESTUnderstanding REST
Understanding REST
 
REST API Design for JAX-RS And Jersey
REST API Design for JAX-RS And JerseyREST API Design for JAX-RS And Jersey
REST API Design for JAX-RS And Jersey
 
Client sidesec 2013-intro
Client sidesec 2013-introClient sidesec 2013-intro
Client sidesec 2013-intro
 
Rest presentation
Rest  presentationRest  presentation
Rest presentation
 
Web Security - Cookies, Domains and CORS
Web Security - Cookies, Domains and CORSWeb Security - Cookies, Domains and CORS
Web Security - Cookies, Domains and CORS
 
Scalable Reliable Secure REST
Scalable Reliable Secure RESTScalable Reliable Secure REST
Scalable Reliable Secure REST
 
Owasp eee 2015 csrf
Owasp eee 2015 csrfOwasp eee 2015 csrf
Owasp eee 2015 csrf
 
Cross site calls with javascript - the right way with CORS
Cross site calls with javascript - the right way with CORSCross site calls with javascript - the right way with CORS
Cross site calls with javascript - the right way with CORS
 
Representational State Transfer (REST) and HATEOAS
Representational State Transfer (REST) and HATEOASRepresentational State Transfer (REST) and HATEOAS
Representational State Transfer (REST) and HATEOAS
 
Rest & RESTful WebServices
Rest & RESTful WebServicesRest & RESTful WebServices
Rest & RESTful WebServices
 
MITM Attacks on HTTPS: Another Perspective
MITM Attacks on HTTPS: Another PerspectiveMITM Attacks on HTTPS: Another Perspective
MITM Attacks on HTTPS: Another Perspective
 
Build a Node.js Client for Your REST+JSON API
Build a Node.js Client for Your REST+JSON APIBuild a Node.js Client for Your REST+JSON API
Build a Node.js Client for Your REST+JSON API
 
ASP.NET WEB API
ASP.NET WEB APIASP.NET WEB API
ASP.NET WEB API
 
Proxy log review and use cases
Proxy log review and use casesProxy log review and use cases
Proxy log review and use cases
 
CSRF: ways to exploit, ways to prevent
CSRF: ways to exploit, ways to preventCSRF: ways to exploit, ways to prevent
CSRF: ways to exploit, ways to prevent
 
CORS and (in)security
CORS and (in)securityCORS and (in)security
CORS and (in)security
 
CORS - Enable Alfresco for CORS
CORS - Enable Alfresco for CORSCORS - Enable Alfresco for CORS
CORS - Enable Alfresco for CORS
 
DEF CON 27 - BEN SADEGHIPOUR - owning the clout through ssrf and pdf generators
DEF CON 27 - BEN SADEGHIPOUR  - owning the clout through ssrf and pdf generatorsDEF CON 27 - BEN SADEGHIPOUR  - owning the clout through ssrf and pdf generators
DEF CON 27 - BEN SADEGHIPOUR - owning the clout through ssrf and pdf generators
 
Secure java script-for-developers
Secure java script-for-developersSecure java script-for-developers
Secure java script-for-developers
 

Similar to JavaScript Security: Mastering Cross Domain Communications in complex JS applications

Message in a Bottle
Message in a BottleMessage in a Bottle
Message in a BottleZohar Arad
 
Krzysztof Kotowicz - Hacking HTML5
Krzysztof Kotowicz - Hacking HTML5Krzysztof Kotowicz - Hacking HTML5
Krzysztof Kotowicz - Hacking HTML5DefconRussia
 
White paper screen
White paper screenWhite paper screen
White paper screeneltincho89
 
WebAppSec Updates from W3C
WebAppSec Updates from W3CWebAppSec Updates from W3C
WebAppSec Updates from W3CNatasha Rooney
 
Security enforcement of Java Microservices with Apiman & Keycloak
Security enforcement of Java Microservices with Apiman & KeycloakSecurity enforcement of Java Microservices with Apiman & Keycloak
Security enforcement of Java Microservices with Apiman & KeycloakCharles Moulliard
 
Cross Origin Resource Sharing (CORS) - Azizul Hakim
Cross Origin Resource Sharing (CORS) - Azizul HakimCross Origin Resource Sharing (CORS) - Azizul Hakim
Cross Origin Resource Sharing (CORS) - Azizul HakimCefalo
 
WebCamp: Developer Day: Web Security: Cookies, Domains and CORS - Юрий Чайков...
WebCamp: Developer Day: Web Security: Cookies, Domains and CORS - Юрий Чайков...WebCamp: Developer Day: Web Security: Cookies, Domains and CORS - Юрий Чайков...
WebCamp: Developer Day: Web Security: Cookies, Domains and CORS - Юрий Чайков...GeeksLab Odessa
 
XST - Cross Site Tracing
XST - Cross Site TracingXST - Cross Site Tracing
XST - Cross Site TracingMagno Logan
 
W3 conf hill-html5-security-realities
W3 conf hill-html5-security-realitiesW3 conf hill-html5-security-realities
W3 conf hill-html5-security-realitiesBrad Hill
 
Hacking HTML5 offensive course (Zeronights edition)
Hacking HTML5 offensive course (Zeronights edition)Hacking HTML5 offensive course (Zeronights edition)
Hacking HTML5 offensive course (Zeronights edition)Krzysztof Kotowicz
 
JSON based CSRF
JSON based CSRFJSON based CSRF
JSON based CSRFAmit Dubey
 
Evolution Of Web Security
Evolution Of Web SecurityEvolution Of Web Security
Evolution Of Web SecurityChris Shiflett
 
Pentesting web applications
Pentesting web applicationsPentesting web applications
Pentesting web applicationsSatish b
 
JSFoo Chennai 2012
JSFoo Chennai 2012JSFoo Chennai 2012
JSFoo Chennai 2012Krishna T
 
Web Attacks - Top threats - 2010
Web Attacks - Top threats - 2010Web Attacks - Top threats - 2010
Web Attacks - Top threats - 2010Shreeraj Shah
 

Similar to JavaScript Security: Mastering Cross Domain Communications in complex JS applications (20)

Message in a Bottle
Message in a BottleMessage in a Bottle
Message in a Bottle
 
Browser Security
Browser SecurityBrowser Security
Browser Security
 
Krzysztof Kotowicz - Hacking HTML5
Krzysztof Kotowicz - Hacking HTML5Krzysztof Kotowicz - Hacking HTML5
Krzysztof Kotowicz - Hacking HTML5
 
White paper screen
White paper screenWhite paper screen
White paper screen
 
WebAppSec Updates from W3C
WebAppSec Updates from W3CWebAppSec Updates from W3C
WebAppSec Updates from W3C
 
Security enforcement of Java Microservices with Apiman & Keycloak
Security enforcement of Java Microservices with Apiman & KeycloakSecurity enforcement of Java Microservices with Apiman & Keycloak
Security enforcement of Java Microservices with Apiman & Keycloak
 
Cross Origin Resource Sharing (CORS) - Azizul Hakim
Cross Origin Resource Sharing (CORS) - Azizul HakimCross Origin Resource Sharing (CORS) - Azizul Hakim
Cross Origin Resource Sharing (CORS) - Azizul Hakim
 
WebCamp: Developer Day: Web Security: Cookies, Domains and CORS - Юрий Чайков...
WebCamp: Developer Day: Web Security: Cookies, Domains and CORS - Юрий Чайков...WebCamp: Developer Day: Web Security: Cookies, Domains and CORS - Юрий Чайков...
WebCamp: Developer Day: Web Security: Cookies, Domains and CORS - Юрий Чайков...
 
XST - Cross Site Tracing
XST - Cross Site TracingXST - Cross Site Tracing
XST - Cross Site Tracing
 
W3 conf hill-html5-security-realities
W3 conf hill-html5-security-realitiesW3 conf hill-html5-security-realities
W3 conf hill-html5-security-realities
 
Hacking HTML5 offensive course (Zeronights edition)
Hacking HTML5 offensive course (Zeronights edition)Hacking HTML5 offensive course (Zeronights edition)
Hacking HTML5 offensive course (Zeronights edition)
 
JSON based CSRF
JSON based CSRFJSON based CSRF
JSON based CSRF
 
Pushing the Web: Interesting things to Know
Pushing the Web: Interesting things to KnowPushing the Web: Interesting things to Know
Pushing the Web: Interesting things to Know
 
Evolution Of Web Security
Evolution Of Web SecurityEvolution Of Web Security
Evolution Of Web Security
 
Pentesting web applications
Pentesting web applicationsPentesting web applications
Pentesting web applications
 
AJAX Transport Layer
AJAX Transport LayerAJAX Transport Layer
AJAX Transport Layer
 
JSFoo Chennai 2012
JSFoo Chennai 2012JSFoo Chennai 2012
JSFoo Chennai 2012
 
Web Attacks - Top threats - 2010
Web Attacks - Top threats - 2010Web Attacks - Top threats - 2010
Web Attacks - Top threats - 2010
 
Copy of cgi
Copy of cgiCopy of cgi
Copy of cgi
 
Android and REST
Android and RESTAndroid and REST
Android and REST
 

Recently uploaded

08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 

Recently uploaded (20)

08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 

JavaScript Security: Mastering Cross Domain Communications in complex JS applications

  • 1. Berlin, 2018-01-01 JavaScript Security Mastering Cross Domain Communications in complex JS applications Grill.js Wrocław, 2018-08-18, 7pm <thomas.witt@infopark.com> @thomas_witt linkedin.com/in/thomaswitt Thomas Witt Co-Founder
  • 2.
  • 4. We're hiring! Boston · Berlin · Wrocław
  • 5.
  • 6.
  • 8. JS Applications need to exchange data with Backend APIs running on domains other than your own SECURELY
  • 9. Challange Only load code from trusted origins, don't execute malicious JS code, don't let people steal your data.
  • 10. Same Origin Policy For security reasons, browsers restrict cross- origin HTTP requests initiated from within scripts. For example, XMLHttpRequest and the Fetch API follow the same-origin policy. This means that a web application using those APIs can only request HTTP resources from the same origin the application was loaded from. – https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS “
  • 11. How to … Exchange data from JS applications with backend APIs
  • 12. Two ways how to talk to other services CORS postMessage
  • 14. Same Origin Policy A web application using those APIs can only request HTTP resources from the same origin the application was loaded from, unless the response from the other origin includes the right CORS headers. – https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS “
  • 16. Simple GET request via CORS var req = new XMLHttpRequest(); var url = 'http://bar.other/resources/public-data/'; function callOtherDomain() { if(req) { req.open('GET', url, true); req.onreadystatechange = handler; req.send(); } }
  • 17. Simple GET request via CORS var req = new XMLHttpRequest(); var url = 'http://bar.other/resources/public-data/'; function callOtherDomain() { if(req) { req.open('GET', url, true); req.onreadystatechange = handler; req.send(); } } GET /resources/public-data/ HTTP/1.1 Origin: http://foo.example HTTP/1.1 200 OK Access-Control-Allow-Origin: * Client (foo.example) Server (bar.other)
  • 18. The uglyness: Preflight Requests aka not-so-simple-requests
  • 19. Preflighted POST request via CORS var invocation = new XMLHttpRequest(); var url = 'http://bar.other/resources/post-here/'; var body = '<?xml version="1.0"?><person><name>Thomas Witt</name></person>'; function callOtherDomain(){ if(invocation) { invocation.open('POST', url, true); invocation.setRequestHeader('Content-Type', 'application/xml'); invocation.onreadystatechange = handler; invocation.send(body); } }
  • 20. Preflighted POST request via CORS - Overview Client (foo.example) Server (bar.other) OPTIONS /resources/post-here/ HTTP/1.1 Origin: http://foo.example Access-Control-Request-Method: POST Access-Control-Request-Headers: Content-Type HTTP/1.1 200 OK Access-Control-Allow-Origin: http://foo.example Access-Control-Allow-Methods: POST, GET Access-Control-Allow-Headers: Content-Type Access-Control-Max-Age: 86400 var invocation = new XMLHttpRequest(); var url = 'http://bar.other/resources/post-here/'; var body = '<?xml version="1.0"?><person><name>Thomas Witt</name></person>'; function callOtherDomain(){ if(invocation) { invocation.open('POST', url, true); invocation.setRequestHeader('Content-Type', 'application/xml'); invocation.onreadystatechange = handler; invocation.send(body); } } POST /resources/post-here/ HTTP/1.1 Content-Type: text/xml; charset=UTF-8 Origin: http://foo.example HTTP/1.1 200 OK Access-Control-Allow-Origin: http://foo.example PreflightPhaseMainRequestPhase
  • 21. For every new resource accessed,
 a preflight request will be issued.
  • 22.
  • 24. CORS vs CSP CORS CORS allows a server (bar.other) to give permission to a site (foo.example) to read (potentially private) data from a server (bar.other), using the visitor's browser and credentials. CSP CSP allows a site (foo.example) to prevent itself from loading (potentially malicious) content from unexpected sources (e.g. against XSS). GET /resources/public-data/ HTTP/1.1 Origin: http://foo.example HTTP/1.1 200 OK Access-Control-Allow-Origin: * Content-Security-Policy: base-uri 'none'; default- src 'self' 'unsafe-inline' data: https: wss:; object- src 'none'; script-src 'self' https://beta- api.scrivito.com; upgrade-insecure-requests;
  • 25. 0,133% of all 1M Alexa sites implement a CSP June 2015, "CSP adoption: current status and future prospects", Ming Ying / Shu Qin Li
  • 26. Example Response: www.scrivito.com (shortened) HTTP/1.1 200 OK Connection: keep-alive Content-Encoding: gzip Content-Security-Policy: base-uri 'none'; default-src 'self' 'unsafe-inline' data: https: wss:; object-src 'none'; script-src 'self' https://assets.scrivito.com https://beta-api.scrivito.com https:// maps.googleapis.com https://www.google-analytics.com; upgrade-insecure-requests; Content-Type: text/html; charset=UTF-8 Date: Wed, 18 Aug 2018 19:00:00 GMT
  • 28. CSP Directives https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src <script> <img> <link rel="stylesheet"> <style> <audio> <video> <iframe> @font-face WebSocket, XMLHttpRequest, EventSource <embed> <object>
  • 29. script-src Values https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src self unsafe-inline unsafe-eval * none my.url.com <script src="/public/mylib.js" /> <script> alert('Hello JavaScript!'); </script> setTimeout(); eval(); All of it None of it Space-separated (*.js.com | api.js.com | https: | https://api.js.com | data:)
  • 33. Our typical CSP Content-Security-Policy: base-uri 'none'; default-src 'self' https: wss:; script-src 'self' https://api.scrivito.com https://assets.scrivito.com https://www.google-analytics.com https://maps.googleapis.com https://whatever.service.you.need.com; object-src 'none'; upgrade-insecure-requests;
  • 36. It will most likely break your site At the first try
  • 37. script-src is most important
  • 40. CSP v1 Browser Support https://caniuse.com/#search=csp
  • 41. CSP - further reading developer.mozilla.org/docs/Web/HTTP/CSP content-security-policy.com csp-evaluator.withgoogle.com cspvalidator.org caniuse.com/#feat=contentsecuritypolicy
  • 43. Cross-domain communication via window.postMessage <iframe name="receiver" src="https://bar.other/my.js"> <script> let win = window.frames.receiver; win.postMessage("message", "https://bar.other"); </script> window.addEventListener("message", function(event) { if (event.origin != 'https://foo.example') { // Unknown domain? Ignore! return; } alert( "Rcvd: " + event.data ); }); Sender (foo.example) Receiver (bar.other)
  • 45. window.postMessage vs CORS/CSP Advantages CORS is not very simple, postMessage is No pre-flight requests No need to modify HTTP headers Not convinced? Google uses it as well in it's Google API JS SDK <iframe name="receiver" src="https://bar.other/my.js"> <script> let win = window.frames.receiver; win.postMessage("message", "https://bar.other"); </script> window.addEventListener("message", function(event) { if (event.origin != 'https://foo.example') { // Unknown domain? Ignore! return; } alert( "Rcvd: " + event.data ); });
  • 46. window.postMessage Security Security caveats No side can figure out whether malicious code has been inserted via XSS! Check-List Does the browser support postMessage? Is the message origin correct and known? Is the message data sanitized and validated? Are origins matched using strict equality
 (no indexOf(".foo.com") > 0)? Are messages sent without using wildcards in the origin? <iframe name="receiver" src="https://bar.other/my.js"> <script> let win = window.frames.receiver; win.postMessage("message", "https://bar.other"); </script> window.addEventListener("message", function(event) { if (event.origin != 'https://foo.example') { // Unknown domain? Ignore! return; } alert( "Rcvd: " + event.data ); });
  • 48. Xdomain A pure JavaScript CORS alternative. No server configuration required - just add a proxy.html on the domain you wish to communicate with. – https://github.com/jpillora/xdomain “
  • 49. window.postMessage - further reading developer.mozilla.org/docs/Web/API/Window/postMessage seclab.stanford.edu/websec/frames/post-message.pdf labs.detectify.com/2016/12/08/the-pitfalls-of-postmessage/ caniuse.com/#feat=x-doc-messaging
  • 52. Use postMessage instead of CORS when implementing Cross Domain Communication.
  • 53. There's one more thing…
  • 54. Bonus Tip #2: HSTS (You use TLS, right?)
  • 55. Example Response: www.scrivito.com HTTP/1.1 200 OK Age: 83186 Cache-Control: public, max-age=0, must-revalidate Connection: keep-alive Content-Encoding: gzip Content-Length: 1313 Content-Security-Policy: base-uri 'none'; default-src 'self' 'unsafe-inline' data: https: wss:; object-src 'none'; script-src 'self' https://assets.scrivito.com https://beta-api.scrivito.com https:// maps.googleapis.com https://www.google-analytics.com; upgrade-insecure-requests; Content-Type: text/html; charset=UTF-8 Date: Wed, 15 Aug 2018 12:59:51 GMT Etag: "7cbc5a14104f9d58b476b606e830533b-ssl-df" Server: Netlify Strict-Transport-Security: max-age=31536000 Vary: Accept-Encoding
  • 58. Can I haz question, please?