SlideShare a Scribd company logo
Web Security
Cookies, Domains and CORS
Perfectial, LLC
info@perfectial.com
What’s all about?
● Same-origin policy
● Cross domain requests use-cases
● Making requests with XHTTPRequest
● CSRF attacks
● Simple and not-so-simple requests
● Cross-domain limitations & Access Control
● Back-end implementation examples
● Limitation in Internet Explorer 8, 9
● Workarounds (proxy, JSONP)
● Content Security Policy
URL1 origin = URL2 origin ⇔
scheme, host and port are
equal
Exceptions:
• link
• img
• iframe
• object
• script
http://en.wikipedia.org/wiki/Same-origin_policy
http://
username:pass@
sub.domain.com
:8080
/folder/index.html
?id=42&action=add
#first-section
URI
↓
URL
scheme
authorization
host
port
path
query
fragment id
http://username:pass@sub.domain.com:8080/folder/index.html?id=42&actio
n=add#first-section
Same-origin
policy
• Share buttons
• Visitors analytics
• Advertisments
• Maps
• Payment systems
• REST API
• Shared services
Use cases
Requests with XHTTPRequest 2
Plain JavaScript
var xhr = new XMLHttpRequest();
xhr.addEventListener("load", transferSuccessful, false);
xhr.open(method, url, async, user, password);
xhr.send(data);
//for compatibility with XHTTPRequest v1
xhr.onreadystatechange = function (req) {
if (req.readyState != 4) return;
if (req.status == 200 || req.status == 304) {
promise.success([req]);
} else {
promise.fail([req]);
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
Requests with XHTTPRequest 2 - Events
Plain JavaScript
var xhr = new XMLHttpRequest();
xhr.addEventListener("progress" , updateProgress , false);
xhr.addEventListener("error" , transferFailed , false);
xhr.addEventListener("abort" , transferCanceled , false);
xhr.addEventListener("load" , transferSuccessful , false);
xhr.addEventListener("loadstart", transferStart , false);
xhr.addEventListener("loadend" , transferEnd , false);
xhr.addEventListener("timeout" , transferTimeout , false);
xhr.withCredentials = true;
xhr.open(method, url, async, user, password);
xhr.send(data);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Requests with XHTTPRequest 2
jQuery
$.ajax(url, {
xhrFields: {
withCredentials: true
}
})
.done(callback);
//Persistent:
$.ajaxPrefilter( function( options, originalOptions, jqXHR ) {
options.xhrFields = {
withCredentials: true
};
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
Requests with XHTTPRequest 2
AngularJS
myApp.config(['$httpProvider', function ($httpProvider) {
$httpProvider.defaults.withCredentials = true;
$httpProvider.defaults.useXDomain = true;
delete $httpP~.defaults.headers.common['X-Requested-With'];
}]);
1
2
3
4
5
6
7
8
9
Hacking time!
What’s all about?
● Same-origin policy
● Cross domain requests use-cases
● Making requests with XHTTPRequest
● CSRF attacks
● Simple and not-so-simple requests
● Cross-domain limitations & Access Control
● Back-end implementation examples
● Limitation in Internet Explorer 8, 9
● Workarounds (proxy, JSONP)
● Content Security Policy
• Only GET, HEAD or POST
• No custom headers
• Content-Type only
application/x-www-form-urlencoded,
multipart/form-data, or text/plain
• All other will have
preflighted request
Not-so-simple and
simple requests
http OPTIONS (Origin: http://example.com:81)
200 Access-Control-Allow- ...
direct GET/POST/PUT/DELETE request
as allowed by access headers
preflightedapplication
• Request always contains an
Origin
• Allow-Origin can be * for
read requests
• For modify requests it should
be set manually
• Allow-Origin can’t be * with
Allow-Credentials: true
Access-Control
headers
Origin: origin
Access-Control-Request-Method: put
Access-Control-Request-Headers: …
Access-Control-Allow-Origin: origin | *
Access-Control-Max-Age: 300
Access-Control-Allow-Credentials: bool
Access-Control-Allow-Methods: put, get
Access-Control-Allow-Headers: …
Access-Control-Expose-Headers: …
preflighted
requestresponse
http://www.html5rocks.com/en/tutorials/cors/
• Have white list of origins
• If not possible use X-
CSRF-Token
Prevent attacks
set header X-CSRF-Token
previous
request
next
request
return X-CSRF-Token
server
validation
server response with new X-CSRF-
Token
http://mircozeiss.com/using-csrf-with-express-
and-angular/
What’s all about?
● Same-origin policy
● Cross domain requests use-cases
● Making requests with XHTTPRequest
● CSRF attacks
● Simple and not-so-simple requests
● Cross-domain limitations & Access Control
● Back-end implementation examples
● Limitation in Internet Explorer 8, 9
● Workarounds (proxy, JSONP)
● Content Security Policy
Back-end implementation
.Net
// library Thinktecture
public static void Register(HttpConfiguration config){
var corsConfig = new WebApiCorsConfiguration();
corsConfig.RegisterGlobal(config);
corsConfig.ForAll().AllowAll();
}
//more details:
//http://brockallen.com/2012/06/28/cors-support-in-webapi-mvc-
and-iis-with-thinktecture-identitymodel/
1
2
3
4
5
6
7
8
9
10
11
12
13
14
Back-end implementation
Ruby
module YourProjectName
class Application < Rails::Application
......
config.action_dispatch.default_headers = {
"Access-Control-Allow-Origin" => "*",
"Access-Control-Allow-Methods" => "PUT, GET, POST, DELETE,
OPTION",
"Access-Control-Allow-Headers" => "Origin, X-Requested-With,
X-File-Name, Content-Type,
Cache-Control, X-CSRF-Token,
Accept",
"Access-Control-Allow-Credentials" => "true",
"Access-Control-Max-Age" => "1728000"
}
......
end
end
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
• Most probably you will
never need it, but in case
flowchart is under link
below
Manual
implementation
http://www.html5rocks.com/en/tutorials/cors/
What’s all about?
● Same-origin policy
● Cross domain requests use-cases
● Making requests with XHTTPRequest
● CSRF attacks
● Simple and not-so-simple requests
● Cross-domain limitations & Access Control
● Back-end implementation examples
● Limitation in Internet Explorer 8, 9
● Workarounds (proxy, JSONP)
● Content Security Policy
• IE ≤ 7 is not a browser
• IE10+ is already a browser
• IE8-9 can be handled with
XDomainRequest
Most loved browser
Limitation in Internet Explorer 8, 9
Feature detection
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
//"withCredentials" only exists on XMLHTTPRequest2 objects
xhr.open(method, url, async, user, password);
} else if (typeof XDomainRequest != "undefined") {
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
//Otherwise, CORS is not supported by the browser
xhr = null;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
1. The target URL must be accessed using only the methods GET and
POST
2. No custom headers may be added to the request
3. Only text/plain is supported for the request's Content-Type header
4. No authentication or cookies will be sent with the request
5. Requests must be targeted to the same scheme as the hosting page
6. The target URL must be accessed using the HTTP or HTTPS protocols
7. Requests targeted to Intranet URLs may only be made from the Intranet
Zone
Limitation in Internet Explorer 8, 9
Things to remember
http://blogs.msdn.com/b/ieinternals/archive/2010/05/13/xdomainrequest-restrictions-limitations-and-workarounds.aspx
Third party services
Proxy
Client
Workarounds
Workarounds
JSONP Concept
<script src="http://3rd-party.com/api/v1/users/27"></script>
#responce from http://3rd-party.com/api/v1/users/27:
callbackFn({"id":1,
"name":"Jack",
"email":"jack@perfectial.com",
"startDate":"2010-01-01T12:00:00",
"endDate":null,
"vacationRate":1.67,
"admin":true,
"defaultRecipient":true,
"userRequestCount":0,
"requestToUserCount":0
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
Workarounds
JSONP with jQuery
<script src="http://3rd-party.com/api/v1/users/27"></script>
$.ajax("http://3rd-party.com/api/v1/users/27", {
"crossDomain": true,
"dataType" : "jsonp"
});
#request URL will be:
http://3rd-
party.com/api/v1/users/27?callback=jQuery111008519500948023051_139817
7525599&_=1398177525600
#responce from http://3rd-party.com/api/v1/users/27:
jQuery111008519500948023051_1398177525599({
"id":1,
"name":"Jack",
"email":"jack@perfectial.com",
...
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
Workarounds
JSONP Limitations
● JavaScript Object Notation is for read, not eval.
● Can’t add custom headers.
● Require ability to modify backend.
● Only GET method.
Workarounds... kind of
Document messaging
window.addEventListener("message", function(event){
if (event.origin !== "http://example.org"){
return;
}
}, false);
window.parent.postMessage("Hi there!", "http://example.org");
1
2
3
4
5
6
7
8
9
10
https://developer.mozilla.org/en-US/docs/Web/API/Window.postMessage
What’s all about?
● Same-origin policy
● Cross domain requests use-cases
● Making requests with XHTTPRequest
● CSRF attacks
● Simple and not-so-simple requests
● Cross-domain limitations & Access Control
● Back-end implementation examples
● Limitation in Internet Explorer 8, 9
● Workarounds (proxy, JSONP)
● Content Security Policy
• Only latest browsers
• With prefix 'X-' in IE10-11
• Inline script won’t work
• eval() too
• Report and Report-Only
https://www.youtube.com/watch?v=C2x1jEekf3g
http://www.html5rocks.com/en/tutorials/security/cont
ent-security-policy/
http://en.wikipedia.org/wiki/Content_Security_Policy
Content Security
PolicyContent-Security-Policy:
default-src 'unsafe-eval' 'unsafe-inline';
connect-src 'none';
font-src https://themes.googleusercontent.com;
frame-src 'self';
img-src http://cdn.example.com/;
media-src http://cdn.example.com/;
object-src http://cdn.example.com/;
style-src http://cdn.example.com/;
script-src 'self';
report-uri /csp_report_parser;
© 2014 Yura Chaikovsky
Perfectial, LLC
http://perfectial.com
info@perfectial.com

More Related Content

PDF
Cross site calls with javascript - the right way with CORS
PDF
CORS and (in)security
PPTX
CORS - Enable Alfresco for CORS
PPTX
Misconfigured CORS, Why being secure isn't getting easier. AppSec USA 2016
PDF
Cross-domain requests with CORS
PDF
Cross Origin Resource Sharing
PPTX
Browsers_SameOriginPolicy_CORS_ContentSecurityPolicy
PPT
Same origin policy
Cross site calls with javascript - the right way with CORS
CORS and (in)security
CORS - Enable Alfresco for CORS
Misconfigured CORS, Why being secure isn't getting easier. AppSec USA 2016
Cross-domain requests with CORS
Cross Origin Resource Sharing
Browsers_SameOriginPolicy_CORS_ContentSecurityPolicy
Same origin policy

What's hot (19)

PDF
RESTful Web Services
PPTX
Evolution Of The Web Platform & Browser Security
PPTX
01. http basics v27
PDF
Krzysztof Kotowicz - Hacking HTML5
PDF
Advanced Chrome extension exploitation
PPT
Comparative Development Methodologies
PDF
Your rest api using laravel
PDF
JavaScript Security: Mastering Cross Domain Communications in complex JS appl...
PDF
htaccess
PPT
Web Browsers And Other Mistakes
PDF
Building Awesome APIs with Lumen
ODP
PHP BASIC PRESENTATION
PDF
Cross Origin Communication (CORS)
PDF
distributing over the web
PPTX
Introduction to asp.net web api
PDF
Connecting to Web Services on Android
PPTX
Demystifying REST
PPT
KMUTNB - Internet Programming 2/7
PPT
HTTP protocol and Streams Security
RESTful Web Services
Evolution Of The Web Platform & Browser Security
01. http basics v27
Krzysztof Kotowicz - Hacking HTML5
Advanced Chrome extension exploitation
Comparative Development Methodologies
Your rest api using laravel
JavaScript Security: Mastering Cross Domain Communications in complex JS appl...
htaccess
Web Browsers And Other Mistakes
Building Awesome APIs with Lumen
PHP BASIC PRESENTATION
Cross Origin Communication (CORS)
distributing over the web
Introduction to asp.net web api
Connecting to Web Services on Android
Demystifying REST
KMUTNB - Internet Programming 2/7
HTTP protocol and Streams Security
Ad

Viewers also liked (20)

PPTX
ALICE IN WASTELAND
PDF
Ng init | EPI Sousse
PDF
Twitter bootstrap | JCertif Tunisie
PPTX
school objects 2015
PPTX
LE ORCHIDEE: DAL DNA AL FIORE
PPTX
Sea Animals
PPTX
Esperimento 1
PPT
Проектирование мероприятий. Лариса Малышева для I_Love_Events.conf
ODP
Pictures m pp
PPTX
Quale pannello?
PPTX
Siamo la terra del sole, non la terra dei fuochi
PPT
Capire il mondo con la matematica
PDF
wordpress-maintenance
PPT
Sopravvivenza nello spazio
PPT
Alla scoperta di Marte
PPT
Space life
PPTX
Событийный маркетинг: заблуждение века. Денис Снетков для I_Love_Events.conf
PPTX
ET chiama Terra
PPTX
Illuminazione artificiale
PPTX
Letter T!
ALICE IN WASTELAND
Ng init | EPI Sousse
Twitter bootstrap | JCertif Tunisie
school objects 2015
LE ORCHIDEE: DAL DNA AL FIORE
Sea Animals
Esperimento 1
Проектирование мероприятий. Лариса Малышева для I_Love_Events.conf
Pictures m pp
Quale pannello?
Siamo la terra del sole, non la terra dei fuochi
Capire il mondo con la matematica
wordpress-maintenance
Sopravvivenza nello spazio
Alla scoperta di Marte
Space life
Событийный маркетинг: заблуждение века. Денис Снетков для I_Love_Events.conf
ET chiama Terra
Illuminazione artificiale
Letter T!
Ad

Similar to Web Security - Cookies, Domains and CORS (20)

PDF
WebCamp: Developer Day: Web Security: Cookies, Domains and CORS - Юрий Чайков...
ODP
CONFidence 2014: Kiss, Zagon, Sseller: Scaling security
PDF
Going Beyond Cross Domain Boundaries (jQuery Bulgaria)
PDF
Javascript cross domain communication
PPTX
JSON based CSRF
PDF
The Same-Origin Policy
PPTX
Web api 2 With MVC 5 With TrainerKrunal
PPTX
Cross Origin Resource Sharing (CORS) - Azizul Hakim
PPTX
Browser Internals-Same Origin Policy
PDF
AJAX Transport Layer
PPTX
Html cors
PDF
Cors kung fu
PDF
Cors michael
PPTX
Stay Out Please
PDF
Advanced I/O in browser
PDF
CORS in Action Creating and consuming cross origin APIs 1st Edition Monsur Ho...
PPTX
Unit-5.pptx
PPTX
Conquering CORS. Taming Cross-Origin Resource Sharing.
PPT
Breaking The Cross Domain Barrier
WebCamp: Developer Day: Web Security: Cookies, Domains and CORS - Юрий Чайков...
CONFidence 2014: Kiss, Zagon, Sseller: Scaling security
Going Beyond Cross Domain Boundaries (jQuery Bulgaria)
Javascript cross domain communication
JSON based CSRF
The Same-Origin Policy
Web api 2 With MVC 5 With TrainerKrunal
Cross Origin Resource Sharing (CORS) - Azizul Hakim
Browser Internals-Same Origin Policy
AJAX Transport Layer
Html cors
Cors kung fu
Cors michael
Stay Out Please
Advanced I/O in browser
CORS in Action Creating and consuming cross origin APIs 1st Edition Monsur Ho...
Unit-5.pptx
Conquering CORS. Taming Cross-Origin Resource Sharing.
Breaking The Cross Domain Barrier

Recently uploaded (20)

PDF
project resource management chapter-09.pdf
PDF
A comparative study of natural language inference in Swahili using monolingua...
PPTX
TLE Review Electricity (Electricity).pptx
PDF
NewMind AI Weekly Chronicles - August'25-Week II
PDF
DASA ADMISSION 2024_FirstRound_FirstRank_LastRank.pdf
PPTX
Tartificialntelligence_presentation.pptx
PDF
Enhancing emotion recognition model for a student engagement use case through...
PDF
Approach and Philosophy of On baking technology
PPTX
OMC Textile Division Presentation 2021.pptx
PPTX
Group 1 Presentation -Planning and Decision Making .pptx
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
A novel scalable deep ensemble learning framework for big data classification...
PDF
WOOl fibre morphology and structure.pdf for textiles
PPTX
SOPHOS-XG Firewall Administrator PPT.pptx
PPTX
Chapter 5: Probability Theory and Statistics
PPTX
A Presentation on Artificial Intelligence
PDF
Univ-Connecticut-ChatGPT-Presentaion.pdf
PPTX
cloud_computing_Infrastucture_as_cloud_p
PDF
Video forgery: An extensive analysis of inter-and intra-frame manipulation al...
PPTX
Programs and apps: productivity, graphics, security and other tools
project resource management chapter-09.pdf
A comparative study of natural language inference in Swahili using monolingua...
TLE Review Electricity (Electricity).pptx
NewMind AI Weekly Chronicles - August'25-Week II
DASA ADMISSION 2024_FirstRound_FirstRank_LastRank.pdf
Tartificialntelligence_presentation.pptx
Enhancing emotion recognition model for a student engagement use case through...
Approach and Philosophy of On baking technology
OMC Textile Division Presentation 2021.pptx
Group 1 Presentation -Planning and Decision Making .pptx
Digital-Transformation-Roadmap-for-Companies.pptx
A novel scalable deep ensemble learning framework for big data classification...
WOOl fibre morphology and structure.pdf for textiles
SOPHOS-XG Firewall Administrator PPT.pptx
Chapter 5: Probability Theory and Statistics
A Presentation on Artificial Intelligence
Univ-Connecticut-ChatGPT-Presentaion.pdf
cloud_computing_Infrastucture_as_cloud_p
Video forgery: An extensive analysis of inter-and intra-frame manipulation al...
Programs and apps: productivity, graphics, security and other tools

Web Security - Cookies, Domains and CORS

  • 1. Web Security Cookies, Domains and CORS Perfectial, LLC info@perfectial.com
  • 2. What’s all about? ● Same-origin policy ● Cross domain requests use-cases ● Making requests with XHTTPRequest ● CSRF attacks ● Simple and not-so-simple requests ● Cross-domain limitations & Access Control ● Back-end implementation examples ● Limitation in Internet Explorer 8, 9 ● Workarounds (proxy, JSONP) ● Content Security Policy
  • 3. URL1 origin = URL2 origin ⇔ scheme, host and port are equal Exceptions: • link • img • iframe • object • script http://en.wikipedia.org/wiki/Same-origin_policy http:// username:pass@ sub.domain.com :8080 /folder/index.html ?id=42&action=add #first-section URI ↓ URL scheme authorization host port path query fragment id http://username:pass@sub.domain.com:8080/folder/index.html?id=42&actio n=add#first-section Same-origin policy
  • 4. • Share buttons • Visitors analytics • Advertisments • Maps • Payment systems • REST API • Shared services Use cases
  • 5. Requests with XHTTPRequest 2 Plain JavaScript var xhr = new XMLHttpRequest(); xhr.addEventListener("load", transferSuccessful, false); xhr.open(method, url, async, user, password); xhr.send(data); //for compatibility with XHTTPRequest v1 xhr.onreadystatechange = function (req) { if (req.readyState != 4) return; if (req.status == 200 || req.status == 304) { promise.success([req]); } else { promise.fail([req]); } }; 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
  • 6. Requests with XHTTPRequest 2 - Events Plain JavaScript var xhr = new XMLHttpRequest(); xhr.addEventListener("progress" , updateProgress , false); xhr.addEventListener("error" , transferFailed , false); xhr.addEventListener("abort" , transferCanceled , false); xhr.addEventListener("load" , transferSuccessful , false); xhr.addEventListener("loadstart", transferStart , false); xhr.addEventListener("loadend" , transferEnd , false); xhr.addEventListener("timeout" , transferTimeout , false); xhr.withCredentials = true; xhr.open(method, url, async, user, password); xhr.send(data); 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
  • 7. Requests with XHTTPRequest 2 jQuery $.ajax(url, { xhrFields: { withCredentials: true } }) .done(callback); //Persistent: $.ajaxPrefilter( function( options, originalOptions, jqXHR ) { options.xhrFields = { withCredentials: true }; }); 1 2 3 4 5 6 7 8 9 10 11 12 13 14
  • 8. Requests with XHTTPRequest 2 AngularJS myApp.config(['$httpProvider', function ($httpProvider) { $httpProvider.defaults.withCredentials = true; $httpProvider.defaults.useXDomain = true; delete $httpP~.defaults.headers.common['X-Requested-With']; }]); 1 2 3 4 5 6 7 8 9
  • 10. What’s all about? ● Same-origin policy ● Cross domain requests use-cases ● Making requests with XHTTPRequest ● CSRF attacks ● Simple and not-so-simple requests ● Cross-domain limitations & Access Control ● Back-end implementation examples ● Limitation in Internet Explorer 8, 9 ● Workarounds (proxy, JSONP) ● Content Security Policy
  • 11. • Only GET, HEAD or POST • No custom headers • Content-Type only application/x-www-form-urlencoded, multipart/form-data, or text/plain • All other will have preflighted request Not-so-simple and simple requests http OPTIONS (Origin: http://example.com:81) 200 Access-Control-Allow- ... direct GET/POST/PUT/DELETE request as allowed by access headers preflightedapplication
  • 12. • Request always contains an Origin • Allow-Origin can be * for read requests • For modify requests it should be set manually • Allow-Origin can’t be * with Allow-Credentials: true Access-Control headers Origin: origin Access-Control-Request-Method: put Access-Control-Request-Headers: … Access-Control-Allow-Origin: origin | * Access-Control-Max-Age: 300 Access-Control-Allow-Credentials: bool Access-Control-Allow-Methods: put, get Access-Control-Allow-Headers: … Access-Control-Expose-Headers: … preflighted requestresponse http://www.html5rocks.com/en/tutorials/cors/
  • 13. • Have white list of origins • If not possible use X- CSRF-Token Prevent attacks set header X-CSRF-Token previous request next request return X-CSRF-Token server validation server response with new X-CSRF- Token http://mircozeiss.com/using-csrf-with-express- and-angular/
  • 14. What’s all about? ● Same-origin policy ● Cross domain requests use-cases ● Making requests with XHTTPRequest ● CSRF attacks ● Simple and not-so-simple requests ● Cross-domain limitations & Access Control ● Back-end implementation examples ● Limitation in Internet Explorer 8, 9 ● Workarounds (proxy, JSONP) ● Content Security Policy
  • 15. Back-end implementation .Net // library Thinktecture public static void Register(HttpConfiguration config){ var corsConfig = new WebApiCorsConfiguration(); corsConfig.RegisterGlobal(config); corsConfig.ForAll().AllowAll(); } //more details: //http://brockallen.com/2012/06/28/cors-support-in-webapi-mvc- and-iis-with-thinktecture-identitymodel/ 1 2 3 4 5 6 7 8 9 10 11 12 13 14
  • 16. Back-end implementation Ruby module YourProjectName class Application < Rails::Application ...... config.action_dispatch.default_headers = { "Access-Control-Allow-Origin" => "*", "Access-Control-Allow-Methods" => "PUT, GET, POST, DELETE, OPTION", "Access-Control-Allow-Headers" => "Origin, X-Requested-With, X-File-Name, Content-Type, Cache-Control, X-CSRF-Token, Accept", "Access-Control-Allow-Credentials" => "true", "Access-Control-Max-Age" => "1728000" } ...... end end 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
  • 17. • Most probably you will never need it, but in case flowchart is under link below Manual implementation http://www.html5rocks.com/en/tutorials/cors/
  • 18. What’s all about? ● Same-origin policy ● Cross domain requests use-cases ● Making requests with XHTTPRequest ● CSRF attacks ● Simple and not-so-simple requests ● Cross-domain limitations & Access Control ● Back-end implementation examples ● Limitation in Internet Explorer 8, 9 ● Workarounds (proxy, JSONP) ● Content Security Policy
  • 19. • IE ≤ 7 is not a browser • IE10+ is already a browser • IE8-9 can be handled with XDomainRequest Most loved browser
  • 20. Limitation in Internet Explorer 8, 9 Feature detection var xhr = new XMLHttpRequest(); if ("withCredentials" in xhr) { //"withCredentials" only exists on XMLHTTPRequest2 objects xhr.open(method, url, async, user, password); } else if (typeof XDomainRequest != "undefined") { xhr = new XDomainRequest(); xhr.open(method, url); } else { //Otherwise, CORS is not supported by the browser xhr = null; } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
  • 21. 1. The target URL must be accessed using only the methods GET and POST 2. No custom headers may be added to the request 3. Only text/plain is supported for the request's Content-Type header 4. No authentication or cookies will be sent with the request 5. Requests must be targeted to the same scheme as the hosting page 6. The target URL must be accessed using the HTTP or HTTPS protocols 7. Requests targeted to Intranet URLs may only be made from the Intranet Zone Limitation in Internet Explorer 8, 9 Things to remember http://blogs.msdn.com/b/ieinternals/archive/2010/05/13/xdomainrequest-restrictions-limitations-and-workarounds.aspx
  • 23. Workarounds JSONP Concept <script src="http://3rd-party.com/api/v1/users/27"></script> #responce from http://3rd-party.com/api/v1/users/27: callbackFn({"id":1, "name":"Jack", "email":"jack@perfectial.com", "startDate":"2010-01-01T12:00:00", "endDate":null, "vacationRate":1.67, "admin":true, "defaultRecipient":true, "userRequestCount":0, "requestToUserCount":0 }); 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
  • 24. Workarounds JSONP with jQuery <script src="http://3rd-party.com/api/v1/users/27"></script> $.ajax("http://3rd-party.com/api/v1/users/27", { "crossDomain": true, "dataType" : "jsonp" }); #request URL will be: http://3rd- party.com/api/v1/users/27?callback=jQuery111008519500948023051_139817 7525599&_=1398177525600 #responce from http://3rd-party.com/api/v1/users/27: jQuery111008519500948023051_1398177525599({ "id":1, "name":"Jack", "email":"jack@perfectial.com", ... }); 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
  • 25. Workarounds JSONP Limitations ● JavaScript Object Notation is for read, not eval. ● Can’t add custom headers. ● Require ability to modify backend. ● Only GET method.
  • 26. Workarounds... kind of Document messaging window.addEventListener("message", function(event){ if (event.origin !== "http://example.org"){ return; } }, false); window.parent.postMessage("Hi there!", "http://example.org"); 1 2 3 4 5 6 7 8 9 10 https://developer.mozilla.org/en-US/docs/Web/API/Window.postMessage
  • 27. What’s all about? ● Same-origin policy ● Cross domain requests use-cases ● Making requests with XHTTPRequest ● CSRF attacks ● Simple and not-so-simple requests ● Cross-domain limitations & Access Control ● Back-end implementation examples ● Limitation in Internet Explorer 8, 9 ● Workarounds (proxy, JSONP) ● Content Security Policy
  • 28. • Only latest browsers • With prefix 'X-' in IE10-11 • Inline script won’t work • eval() too • Report and Report-Only https://www.youtube.com/watch?v=C2x1jEekf3g http://www.html5rocks.com/en/tutorials/security/cont ent-security-policy/ http://en.wikipedia.org/wiki/Content_Security_Policy Content Security PolicyContent-Security-Policy: default-src 'unsafe-eval' 'unsafe-inline'; connect-src 'none'; font-src https://themes.googleusercontent.com; frame-src 'self'; img-src http://cdn.example.com/; media-src http://cdn.example.com/; object-src http://cdn.example.com/; style-src http://cdn.example.com/; script-src 'self'; report-uri /csp_report_parser;
  • 29. © 2014 Yura Chaikovsky Perfectial, LLC http://perfectial.com info@perfectial.com