SlideShare ist ein Scribd-Unternehmen logo
1 von 29
Downloaden Sie, um offline zu lesen
Web Security 
Cookies, Domains and CORS 
4/2014, Yura Chaikovsky
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
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:pass@sub.domain.com:8080/folder/index.html?id=42&action=add#first-section
Use cases 
§ Share buttons 
§ Visitors analytics 
§ Advertisments 
§ Maps 
§ Payment systems 
§ REST API 
§ Shared services
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
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
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
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
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
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 
application preflighted
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: … 
preflighted 
response request 
http://www.html5rocks.com/en/tutorials/cors/
Prevent attacks 
§ Have white list of origins 
§ If not possible 
use X-CSRF-Token 
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 
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
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
Manual 
implementation 
§ Most probably you will 
never need it, but in case 
flowchart is under link 
below 
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
Most loved 
browser 
§ IE ≤ 7 is not a browser 
§ IE10+ is already a browser 
§ IE8-9 can be handled with 
XDomainRequest
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
Limitation in Internet Explorer 8, 9 
Things to remember 
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 
http://blogs.msdn.com/b/ieinternals/archive/2010/05/13/xdomainrequest-restrictions-limitations-and-workarounds.aspx
Workarounds 
Third party services 
Proxy 
Client
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":"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 
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":"jack@3rd-party.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 
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
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
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;
Thank you! 
Yura Chaikovsky 
yura.chaikovsky@gmail.com 
yura.chaikovsky

Weitere ähnliche Inhalte

Was ist angesagt?

[CB16] Esoteric Web Application Vulnerabilities by Andrés Riancho
[CB16] Esoteric Web Application Vulnerabilities by Andrés Riancho[CB16] Esoteric Web Application Vulnerabilities by Andrés Riancho
[CB16] Esoteric Web Application Vulnerabilities by Andrés Riancho
CODE BLUE
 
Reutov, yunusov, nagibin random numbers take ii
Reutov, yunusov, nagibin   random numbers take iiReutov, yunusov, nagibin   random numbers take ii
Reutov, yunusov, nagibin random numbers take ii
DefconRussia
 
Cancer de-prostata-40601330[1]
Cancer de-prostata-40601330[1]Cancer de-prostata-40601330[1]
Cancer de-prostata-40601330[1]
Ludwing007
 
Make Your SW Component Testable
Make Your SW Component TestableMake Your SW Component Testable
Make Your SW Component Testable
Li-Wei Cheng
 

Was ist angesagt? (19)

PHP Secure Programming
PHP Secure ProgrammingPHP Secure Programming
PHP Secure Programming
 
Vladimir Vorontsov - Splitting, smuggling and cache poisoning come back
Vladimir Vorontsov - Splitting, smuggling and cache poisoning come backVladimir Vorontsov - Splitting, smuggling and cache poisoning come back
Vladimir Vorontsov - Splitting, smuggling and cache poisoning come back
 
It's 10pm: Do You Know Where Your Writes Are?
It's 10pm: Do You Know Where Your Writes Are?It's 10pm: Do You Know Where Your Writes Are?
It's 10pm: Do You Know Where Your Writes Are?
 
UA testing with Selenium and PHPUnit - TrueNorthPHP 2013
UA testing with Selenium and PHPUnit - TrueNorthPHP 2013UA testing with Selenium and PHPUnit - TrueNorthPHP 2013
UA testing with Selenium and PHPUnit - TrueNorthPHP 2013
 
Mug17 gurgaon
Mug17 gurgaonMug17 gurgaon
Mug17 gurgaon
 
Philipp Krenn "Make Your Data FABulous"
Philipp Krenn "Make Your Data FABulous"Philipp Krenn "Make Your Data FABulous"
Philipp Krenn "Make Your Data FABulous"
 
Learning Dtrace
Learning DtraceLearning Dtrace
Learning Dtrace
 
[CB16] Esoteric Web Application Vulnerabilities by Andrés Riancho
[CB16] Esoteric Web Application Vulnerabilities by Andrés Riancho[CB16] Esoteric Web Application Vulnerabilities by Andrés Riancho
[CB16] Esoteric Web Application Vulnerabilities by Andrés Riancho
 
MongoDB World 2016: Deciphering .explain() Output
MongoDB World 2016: Deciphering .explain() OutputMongoDB World 2016: Deciphering .explain() Output
MongoDB World 2016: Deciphering .explain() Output
 
Logstash for SEO: come monitorare i Log del Web Server in realtime
Logstash for SEO: come monitorare i Log del Web Server in realtimeLogstash for SEO: come monitorare i Log del Web Server in realtime
Logstash for SEO: come monitorare i Log del Web Server in realtime
 
Ajax и будущее Java Script
Ajax и будущее Java ScriptAjax и будущее Java Script
Ajax и будущее Java Script
 
Detection of REST Patterns and Antipatterns: A Heuristics-based Approach
Detection of REST Patterns and Antipatterns: A Heuristics-based ApproachDetection of REST Patterns and Antipatterns: A Heuristics-based Approach
Detection of REST Patterns and Antipatterns: A Heuristics-based Approach
 
Reutov, yunusov, nagibin random numbers take ii
Reutov, yunusov, nagibin   random numbers take iiReutov, yunusov, nagibin   random numbers take ii
Reutov, yunusov, nagibin random numbers take ii
 
Philipp Krenn | Make Your Data FABulous | Codemotion Madrid 2018
Philipp Krenn | Make Your Data FABulous | Codemotion Madrid 2018Philipp Krenn | Make Your Data FABulous | Codemotion Madrid 2018
Philipp Krenn | Make Your Data FABulous | Codemotion Madrid 2018
 
sf bay area dfir meetup (2016-04-30) - OsxCollector
sf bay area dfir meetup (2016-04-30) - OsxCollector   sf bay area dfir meetup (2016-04-30) - OsxCollector
sf bay area dfir meetup (2016-04-30) - OsxCollector
 
Cancer de-prostata-40601330[1]
Cancer de-prostata-40601330[1]Cancer de-prostata-40601330[1]
Cancer de-prostata-40601330[1]
 
BlockChain implementation by python
BlockChain implementation by pythonBlockChain implementation by python
BlockChain implementation by python
 
Make Your SW Component Testable
Make Your SW Component TestableMake Your SW Component Testable
Make Your SW Component Testable
 
Anex....,,,.
Anex....,,,.Anex....,,,.
Anex....,,,.
 

Ähnlich wie WebCamp: Developer Day: Web Security: Cookies, Domains and CORS - Юрий Чайковский

CONFidence 2014: Kiss, Zagon, Sseller: Scaling security
CONFidence 2014: Kiss, Zagon, Sseller: Scaling securityCONFidence 2014: Kiss, Zagon, Sseller: Scaling security
CONFidence 2014: Kiss, Zagon, Sseller: Scaling security
PROIDEA
 

Ähnlich wie WebCamp: Developer Day: Web Security: Cookies, Domains and CORS - Юрий Чайковский (20)

Web Security - Cookies, Domains and CORS
Web Security - Cookies, Domains and CORSWeb Security - Cookies, Domains and CORS
Web Security - Cookies, Domains and CORS
 
Ajax basics
Ajax basicsAjax basics
Ajax basics
 
CONFidence 2014: Kiss, Zagon, Sseller: Scaling security
CONFidence 2014: Kiss, Zagon, Sseller: Scaling securityCONFidence 2014: Kiss, Zagon, Sseller: Scaling security
CONFidence 2014: Kiss, Zagon, Sseller: Scaling security
 
Android and REST
Android and RESTAndroid and REST
Android and REST
 
JavaScript Security: Mastering Cross Domain Communications in complex JS appl...
JavaScript Security: Mastering Cross Domain Communications in complex JS appl...JavaScript Security: Mastering Cross Domain Communications in complex JS appl...
JavaScript Security: Mastering Cross Domain Communications in complex JS appl...
 
Building Applications Using Ajax
Building Applications Using AjaxBuilding Applications Using Ajax
Building Applications Using Ajax
 
W3 conf hill-html5-security-realities
W3 conf hill-html5-security-realitiesW3 conf hill-html5-security-realities
W3 conf hill-html5-security-realities
 
Rapid API development examples for Impress Application Server / Node.js (jsfw...
Rapid API development examples for Impress Application Server / Node.js (jsfw...Rapid API development examples for Impress Application Server / Node.js (jsfw...
Rapid API development examples for Impress Application Server / Node.js (jsfw...
 
AJAX Transport Layer
AJAX Transport LayerAJAX Transport Layer
AJAX Transport Layer
 
Drive chrome(headless) with puppeteer
Drive chrome(headless) with puppeteerDrive chrome(headless) with puppeteer
Drive chrome(headless) with puppeteer
 
How to make Ajax work for you
How to make Ajax work for youHow to make Ajax work for you
How to make Ajax work for you
 
Secure java script-for-developers
Secure java script-for-developersSecure java script-for-developers
Secure java script-for-developers
 
Os Pruett
Os PruettOs Pruett
Os Pruett
 
CORS - Enable Alfresco for CORS
CORS - Enable Alfresco for CORSCORS - Enable Alfresco for CORS
CORS - Enable Alfresco for CORS
 
Modern Web Application Defense
Modern Web Application DefenseModern Web Application Defense
Modern Web Application Defense
 
Evolution Of Web Security
Evolution Of Web SecurityEvolution Of Web Security
Evolution Of Web Security
 
Android dev 3
Android dev 3Android dev 3
Android dev 3
 
AtlasCamp 2014: 10 Things a Front End Developer Should Know About Connect
AtlasCamp 2014: 10 Things a Front End Developer Should Know About ConnectAtlasCamp 2014: 10 Things a Front End Developer Should Know About Connect
AtlasCamp 2014: 10 Things a Front End Developer Should Know About Connect
 
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
 
UA Testing with Selenium and PHPUnit - ZendCon 2013
UA Testing with Selenium and PHPUnit - ZendCon 2013UA Testing with Selenium and PHPUnit - ZendCon 2013
UA Testing with Selenium and PHPUnit - ZendCon 2013
 

Mehr von GeeksLab Odessa

DataScience Lab2017_Коррекция геометрических искажений оптических спутниковых...
DataScience Lab2017_Коррекция геометрических искажений оптических спутниковых...DataScience Lab2017_Коррекция геометрических искажений оптических спутниковых...
DataScience Lab2017_Коррекция геометрических искажений оптических спутниковых...
GeeksLab Odessa
 
DataScienceLab2017_Cервинг моделей, построенных на больших данных с помощью A...
DataScienceLab2017_Cервинг моделей, построенных на больших данных с помощью A...DataScienceLab2017_Cервинг моделей, построенных на больших данных с помощью A...
DataScienceLab2017_Cервинг моделей, построенных на больших данных с помощью A...
GeeksLab Odessa
 
DataScienceLab2017_Высокопроизводительные вычислительные возможности для сист...
DataScienceLab2017_Высокопроизводительные вычислительные возможности для сист...DataScienceLab2017_Высокопроизводительные вычислительные возможности для сист...
DataScienceLab2017_Высокопроизводительные вычислительные возможности для сист...
GeeksLab Odessa
 
DataScience Lab 2017_Графические вероятностные модели для принятия решений в ...
DataScience Lab 2017_Графические вероятностные модели для принятия решений в ...DataScience Lab 2017_Графические вероятностные модели для принятия решений в ...
DataScience Lab 2017_Графические вероятностные модели для принятия решений в ...
GeeksLab Odessa
 
JS Lab 2017_Mapbox GL: как работают современные интерактивные карты_Владимир ...
JS Lab 2017_Mapbox GL: как работают современные интерактивные карты_Владимир ...JS Lab 2017_Mapbox GL: как работают современные интерактивные карты_Владимир ...
JS Lab 2017_Mapbox GL: как работают современные интерактивные карты_Владимир ...
GeeksLab Odessa
 

Mehr von GeeksLab Odessa (20)

DataScience Lab2017_Коррекция геометрических искажений оптических спутниковых...
DataScience Lab2017_Коррекция геометрических искажений оптических спутниковых...DataScience Lab2017_Коррекция геометрических искажений оптических спутниковых...
DataScience Lab2017_Коррекция геометрических искажений оптических спутниковых...
 
DataScience Lab 2017_Kappa Architecture: How to implement a real-time streami...
DataScience Lab 2017_Kappa Architecture: How to implement a real-time streami...DataScience Lab 2017_Kappa Architecture: How to implement a real-time streami...
DataScience Lab 2017_Kappa Architecture: How to implement a real-time streami...
 
DataScience Lab 2017_Блиц-доклад_Турский Виктор
DataScience Lab 2017_Блиц-доклад_Турский ВикторDataScience Lab 2017_Блиц-доклад_Турский Виктор
DataScience Lab 2017_Блиц-доклад_Турский Виктор
 
DataScience Lab 2017_Обзор методов детекции лиц на изображение
DataScience Lab 2017_Обзор методов детекции лиц на изображениеDataScience Lab 2017_Обзор методов детекции лиц на изображение
DataScience Lab 2017_Обзор методов детекции лиц на изображение
 
DataScienceLab2017_Сходство пациентов: вычистка дубликатов и предсказание про...
DataScienceLab2017_Сходство пациентов: вычистка дубликатов и предсказание про...DataScienceLab2017_Сходство пациентов: вычистка дубликатов и предсказание про...
DataScienceLab2017_Сходство пациентов: вычистка дубликатов и предсказание про...
 
DataScienceLab2017_Блиц-доклад
DataScienceLab2017_Блиц-докладDataScienceLab2017_Блиц-доклад
DataScienceLab2017_Блиц-доклад
 
DataScienceLab2017_Блиц-доклад
DataScienceLab2017_Блиц-докладDataScienceLab2017_Блиц-доклад
DataScienceLab2017_Блиц-доклад
 
DataScienceLab2017_Блиц-доклад
DataScienceLab2017_Блиц-докладDataScienceLab2017_Блиц-доклад
DataScienceLab2017_Блиц-доклад
 
DataScienceLab2017_Cервинг моделей, построенных на больших данных с помощью A...
DataScienceLab2017_Cервинг моделей, построенных на больших данных с помощью A...DataScienceLab2017_Cервинг моделей, построенных на больших данных с помощью A...
DataScienceLab2017_Cервинг моделей, построенных на больших данных с помощью A...
 
DataScienceLab2017_BioVec: Word2Vec в задачах анализа геномных данных и биоин...
DataScienceLab2017_BioVec: Word2Vec в задачах анализа геномных данных и биоин...DataScienceLab2017_BioVec: Word2Vec в задачах анализа геномных данных и биоин...
DataScienceLab2017_BioVec: Word2Vec в задачах анализа геномных данных и биоин...
 
DataScienceLab2017_Data Sciences и Big Data в Телекоме_Александр Саенко
DataScienceLab2017_Data Sciences и Big Data в Телекоме_Александр Саенко DataScienceLab2017_Data Sciences и Big Data в Телекоме_Александр Саенко
DataScienceLab2017_Data Sciences и Big Data в Телекоме_Александр Саенко
 
DataScienceLab2017_Высокопроизводительные вычислительные возможности для сист...
DataScienceLab2017_Высокопроизводительные вычислительные возможности для сист...DataScienceLab2017_Высокопроизводительные вычислительные возможности для сист...
DataScienceLab2017_Высокопроизводительные вычислительные возможности для сист...
 
DataScience Lab 2017_Мониторинг модных трендов с помощью глубокого обучения и...
DataScience Lab 2017_Мониторинг модных трендов с помощью глубокого обучения и...DataScience Lab 2017_Мониторинг модных трендов с помощью глубокого обучения и...
DataScience Lab 2017_Мониторинг модных трендов с помощью глубокого обучения и...
 
DataScience Lab 2017_Кто здесь? Автоматическая разметка спикеров на телефонны...
DataScience Lab 2017_Кто здесь? Автоматическая разметка спикеров на телефонны...DataScience Lab 2017_Кто здесь? Автоматическая разметка спикеров на телефонны...
DataScience Lab 2017_Кто здесь? Автоматическая разметка спикеров на телефонны...
 
DataScience Lab 2017_From bag of texts to bag of clusters_Терпиль Евгений / П...
DataScience Lab 2017_From bag of texts to bag of clusters_Терпиль Евгений / П...DataScience Lab 2017_From bag of texts to bag of clusters_Терпиль Евгений / П...
DataScience Lab 2017_From bag of texts to bag of clusters_Терпиль Евгений / П...
 
DataScience Lab 2017_Графические вероятностные модели для принятия решений в ...
DataScience Lab 2017_Графические вероятностные модели для принятия решений в ...DataScience Lab 2017_Графические вероятностные модели для принятия решений в ...
DataScience Lab 2017_Графические вероятностные модели для принятия решений в ...
 
DataScienceLab2017_Оптимизация гиперпараметров машинного обучения при помощи ...
DataScienceLab2017_Оптимизация гиперпараметров машинного обучения при помощи ...DataScienceLab2017_Оптимизация гиперпараметров машинного обучения при помощи ...
DataScienceLab2017_Оптимизация гиперпараметров машинного обучения при помощи ...
 
DataScienceLab2017_Как знать всё о покупателях (или почти всё)?_Дарина Перемот
DataScienceLab2017_Как знать всё о покупателях (или почти всё)?_Дарина Перемот DataScienceLab2017_Как знать всё о покупателях (или почти всё)?_Дарина Перемот
DataScienceLab2017_Как знать всё о покупателях (или почти всё)?_Дарина Перемот
 
JS Lab 2017_Mapbox GL: как работают современные интерактивные карты_Владимир ...
JS Lab 2017_Mapbox GL: как работают современные интерактивные карты_Владимир ...JS Lab 2017_Mapbox GL: как работают современные интерактивные карты_Владимир ...
JS Lab 2017_Mapbox GL: как работают современные интерактивные карты_Владимир ...
 
JS Lab2017_Под микроскопом: блеск и нищета микросервисов на node.js
JS Lab2017_Под микроскопом: блеск и нищета микросервисов на node.js JS Lab2017_Под микроскопом: блеск и нищета микросервисов на node.js
JS Lab2017_Под микроскопом: блеск и нищета микросервисов на node.js
 

Kürzlich hochgeladen

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 

Kürzlich hochgeladen (20)

Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 

WebCamp: Developer Day: Web Security: Cookies, Domains and CORS - Юрий Чайковский

  • 1. Web Security Cookies, Domains and CORS 4/2014, Yura Chaikovsky
  • 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. 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:pass@sub.domain.com:8080/folder/index.html?id=42&action=add#first-section
  • 4. Use cases § Share buttons § Visitors analytics § Advertisments § Maps § Payment systems § REST API § Shared services
  • 5. 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
  • 6. 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
  • 7. 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
  • 8. 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
  • 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. 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 application preflighted
  • 12. 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: … preflighted response request http://www.html5rocks.com/en/tutorials/cors/
  • 13. Prevent attacks § Have white list of origins § If not possible use X-CSRF-Token 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 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
  • 16. 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
  • 17. Manual implementation § Most probably you will never need it, but in case flowchart is under link below 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. Most loved browser § IE ≤ 7 is not a browser § IE10+ is already a browser § IE8-9 can be handled with XDomainRequest
  • 20. 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
  • 21. Limitation in Internet Explorer 8, 9 Things to remember 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 http://blogs.msdn.com/b/ieinternals/archive/2010/05/13/xdomainrequest-restrictions-limitations-and-workarounds.aspx
  • 22. Workarounds Third party services Proxy Client
  • 23. 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":"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 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":"jack@3rd-party.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 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
  • 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. 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;
  • 29. Thank you! Yura Chaikovsky yura.chaikovsky@gmail.com yura.chaikovsky