CORS Policy Exercise

Understanding the Problem

We need to understand how different CORS (Cross-Origin Resource Sharing) policies affect web application security, specifically:

Input: Web requests from different origins (localhost:5001 and localhost:5002)

Output: Different levels of access control based on CORS policy configuration

Real-world analogy: Think of CORS like a bouncer at a club. The bouncer (browser) checks IDs (origins) against the guest list (CORS policy) before allowing entry (access to resources).

Devising a Plan

Whiteboard Plan:

  1. Set up development environment with two applications
  2. Test ambiguous CORS policy (*)
  3. Test less-ambiguous CORS policy (localhost pattern)
  4. Test specific CORS policy (exact origin match)
  5. Document results and security implications

Implementing the Solution

File Structure

project_root/
├── malicious_app/
│   └── package.json
└── real_app/
    ├── backend/
    │   └── app.js
    └── package.json

Solution 1: Ambiguous CORS Policy

Location: real_app/backend/app.js

// Most permissive CORS policy
app.use(cors({
    origin: "*"  // Allows all origins
}));

Solution 2: Less-Ambiguous CORS Policy

// Pattern matching CORS policy
app.use(cors({
    origin: /^http:\/\/localhost/  // Matches any localhost origin
}));

Solution 3: Specific CORS Policy

// Strict CORS policy
app.use(cors({
    origin: "http://localhost:5001"  // Only allows specific origin
}));

Step-by-Step Implementation Instructions

1. Set up the development environment:

# Terminal 1 - Malicious App
cd malicious_app
npm install
npm run dev

# Terminal 2 - Real App
cd real_app
npm install
npm run migrate
npm run seed
npm run dev

2. Testing each CORS policy:

Looking Back and Security Implications

Important security lessons learned:

1. Ambiguous Policy (*):
- Allows all origins
- Dangerous for sensitive operations
- Some browsers block it for non-GET requests

2. Less-Ambiguous Policy (localhost pattern):
- Allows any localhost origin
- Better than *, but still too permissive
- Suitable for development only

3. Specific Policy (exact origin):
- Most secure option
- Prevents cross-origin attacks
- Recommended for production

Real-world Application: Many companies face CORS-related security issues. For example, in 2019, a major financial institution had a CORS misconfiguration that could have allowed attackers to access customer data from malicious sites.

Additional Learning Resources

For further understanding: