SlideShare a Scribd company logo
1 of 29
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

What's hot

Krzysztof Kotowicz - Hacking HTML5
Krzysztof Kotowicz - Hacking HTML5Krzysztof Kotowicz - Hacking HTML5
Krzysztof Kotowicz - Hacking HTML5
DefconRussia
 
Comparative Development Methodologies
Comparative Development MethodologiesComparative Development Methodologies
Comparative Development Methodologies
elliando dias
 

What's hot (20)

RESTful Web Services
RESTful Web ServicesRESTful Web Services
RESTful Web Services
 
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
 
Introduction to RESTful Web Services
Introduction to RESTful Web ServicesIntroduction to RESTful Web Services
Introduction to RESTful Web Services
 
01. http basics v27
01. http basics v2701. http basics v27
01. http basics v27
 
Krzysztof Kotowicz - Hacking HTML5
Krzysztof Kotowicz - Hacking HTML5Krzysztof Kotowicz - Hacking HTML5
Krzysztof Kotowicz - Hacking HTML5
 
Advanced Chrome extension exploitation
Advanced Chrome extension exploitationAdvanced Chrome extension exploitation
Advanced Chrome extension exploitation
 
Comparative Development Methodologies
Comparative Development MethodologiesComparative Development Methodologies
Comparative Development Methodologies
 
Your rest api using laravel
Your rest api using laravelYour rest api using laravel
Your rest api using laravel
 
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...
 
htaccess
htaccesshtaccess
htaccess
 
Web Browsers And Other Mistakes
Web Browsers And Other MistakesWeb Browsers And Other Mistakes
Web Browsers And Other Mistakes
 
Building Awesome APIs with Lumen
Building Awesome APIs with LumenBuilding Awesome APIs with Lumen
Building Awesome APIs with Lumen
 
PHP BASIC PRESENTATION
PHP BASIC PRESENTATIONPHP BASIC PRESENTATION
PHP BASIC PRESENTATION
 
Cross Origin Communication (CORS)
Cross Origin Communication (CORS)Cross Origin Communication (CORS)
Cross Origin Communication (CORS)
 
distributing over the web
distributing over the webdistributing over the web
distributing over the web
 
Introduction to asp.net web api
Introduction to asp.net web apiIntroduction to asp.net web api
Introduction to asp.net web api
 
Connecting to Web Services on Android
Connecting to Web Services on AndroidConnecting to Web Services on Android
Connecting to Web Services on Android
 
Demystifying REST
Demystifying RESTDemystifying REST
Demystifying REST
 
KMUTNB - Internet Programming 2/7
KMUTNB - Internet Programming 2/7KMUTNB - Internet Programming 2/7
KMUTNB - Internet Programming 2/7
 
HTTP protocol and Streams Security
HTTP protocol and Streams SecurityHTTP protocol and Streams Security
HTTP protocol and Streams Security
 

Viewers also liked

Проектирование мероприятий. Лариса Малышева для I_Love_Events.conf
Проектирование мероприятий. Лариса Малышева для I_Love_Events.confПроектирование мероприятий. Лариса Малышева для I_Love_Events.conf
Проектирование мероприятий. Лариса Малышева для I_Love_Events.conf
lashkova
 
Alla scoperta di Marte
Alla scoperta di MarteAlla scoperta di Marte
Alla scoperta di Marte
chreact
 
Событийный маркетинг: заблуждение века. Денис Снетков для I_Love_Events.conf
Событийный маркетинг: заблуждение века. Денис Снетков для I_Love_Events.confСобытийный маркетинг: заблуждение века. Денис Снетков для I_Love_Events.conf
Событийный маркетинг: заблуждение века. Денис Снетков для I_Love_Events.conf
lashkova
 
Illuminazione artificiale
Illuminazione artificialeIlluminazione artificiale
Illuminazione artificiale
chreact
 

Viewers also liked (20)

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

Similar to Web Security - Cookies, Domains and CORS

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
 
Secureyourrestapi 140530183606-phpapp02
Secureyourrestapi 140530183606-phpapp02Secureyourrestapi 140530183606-phpapp02
Secureyourrestapi 140530183606-phpapp02
Subhajit Bhuiya
 
Site Security Policy - Yahoo! Security Week
Site Security Policy - Yahoo! Security WeekSite Security Policy - Yahoo! Security Week
Site Security Policy - Yahoo! Security Week
guest9663eb
 

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

Going Beyond Cross Domain Boundaries (jQuery Bulgaria)
Going Beyond Cross Domain Boundaries (jQuery Bulgaria)Going Beyond Cross Domain Boundaries (jQuery Bulgaria)
Going Beyond Cross Domain Boundaries (jQuery Bulgaria)
 
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 - Юрий Чайков...
 
Hacking HTML5 offensive course (Zeronights edition)
Hacking HTML5 offensive course (Zeronights edition)Hacking HTML5 offensive course (Zeronights edition)
Hacking HTML5 offensive course (Zeronights edition)
 
Using Communication and Messaging API in the HTML5 World
Using Communication and Messaging API in the HTML5 WorldUsing Communication and Messaging API in the HTML5 World
Using Communication and Messaging API in the HTML5 World
 
Ch 3: Web Application Technologies
Ch 3: Web Application TechnologiesCh 3: Web Application Technologies
Ch 3: Web Application Technologies
 
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
 
The never-ending REST API design debate
The never-ending REST API design debateThe never-ending REST API design debate
The never-ending REST API design debate
 
Secureyourrestapi 140530183606-phpapp02
Secureyourrestapi 140530183606-phpapp02Secureyourrestapi 140530183606-phpapp02
Secureyourrestapi 140530183606-phpapp02
 
Secure Your REST API (The Right Way)
Secure Your REST API (The Right Way)Secure Your REST API (The Right Way)
Secure Your REST API (The Right Way)
 
Web security for app developers
Web security for app developersWeb security for app developers
Web security for app developers
 
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
 
The never-ending REST API design debate -- Devoxx France 2016
The never-ending REST API design debate -- Devoxx France 2016The never-ending REST API design debate -- Devoxx France 2016
The never-ending REST API design debate -- Devoxx France 2016
 
REST Api Tips and Tricks
REST Api Tips and TricksREST Api Tips and Tricks
REST Api Tips and Tricks
 
CNIT 129S: Ch 3: Web Application Technologies
CNIT 129S: Ch 3: Web Application TechnologiesCNIT 129S: Ch 3: Web Application Technologies
CNIT 129S: Ch 3: Web Application Technologies
 
CNIT 129S - Ch 3: Web Application Technologies
CNIT 129S - Ch 3: Web Application TechnologiesCNIT 129S - Ch 3: Web Application Technologies
CNIT 129S - Ch 3: Web Application Technologies
 
Attacking REST API
Attacking REST APIAttacking REST API
Attacking REST API
 
Site Security Policy - Yahoo! Security Week
Site Security Policy - Yahoo! Security WeekSite Security Policy - Yahoo! Security Week
Site Security Policy - Yahoo! Security Week
 
Using communication and messaging API in the HTML5 world - GIl Fink, sparXsys
Using communication and messaging API in the HTML5 world - GIl Fink, sparXsysUsing communication and messaging API in the HTML5 world - GIl Fink, sparXsys
Using communication and messaging API in the HTML5 world - GIl Fink, sparXsys
 
HTML5 hacking
HTML5 hackingHTML5 hacking
HTML5 hacking
 
Deep Dive on Accelerating Content, APIs, and Applications with Amazon CloudFr...
Deep Dive on Accelerating Content, APIs, and Applications with Amazon CloudFr...Deep Dive on Accelerating Content, APIs, and Applications with Amazon CloudFr...
Deep Dive on Accelerating Content, APIs, and Applications with Amazon CloudFr...
 

Recently uploaded

IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
Enterprise Knowledge
 

Recently uploaded (20)

2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
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
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 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...
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 

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