leftArrow

All Blogs

Vulnerability

Cross-Origin Resource Sharing: Explanation and Ways to Prevent CORS Vulnerability

Updated Date: Aug 29, 2024
Cross-Origin Resource Sharing Guide

Quick Summary: CORS offers a secure way for client web apps in one domain to access resources in another domain. While this is a good method to execute cross-domain resource requests, it can also be risky when misconfigured. Keep reading for detailed information about it, how it works, and ways to prevent vulnerabilities.

Loading resources from other domains or subdomains is common for modern web applications. Think of a web application that gathers weather information from a national weather database and displays it to users through the UI. However, when web apps do this without adequate security measures, it could lead to cyberattacks and data breaches.

Therefore, Cross-Origin Resource Sharing or CORS was introduced as a supplementary mechanism for loading resources securely. It offers an effective technique to obtain data or resources from a domain other than the one from where the request was sent.

Keep reading to get a complete understanding of this concept with examples. Besides, you can know about vulnerabilities arising from misconfigured CORS. Don’t forget to check the methods to prevent vulnerabilities, like customizing headers, vulnerability assessment, and more.

Let’s dive into the article for all the details.

Table of Contents
  1. What is Cross-Origin Resource Sharing (CORS) and What is Its Use?
  2. Why is Cross Origin Resource Sharing Important?
  3. How Does the Magic Works with CORS?
  4. Understanding CORS Vulnerability and Its Impact on Cybersecurity
  5. Types of Threats from Cross-Origin Resource Sharing (CORS) Vulnerability
  6. What are Some Ways to Prevent CORS-based Attacks?
  7. To Wrap Up

What is Cross-Origin Resource Sharing (CORS) and What is Its Use?

CORS is a mechanism that allows a web page on one (sub)domain to securely access external resources from another (sub)domain. It helps to successfully perform cross-origin requests and transfer data between the browser and an external server.

Put simply, it allows controlled and secure access to data between two different origins. By default, web browsers function on a same-origin policy, which means any request made from a (sub)domain to fetch resources from another (sub)domain is restricted.

Note: The same origin is determined by the protocol, port, and hostname for a domain. A protocol like ‘https’ or ‘http’, a port like ‘80’ or ‘443’, and a hostname like ‘example.com’ and api.example.com’.

However, CORS extends this policy by allowing web browsers to process requests to fetch resources from another (sub)domain. CORS technique combined with web app security best practices provide a greater level of protection against cyberattacks.

The same-origin policy provides security against such threats as XSS and XSRF. However, there are many legitimate reasons for cross-origin requests, such as fetching weather data from a national database, fonts from a public library of fonts, and videos from an API.

Why is Cross Origin Resource Sharing Important?

Let’s check out why cross origin resource sharing is important to ensure robust security in web applications.

1. Secure Resource Sharing

With CORS, servers can easily specify who can access their resources which reduces the risk of unauthorized access. CORS play an important role in ensuring that only authenticated domains can access servers’ resources.

Additionally, implementation of cross origin resource sharing policies allows organizations’ servers to prevent malicious scripts from other origins from accessing confidential details.

2. Enabling Modern Web Apps

Many modern web apps use APIs hosted on multiple domains. CORS helps organizations to create secured cross-origin requests that ensures safe and secured data exchange between different servers.

Moreover, CORS enables dynamic content loading in web applications. It dynamically loads resources such as fonts, scripts, and stylesheets from various domains which improves functionality and user experience.

3. Compliance with Same-Origin Policy

The same-origin policy blocks web pages from requesting data from multiple domains. CORS has specific rules that ensure secure data requests from different domains.

4. Preventing Security Vulnerabilities

As CORS only permits origins that meet predefined standards, this potentially reduces the chances of vulnerabilities and unauthorized access to the server. CORS also prevents data leakage by controlling which external domains can access confidential information.

How Does the Magic Works with CORS?

We will understand how CORS works with an example here.

Let’s assume there is a web application that is hosted at a domain (origin) https://samplesite.com. It has JavaScript embedded that makes a request to fetch data from https://api.anothersite.com. Now, the CORS will work as follows.

  • Make a cross-origin request: First, the browser will make a cross-origin request based on the following JavaScript code
const req = new XMLHttpRequest();  req.open(‘GET’, ‘https://api.anothersite.com/data’, true);  req.onreadystatechange = function() {  if(XMLHttpRequest.DONE) {  if(req.status === 200) {  console.log(req.responseText);  } else {  console.error(‘Request failed:’, req.status);  }  }  };  req.send();

As you can see in the above code, the ‘req.open()’ method sends a request to https://api.anothersite.com to fetch data for the existing domain. It is a cross-origin request. Now, usually, browsers will block this request with the same-origin policy.

  • Block cross-origin request: Now when the browser executes this JavaScript code, it will discover that there is a cross-origin request being made from https://samplesite.com to https://api.anothersite.com. It will be blocked by default. However, when the Cross-Origin Resource Sharing mechanism is used it will be handled as per the following steps.
  • Preflight request: This is a request sent before the actual request to verify whether it is allowed on the destination domain. So, in the case of a cross-origin request, the browser will send a preflight request to the server using the “OPTIONS” method (https://api.anothersite.com in this case) to check if the request (with ‘GET’) from the existing domain is allowed. This request includes an ‘Origin’ header that points to the address of the existing domain, which is https://samplesite.com.
  • Server response: When the CORS is configured, the server at https://api.anothersite.com will examine the preflight request to check the “Origin” header. When the request from the other domain is allowed, the server will send a response.
  • Actual request: If the preflight request was made successfully and the server also allows the requests from https://samplesite.com, the browser will make an actual request to get data from https://api.anothersite.com.
  • Request handled: Finally, the server will handle the request, which is “GET /data” in this case. It will return the data in JSON, XML, HTML, etc.

Understanding CORS Vulnerability and Its Impact on Cybersecurity

Modern web applications and websites use CORS to allow seamless access to resources residing on domains or subdomains other than where the request originated. However, vulnerabilities that arise from misconfigurations can lead to exploitation.

Attackers can take advantage of such a CORS exploit to steal sensitive data by executing malicious JavaScript code on a victim’s browser. Lack of proper validation of the origin of requests and permissive access control policies are the root causes of this problem.

There is a drastic impact on the security of web applications when there is a CORS vulnerability. An attacker can bypass the same-origin policy of a web browser to perform unauthorized transactions or gain access to sensitive data.

Let’s understand this with an example.

Suppose users can authenticate and log in to a web application at https://testsite.com and fetch their profile information. However, to fetch profile information, the web application uses another domain, which is https://profile.testsite.com. There is a script embedded in the web app that sends a request to https://profile.testsite.com to get the profile data.

Now, suppose the web application is configured to allow requests from any domain using a wildcard “*” symbol. In that case, it sets the “Access-Control-Allow-Origin" header to all domains, resulting in accepting requests from any domain without validation. Consequently, an attacker exploits this vulnerability to send users to a malicious website.

The website can use a script to send a request to the profile page and provide users’ cookies. If the web application doesn’t have a proper validation method for origins, the attacker will access users’ profile data.

Types of Threats from Cross-Origin Resource Sharing (CORS) Vulnerability

The following are the different threats that arise from poor implementation of the Cross-Origin Resource Sharing mechanism.

Types of CORS Vulnerability Threats

Cross-site Scripting

CORS builds trust between two origins when configured correctly. So, a web application could allow a request to pull resources from a different origin due to this trust. However, an attacker could exploit this trust if another origin is vulnerable to an attack like Cross-site Scripting. The attacker can take advantage of vulnerable origins to inject malicious into a web application that uses CORS. It can allow the attacker to steal sensitive data or perform unauthorized actions.

Manipulation of Origin Header

An attacker can tamper with the headers in a cross-domain request to perform malicious actions. The attacker can replace the “Origin” header in HTTP requests with a custom one to trick the server into believing that the request is from a legitimate server. Consequently, the attacker will be able to gain access to sensitive data.

Cross Server Request Forgery

Improperly configured CORS can result in CSRF or Cross Server Request Forgery attacks. These attacks compel users to perform actions on web apps they are currently authenticated with. An attacker steals the credentials of users by redirecting them to a malicious domain and using the credentials to do unauthorized actions.

For example, a user authenticates a bank website, and an attacker tricks the user into opening a malicious website that steals cookie data. Now this cookie data is used to perform unwanted transactions pretending to be the user on the bank’s website.

What are Some Ways to Prevent CORS-based Attacks?

CORS vulnerabilities occur primarily because of misconfigurations. Therefore, if you want to prevent this attack, you need to work on this aspect. Moreover, the following are some measures to prevent CORS attacks and protect web applications.

Customized Headers

Customizing HTTP headers can prevent malicious cross-origin requests. Indeed, you can use the ‘Access-Control-Allow-Headers’ response header to allow or disallow certain headers. It helps to define the headers that can be used during an actual request. It uses the following syntax.

Access-Control-Allow-Headers: [<header-name>[, <header-name>]*]

Access-Control-Allow-Headers: *

How can it protect from a malicious cross-origin request? It can restrict the types of headers that can be sent in a cross-origin request. For example, you can set ‘Access-Control-Allow-Credentials' if the cross-origin request needs cookies.

Using a Whitelist

Another effective measure to prevent the Cross-Origin Resource Sharing vulnerability is using a whitelist of trusted domains. After this, the web application will permit cross-origin requests if they are from a trusted domain or origin.

You can customize the “Access-Control-Allow-Origin" HTTP header to include a list of trusted origins. After this, if an attacker attempts to send a request from a malicious domain, the request will not be allowed as it won’t match with the whitelisted domains.

Restrict HTTP Methods

Pick and choose the HTTP methods allowed to make cross-origin requests as they can help prevent vulnerabilities from CORS. Make sure that your web application uses safe HTTP methods for any cross-origin request. Avoid methods like PUT, PATCH, and DELETE, and use safe methods like GET, POST, and HEAD. It is best to utilize the “Access-Control-Allow-Methods" HTTP header to define methods that are allowed.

Preflight Requests

It helps to verify a domain before making an actual request. Web browsers make a preflight request to check if the cross-origin request is allowed. It can help to prevent unwanted requests by verifying a cross-origin request with the target server.

Vulnerability Scanning

Vulnerabilities are the common root cause behind cyberattacks. You can protect your web applications by identifying and removing these vulnerabilities such as CORS. For this, you need an advanced web app security scanner that can detect all types of vulnerabilities and give a detailed report. Finding and resolving vulnerabilities will help you improve your security posture and prevent cyberattacks.

To Wrap Up

CORS helps improve the security of your web application on the client side. However, it’s not the only layer for defense. In fact, it cannot completely safeguard your web apps from attacks like cross-site scripting. To make it worse, when configured incorrectly, it can even be a security risk.

Nevertheless, you can utilize security testing methods like DAST to identify CORS misconfigurations and other vulnerabilities. It will help to strengthen the security of your web apps and APIs. ZeroThreat is an advanced DAST tool and offers AI-powered vulnerability scanning.

With ZeroThreat, you can discover common vulnerabilities such as OWASP Top 10, or go beyond it with OAST to identify complex vulnerabilities. It is user-friendly and scans web apps in minutes; even complex ones are scanned quickly. Despite its speed, it offers the most accurate results.

Let’s try it for free and secure your web applications.

Frequently Asked Questions

What are the different types of CORS requests?

They are of three types as follows:

  • Simple requests
  • Preflight requests
  • Requests with credentials

Is CORS handled on the client side or the server side?

Is CORS used only in web browsers?

What is the Best Practice to Enable CORS?

Explore ZeroThreat

Automate security testing, save time, and avoid the pitfalls of manual work with ZeroThreat.