Monitoring and Responding to SSRF Incidents

Monitoring and Responding to SSRF Incidents

Introduction

Welcome to the third lesson of our Server-Side Request Forgery (SSRF) Prevention in Express course! We've covered what SSRF is and how to prevent it in Express applications. Now, let's focus on an equally important aspect: monitoring and responding to SSRF incidents. Even with robust prevention measures, it's essential to detect and respond to potential attacks quickly. Let's dive in! 🔍

The Importance of Monitoring

Monitoring is a critical component of a comprehensive security strategy. It allows you to:

  1. Detect potential SSRF attacks in real-time
  2. Collect data for forensic analysis
  3. Improve your security measures based on attack patterns
  4. Respond quickly to minimize damage

Let's explore how to set up effective monitoring for SSRF vulnerabilities in Express applications.

Setting Up Request Logging

The first step in monitoring is to set up comprehensive request logging. This allows you to track and analyze all incoming requests, making it easier to detect suspicious activity:

TypeScript
import express from 'express';
import morgan from 'morgan';
import fs from 'fs';
import path from 'path';

const app = express();

// Create a write stream for access logs
const accessLogStream = fs.createWriteStream(
  path.join(__dirname, 'access.log'),
  { flags: 'a' }
);

// Set up request logging
app.use(morgan('combined', { stream: accessLogStream }));

// Example route
app.get('/', (req, res) => {
  res.send('Hello, world!');
});

app.listen(3000, () => {
  console.log('Server running on port 3000');
});

In this example, we use the morgan middleware to log all HTTP requests to a file. The 'combined' format includes information such as the IP address, request method, URL, status code, and user agent.

Advanced SSRF Detection

To detect potential SSRF attacks, we need to implement more sophisticated monitoring. Let's create a middleware that specifically looks for suspicious URL patterns:

TypeScript
import express from 'express';
import { URL } from 'url';

const app = express();
app.use(express.json());

// SSRF detection middleware
const ssrfDetectionMiddleware = (req: express.Request, res: express.Response, next: express.NextFunction) => {
  // Extract URL from request body, query, or params
  const url = req.body.url || req.query.url || '';
  
  if (url && typeof url === 'string') {
    try {
      const parsedUrl = new URL(url);
      
      // Check for suspicious patterns
      const suspiciousPatterns = [
        '127.0.0.1',
        'localhost',
        'internal',
        '169.254.169.254', // Cloud metadata service
        'file:',
        'dict:',
        'gopher:',
        '10.',
        '172.16.',
        '192.168.'
      ];
      
      const isSuspicious = suspiciousPatterns.some(pattern => 
        parsedUrl.hostname.includes(pattern) || url.includes(pattern)
      );
      
      if (isSuspicious) {
        // Log the suspicious request
        console.warn(`POTENTIAL SSRF ATTACK: ${req.ip} tried to access ${url}`);
        
        // You could also trigger an alert or save to a security log
        alertAdmin('Potential SSRF Attack', `IP: ${req.ip}, URL: ${url}`);
      }
    } catch (error) {
      // URL parsing failed, but we'll continue processing the request
    }
  }
  
  next();
};

// Apply the middleware
app.use(ssrfDetectionMiddleware);

// Example route
app.post('/fetch-url', async (req, res) => {
  // Your secure URL fetching logic here
  res.json({ success: true });
});

function alertAdmin(subject: string, message: string) {
  // Implementation of alerting mechanism (email, SMS, etc.)
  console.log(`ALERT: ${subject} - ${message}`);
}

app.listen(3000, () => {
  console.log('Server running on port 3000');
});

This middleware checks for suspicious URL patterns that might indicate an SSRF attack attempt. When detected, it logs the incident and triggers an alert.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal