# CORS Misconfiguration

### CORS Misconfiguration

#### Description

CORS (Cross-Origin Resource Sharing) misconfiguration occurs when a web application improperly configures its CORS policy, allowing unauthorized domains to access its resources, leading to potential data leaks or unauthorized actions.

#### Example with Scenario

**Scenario:** A web application has a misconfigured CORS policy that allows any origin to access its API. An attacker can exploit this to steal sensitive data by making requests from a malicious site.

#### Payloads and Test Cases

**Payloads**

1. **Wildcard Origin:**

   ```http
   Origin: http://evil.com
   ```
2. **Insecure Allow-Origin Header:**

   ```http
   Access-Control-Allow-Origin: *
   ```
3. **Allowed Methods:**

   ```http
   Access-Control-Allow-Methods: GET, POST, PUT, DELETE
   ```

**Test Cases**

1. **Wildcard Origin:**
   * **Payload:**

     ```http
     Origin: http://evil.com
     ```
   * **Test Case:**

     ```javascript
     // Send a request with a malicious origin
     sendCORSRequest("http://evil.com", "/sensitive-data")
     // Verify if the server responds with sensitive data
     checkForSensitiveDataInResponse()
     ```
2. **Insecure Allow-Origin Header:**
   * **Payload:**

     ```http
     Access-Control-Allow-Origin: *
     ```
   * **Test Case:**

     ```javascript
     // Send a request from any origin
     sendCORSRequest("http://any-origin.com", "/sensitive-data")
     // Verify if the server responds with sensitive data
     checkForSensitiveDataInResponse()
     ```
3. **Allowed Methods:**
   * **Payload:**

     ```http
     Access-Control-Allow-Methods: GET, POST, PUT, DELETE
     ```
   * **Test Case:**

     ```javascript
     // Send a request using an allowed method
     sendCORSRequest("http://allowed-origin.com", "/sensitive-data", "POST")
     // Verify if the server processes the request
     checkForSensitiveDataInResponse()
     ```

#### Mitigation

1. **Restrict Allowed Origins:**
   * Specify a strict allow-list of trusted origins.
   * Avoid using wildcard (\*) in the Access-Control-Allow-Origin header.
2. **Limit Allowed Methods:**
   * Restrict the allowed HTTP methods to only those necessary.
   * Avoid allowing all methods (e.g., GET, POST, PUT, DELETE).
3. **Validate Preflight Requests:**
   * Validate and properly handle preflight OPTIONS requests.
   * Ensure the Access-Control-Allow-Origin and other headers are correctly set.
4. **Use Credentials Securely:**
   * Avoid using `Access-Control-Allow-Credentials: true` unless necessary.
   * Ensure the allowed origins are secure when using credentials.
5. **Content Security Policy (CSP):**
   * Implement a strict Content Security Policy to mitigate the impact of CORS misconfigurations.
   * Use CSP to control the sources of content and reduce the risk of data leaks.
