Common Vulnerability Scenarios

Common Vulnerability Scenarios

Scenario 1: User Avatar Upload

// Vulnerable implementation
app.post('/upload-avatar', upload.single('avatar'), (req, res) => {
    // Just save file without proper headers
    res.json({ filename: req.file.filename });
});

app.get('/avatars/:filename', (req, res) => {
    res.sendFile(path.join(__dirname, 'avatars', req.params.filename));
    // Missing security headers!
});

// Secure implementation
app.get('/avatars/:filename', (req, res) => {
    const filename = req.params.filename;
    const filepath = path.join(__dirname, 'avatars', filename);
    
    // Validate filename to prevent directory traversal
    if (filename.includes('..') || filename.includes('/')) {
        return res.status(400).send('Invalid filename');
    }
    
    // Set proper headers
    res.setHeader('X-Content-Type-Options', 'nosniff');
    res.setHeader('Content-Type', 'image/jpeg'); // Force image type
    res.setHeader('Content-Security-Policy', "default-src 'none'; style-src 'unsafe-inline'");
    
    res.sendFile(filepath);
});

Scenario 2: JSON API Endpoints

// Ensure JSON endpoints have correct headers
app.get('/api/data', (req, res) => {
    const data = { 
        users: 100, 
        status: 'active' 
    };
    
    // Set headers before sending
    res.setHeader('Content-Type', 'application/json');
    res.setHeader('X-Content-Type-Options', 'nosniff');
    
    // Prevent JSON from being interpreted as HTML
    res.json(data);
});

// Middleware for all API routes
app.use('/api/*', (req, res, next) => {
    res.setHeader('X-Content-Type-Options', 'nosniff');
    next();
});