HIGH CWE-22 Authentication & Authorization

CWE-22 in APIs

What is CWE-22?

CWE-22 (Improper Limitation of a Pathname to a Restricted Directory) is a critical security weakness where software uses external input to construct a pathname that should be within a restricted directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location outside the restricted directory. This is commonly known as a directory traversal vulnerability or "path traversal" attack.

The weakness allows attackers to access files and directories that are outside the intended restricted directory. By manipulating file path inputs with special characters like "../" (dot-dot-slash), attackers can navigate up the directory tree and potentially access sensitive system files, configuration files, or other restricted resources.

According to the CWE description: "The software uses external input to construct a pathname that should be within a restricted directory, but it does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory."

CWE-22 in API Contexts

In API contexts, CWE-22 manifests in several critical ways that are particularly dangerous for modern web services. APIs often handle file operations dynamically based on user input, making them prime targets for path traversal attacks.

Common API scenarios vulnerable to CWE-22 include:

  • File upload/download endpoints: APIs that allow users to specify filenames or paths for file operations without proper validation
  • Configuration management APIs: Endpoints that read or write configuration files based on user-supplied paths
  • Template rendering APIs: Services that load template files or content from disk using path parameters
  • Database backup APIs: Endpoints that generate backups to user-specified locations
  • Static asset serving APIs: Services that serve files from a directory based on URL parameters

The risk is amplified in APIs because they often run with elevated privileges and serve multiple clients. A successful path traversal attack can expose sensitive data like API keys, database credentials, or source code that could lead to further compromise.

Consider this vulnerable API endpoint:

app.get('/download/:filename', (req, res) => {
  const filePath = `/uploads/${req.params.filename}`;
  res.download(filePath);
});

An attacker could request /download/../../../etc/passwd to read system files, or /download/../../../config/api-keys.json to access sensitive credentials.

Detection

Detecting CWE-22 requires both static code analysis and dynamic testing approaches. middleBrick's black-box scanning methodology is particularly effective at identifying path traversal vulnerabilities without requiring source code access.

middleBrick tests for CWE-22 by:

  • Input fuzzing: Submitting path traversal payloads like ../../etc/passwd, ..\..\..\windows\system32\drivers\etc\hosts, and URL-encoded variations
  • Canonicalization testing: Verifying that the API properly resolves and validates the final path after all symbolic links and relative components are processed
  • Response analysis: Detecting when file contents are returned, error messages reveal file paths, or access is granted to restricted resources
  • Time-based detection: Measuring response times to identify when the server is attempting to access files outside the intended directory

Beyond automated scanning, developers should implement manual testing strategies:

// Test cases for path traversal
const testPayloads = [
  '../../etc/passwd',
  '../.\./../etc/passwd',
  '%2e%2e%2fetc%2fpasswd', // URL encoded
  '..\\..\\..\\windows\\system32\\drivers\\etc\\hosts',
  '/etc/passwd',
  'subdir/../../etc/passwd'
];

middleBrick's API security scanning provides a comprehensive CWE-22 assessment by testing these patterns across all endpoints that handle file paths, returning a risk score and specific findings with severity levels and remediation guidance.

Remediation

Effective remediation of CWE-22 requires a defense-in-depth approach combining input validation, path canonicalization, and secure coding practices. Here are proven strategies with code examples:

1. Input Validation and Whitelisting

The most effective approach is to validate and whitelist acceptable inputs rather than trying to blacklist dangerous patterns.

// Allow only alphanumeric filenames with specific extensions
const validExtensions = ['.txt', '.pdf', '.jpg'];

function validateFilename(filename) {
  const extension = path.extname(filename).toLowerCase();
  const basename = path.basename(filename, extension);
  
  if (!validExtensions.includes(extension)) {
    throw new Error('Invalid file extension');
  }
  
  if (!/^[a-zA-Z0-9_-]+$/.test(basename)) {
    throw new Error('Invalid characters in filename');
  }
  
  return true;
}

// Usage
app.get('/download/:filename', (req, res) => {
  const filename = req.params.filename;
  
  try {
    validateFilename(filename);
    const filePath = path.join(__dirname, 'uploads', filename);
    
    // Additional canonicalization check
    if (!filePath.startsWith(path.join(__dirname, 'uploads'))) {
      throw new Error('Path traversal attempt detected');
    }
    
    res.download(filePath);
  } catch (error) {
    res.status(400).json({ error: 'Invalid file request' });
  }
});

2. Path Canonicalization

Always resolve paths to their canonical form and verify they remain within the intended directory.

const path = require('path');

function getSafeFilePath(baseDir, userPath) {
  const resolvedPath = path.resolve(baseDir, userPath);
  const canonicalPath = path.normalize(resolvedPath);
  
  // Verify the resolved path starts with the base directory
  if (!canonicalPath.startsWith(path.resolve(baseDir))) {
    throw new Error('Path traversal attempt detected');
  }
  
  return canonicalPath;
}

// Usage
app.get('/config/:section', (req, res) => {
  try {
    const section = req.params.section;
    const configPath = getSafeFilePath('./config-sections', section);
    
    const configData = fs.readFileSync(configPath, 'utf8');
    res.json(JSON.parse(configData));
  } catch (error) {
    res.status(403).json({ error: 'Access denied' });
  }
});

3. Use Safe APIs and Libraries

Leverage libraries designed to prevent path traversal:

// Using safe libraries
const express = require('express');
const safePath = require('safe-path');

app.get('/download/:filename', (req, res) => {
  const filename = req.params.filename;
  
  // safePath ensures the file is within the base directory
  const filePath = safePath('./uploads', filename);
  
  if (!filePath) {
    return res.status(400).json({ error: 'Invalid file path' });
  }
  
  res.download(filePath);
});

4. Principle of Least Privilege

Ensure your application runs with minimal file system permissions:

// Set up restrictive file permissions
const fs = require('fs');
const path = require('path');

// Create uploads directory with restricted permissions
const uploadDir = path.join(__dirname, 'uploads');
if (!fs.existsSync(uploadDir)) {
  fs.mkdirSync(uploadDir, { mode: 0o700 }); // Only readable/writable by owner
}

// Use chroot jail for additional isolation
// (Platform-specific implementation varies)

middleBrick's scanning helps verify these remediation efforts by continuously testing your APIs against path traversal payloads and providing detailed reports on any remaining vulnerabilities.

Frequently Asked Questions

How does CWE-22 differ from other injection vulnerabilities?
CWE-22 specifically targets path manipulation to access unauthorized files and directories, while other injection vulnerabilities (like SQL injection or command injection) target different contexts. Path traversal attacks manipulate filesystem paths rather than database queries or system commands. The key distinction is that CWE-22 exploits how the application handles file paths and directory structures, potentially exposing sensitive files like configuration data, source code, or system files that other injection types cannot access.
Can CWE-22 be exploited in cloud-based APIs?
Yes, CWE-22 remains a critical vulnerability in cloud APIs. Cloud environments often have different filesystem structures, but path traversal attacks can still access sensitive files like cloud configuration files, credentials stored in instance metadata services, or files in shared storage volumes. Cloud-specific targets include IAM configuration files, cloud provider metadata endpoints, and container filesystem paths. The attack surface may differ, but the fundamental weakness of improper path validation remains exploitable in cloud-native applications.