CSRF Attack Prevention Exercise

Understanding the Problem

Cross-Site Request Forgery (CSRF) is like a forged check - someone else trying to make transactions using your signature. In this exercise, we need to:

Devising a Plan

  1. Set up both applications:
  2. Log in as DemoUser to demonstrate vulnerability
  3. Execute the CSRF attack through malicious app
  4. Implement CSRF protection
  5. Verify protection works

Executing the Plan

Step 1: Initial Setup

# 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

Step 2: Understanding the Attack

The attack flow works like this:

  1. User logs into legitimate site at localhost:5001
  2. User clicks malicious link
  3. Malicious site uses stored credentials to make requests
  4. Real site accepts requests thinking they're legitimate

Step 3: Implementing Protection

In real-app/backend/app.js, enable CSRF protection:

// Enable CSRF protection
app.use(csurf({
    cookie: {
        secure: process.env.NODE_ENV === 'production',
        sameSite: process.env.NODE_ENV === 'production' && "Strict",
        httpOnly: true
    }
}));

In frontend JavaScript files, add CSRF token to requests:

// Add to fetch requests
headers: {
    'XSRF-Token': getCookie('XSRF-Token')
}

Verifying the Solution

To verify our protection works:

  1. Submit tweet in real application - should succeed
  2. Try submitting through malicious app - should fail

Real World Applications

CSRF protection is crucial in:

Additional Protection Methods

Beyond CSRF tokens, other protection methods include:

Common Mistakes to Avoid

Further Learning Resources

File Structure Reference

real-app/
├── backend/
│   └── app.js         // Main server file with CSRF protection
├── frontend/
│   └── js/
│       ├── home.js    // Frontend CSRF token handling
│       ├── login.js   // Login form protection
│       ├── nav.js     // Navigation protection
│       └── tweet-form.js // Tweet submission protection