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:
- Set up development environment with two applications
- Test ambiguous CORS policy (*)
- Test less-ambiguous CORS policy (localhost pattern)
- Test specific CORS policy (exact origin match)
- 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:
- Navigate to http://localhost:5001 (real app)
- Navigate to http://localhost:5002 (malicious app)
- Try logging in with credentials:
Username: DemoUser
Password: password
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:
- MDN Web Docs: CORS
- OWASP CORS Security Cheat Sheet
- Express CORS middleware documentation