webcamp: developer day: web security: cookies, domains and cors - Юрий Чайковский
DESCRIPTION
Web Security: Cookies, Domains and CORS Юрий Чайковский О предложенном еще в 1995 году и актуальным до сегодняшнего дня принципе одинакового источника (Same-origin policy) и о применении и ограничениях при междоменных запросах. Пример CSRF атак, а также правила конфигурации сервера для защиты от них. О последних нововведениях, касающихся контроля происхождения контента для предотвращения XSS атак. Кроме того: - Принцип одинакового источника. - Использование междоменных запросов. - CSRF атаки (с демонстрацией). - Классификация браузерных запросов. - Ограничения междоменных запросов. - Серверный контроль доступа. - Особенности Internet Explorer 8, 9. - Принцип безопасности контента (CSP).TRANSCRIPT
![Page 1: WebCamp: Developer Day: Web Security: Cookies, Domains and CORS - Юрий Чайковский](https://reader031.vdocuments.mx/reader031/viewer/2022020218/5591d59a1a28aba82a8b45d8/html5/thumbnails/1.jpg)
Web Security Cookies, Domains and CORS
4/2014, Yura Chaikovsky
![Page 2: WebCamp: Developer Day: Web Security: Cookies, Domains and CORS - Юрий Чайковский](https://reader031.vdocuments.mx/reader031/viewer/2022020218/5591d59a1a28aba82a8b45d8/html5/thumbnails/2.jpg)
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
![Page 3: WebCamp: Developer Day: Web Security: Cookies, Domains and CORS - Юрий Чайковский](https://reader031.vdocuments.mx/reader031/viewer/2022020218/5591d59a1a28aba82a8b45d8/html5/thumbnails/3.jpg)
Same-origin 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:[email protected]:8080/folder/index.html?id=42&action=add#first-section
![Page 4: WebCamp: Developer Day: Web Security: Cookies, Domains and CORS - Юрий Чайковский](https://reader031.vdocuments.mx/reader031/viewer/2022020218/5591d59a1a28aba82a8b45d8/html5/thumbnails/4.jpg)
Use cases
§ Share buttons
§ Visitors analytics
§ Advertisments
§ Maps
§ Payment systems
§ REST API
§ Shared services
![Page 5: WebCamp: Developer Day: Web Security: Cookies, Domains and CORS - Юрий Чайковский](https://reader031.vdocuments.mx/reader031/viewer/2022020218/5591d59a1a28aba82a8b45d8/html5/thumbnails/5.jpg)
Requests with XHTTPRequest 2 Plain JavaScript
CODE
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
![Page 6: WebCamp: Developer Day: Web Security: Cookies, Domains and CORS - Юрий Чайковский](https://reader031.vdocuments.mx/reader031/viewer/2022020218/5591d59a1a28aba82a8b45d8/html5/thumbnails/6.jpg)
Requests with XHTTPRequest 2 - Events Plain JavaScript
CODE
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
![Page 7: WebCamp: Developer Day: Web Security: Cookies, Domains and CORS - Юрий Чайковский](https://reader031.vdocuments.mx/reader031/viewer/2022020218/5591d59a1a28aba82a8b45d8/html5/thumbnails/7.jpg)
Requests with XHTTPRequest 2 jQuery
CODE
$.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
![Page 8: WebCamp: Developer Day: Web Security: Cookies, Domains and CORS - Юрий Чайковский](https://reader031.vdocuments.mx/reader031/viewer/2022020218/5591d59a1a28aba82a8b45d8/html5/thumbnails/8.jpg)
Requests with XHTTPRequest 2 AngularJS
CODE
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
![Page 9: WebCamp: Developer Day: Web Security: Cookies, Domains and CORS - Юрий Чайковский](https://reader031.vdocuments.mx/reader031/viewer/2022020218/5591d59a1a28aba82a8b45d8/html5/thumbnails/9.jpg)
Hacking time!
![Page 10: WebCamp: Developer Day: Web Security: Cookies, Domains and CORS - Юрий Чайковский](https://reader031.vdocuments.mx/reader031/viewer/2022020218/5591d59a1a28aba82a8b45d8/html5/thumbnails/10.jpg)
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
![Page 11: WebCamp: Developer Day: Web Security: Cookies, Domains and CORS - Юрий Чайковский](https://reader031.vdocuments.mx/reader031/viewer/2022020218/5591d59a1a28aba82a8b45d8/html5/thumbnails/11.jpg)
Not-so-simple and simple requests § 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
http OPTIONS (Origin: http://example.com:81)
200 Access-Control-Allow- ...
direct GET/POST/PUT/DELETE request as allowed by access headers
pref
light
ed
appl
icat
ion
![Page 12: WebCamp: Developer Day: Web Security: Cookies, Domains and CORS - Юрий Чайковский](https://reader031.vdocuments.mx/reader031/viewer/2022020218/5591d59a1a28aba82a8b45d8/html5/thumbnails/12.jpg)
Access-Control headers
§ 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
Origin: host
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: …
pref
light
ed
requ
est
resp
onse
http://www.html5rocks.com/en/tutorials/cors/
![Page 13: WebCamp: Developer Day: Web Security: Cookies, Domains and CORS - Юрий Чайковский](https://reader031.vdocuments.mx/reader031/viewer/2022020218/5591d59a1a28aba82a8b45d8/html5/thumbnails/13.jpg)
Prevent attacks
§ Have white list of origins
§ If not possible
use X-CSRF-Token
set header X-CSRF-Token
prev
ious
re
ques
t ne
xt
requ
est
return X-CSRF-Token
serv
er
valid
atio
n
server response with new X-CSRF-Token
http://mircozeiss.com/using-csrf-with-express-and-angular/
![Page 14: WebCamp: Developer Day: Web Security: Cookies, Domains and CORS - Юрий Чайковский](https://reader031.vdocuments.mx/reader031/viewer/2022020218/5591d59a1a28aba82a8b45d8/html5/thumbnails/14.jpg)
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
![Page 15: WebCamp: Developer Day: Web Security: Cookies, Domains and CORS - Юрий Чайковский](https://reader031.vdocuments.mx/reader031/viewer/2022020218/5591d59a1a28aba82a8b45d8/html5/thumbnails/15.jpg)
Back-end implementation .Net
CODE
// 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
![Page 16: WebCamp: Developer Day: Web Security: Cookies, Domains and CORS - Юрий Чайковский](https://reader031.vdocuments.mx/reader031/viewer/2022020218/5591d59a1a28aba82a8b45d8/html5/thumbnails/16.jpg)
Back-end implementation Ruby
CODE
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
![Page 17: WebCamp: Developer Day: Web Security: Cookies, Domains and CORS - Юрий Чайковский](https://reader031.vdocuments.mx/reader031/viewer/2022020218/5591d59a1a28aba82a8b45d8/html5/thumbnails/17.jpg)
Manual implementation
§ Most probably you will
never need it, but in case
flowchart is under link
below
http://www.html5rocks.com/en/tutorials/cors/
![Page 18: WebCamp: Developer Day: Web Security: Cookies, Domains and CORS - Юрий Чайковский](https://reader031.vdocuments.mx/reader031/viewer/2022020218/5591d59a1a28aba82a8b45d8/html5/thumbnails/18.jpg)
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
![Page 19: WebCamp: Developer Day: Web Security: Cookies, Domains and CORS - Юрий Чайковский](https://reader031.vdocuments.mx/reader031/viewer/2022020218/5591d59a1a28aba82a8b45d8/html5/thumbnails/19.jpg)
Most loved browser
§ IE ≤ 7 is not a browser
§ IE10+ is already a browser
§ IE8-9 can be handled with
XDomainRequest
![Page 20: WebCamp: Developer Day: Web Security: Cookies, Domains and CORS - Юрий Чайковский](https://reader031.vdocuments.mx/reader031/viewer/2022020218/5591d59a1a28aba82a8b45d8/html5/thumbnails/20.jpg)
Limitation in Internet Explorer 8, 9 Feature detection
CODE
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
![Page 21: WebCamp: Developer Day: Web Security: Cookies, Domains and CORS - Юрий Чайковский](https://reader031.vdocuments.mx/reader031/viewer/2022020218/5591d59a1a28aba82a8b45d8/html5/thumbnails/21.jpg)
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
![Page 22: WebCamp: Developer Day: Web Security: Cookies, Domains and CORS - Юрий Чайковский](https://reader031.vdocuments.mx/reader031/viewer/2022020218/5591d59a1a28aba82a8b45d8/html5/thumbnails/22.jpg)
Workarounds
Third party services
Proxy
Client
![Page 23: WebCamp: Developer Day: Web Security: Cookies, Domains and CORS - Юрий Чайковский](https://reader031.vdocuments.mx/reader031/viewer/2022020218/5591d59a1a28aba82a8b45d8/html5/thumbnails/23.jpg)
Workarounds JSONP Concept
CODE
<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":"[email protected]", "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
![Page 24: WebCamp: Developer Day: Web Security: Cookies, Domains and CORS - Юрий Чайковский](https://reader031.vdocuments.mx/reader031/viewer/2022020218/5591d59a1a28aba82a8b45d8/html5/thumbnails/24.jpg)
Workarounds JSONP with jQuery
CODE
<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_1398177525599&_=1398177525600 #responce from http://3rd-party.com/api/v1/users/27: jQuery111008519500948023051_1398177525599({
"id":1, "name":"Jack", "email":"[email protected]", ...
});
1 2 3 4 5 6 7 8 9
10 11 12 13 14 15 16 17 18
![Page 25: WebCamp: Developer Day: Web Security: Cookies, Domains and CORS - Юрий Чайковский](https://reader031.vdocuments.mx/reader031/viewer/2022020218/5591d59a1a28aba82a8b45d8/html5/thumbnails/25.jpg)
Workarounds JSONP Limitations
● JavaScript Object Notation is for read, not eval.
● Can’t add custom headers.
● Require ability to modify backend.
● Only GET method.
![Page 26: WebCamp: Developer Day: Web Security: Cookies, Domains and CORS - Юрий Чайковский](https://reader031.vdocuments.mx/reader031/viewer/2022020218/5591d59a1a28aba82a8b45d8/html5/thumbnails/26.jpg)
Workarounds... kind of Document messaging
CODE
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
![Page 27: WebCamp: Developer Day: Web Security: Cookies, Domains and CORS - Юрий Чайковский](https://reader031.vdocuments.mx/reader031/viewer/2022020218/5591d59a1a28aba82a8b45d8/html5/thumbnails/27.jpg)
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
![Page 28: WebCamp: Developer Day: Web Security: Cookies, Domains and CORS - Юрий Чайковский](https://reader031.vdocuments.mx/reader031/viewer/2022020218/5591d59a1a28aba82a8b45d8/html5/thumbnails/28.jpg)
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/content-security-policy/ http://en.wikipedia.org/wiki/Content_Security_Policy
Content-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;
![Page 29: WebCamp: Developer Day: Web Security: Cookies, Domains and CORS - Юрий Чайковский](https://reader031.vdocuments.mx/reader031/viewer/2022020218/5591d59a1a28aba82a8b45d8/html5/thumbnails/29.jpg)
Thank you!
Yura Chaikovsky [email protected] yura.chaikovsky
Yura Chaikovsky [email protected] yura.chaikovsky