HIGH path traversalaws

Path Traversal on Aws

How Path Traversal Manifests in Aws

Path traversal vulnerabilities in Aws applications exploit improper handling of file paths, allowing attackers to access files outside intended directories. In Aws applications, this often occurs when user input is used to construct file paths without proper validation or sanitization.

Consider a typical Aws Express route that serves static files:

app.get('/files/:filename', (req, res) => {
  const filePath = path.join('uploads', req.params.filename);
  res.sendFile(filePath);
});

This code is vulnerable because an attacker can request /files/../../etc/passwd, causing the path.join() function to traverse outside the intended uploads directory. The resulting path resolves to the system's /etc/passwd file.

Aws applications often use the path module's join() or resolve() methods without understanding their behavior with .. segments. The path.join() function simply concatenates paths and normalizes them, but it doesn't prevent directory traversal—it only resolves the path to its canonical form.

Another common Aws-specific scenario involves dynamic template rendering:

app.get('/view/:template', (req, res) => {
  const templatePath = path.join(__dirname, 'templates', req.query.template);
  res.render(templatePath);
});

Here, an attacker could request /view/?template=../../package.json to read the application's package.json file, potentially exposing sensitive configuration details.

Aws applications using the fs module for file operations are particularly vulnerable when constructing paths from user input:

const fs = require('fs');
const filePath = path.join('data', req.body.filename);
const fileContent = fs.readFileSync(filePath, 'utf8');
res.send(fileContent);

If req.body.filename contains ../config, the application reads files outside the intended data directory, potentially exposing database credentials or API keys.

Cloud storage integrations in Aws applications can also suffer from path traversal. When Aws applications interact with AWS S3 or other cloud storage services, improper path handling can lead to unauthorized access:

const AWS = require('aws-sdk');
const s3 = new AWS.S3();
const params = {
  Bucket: 'my-bucket',
  Key: req.query.file
};
s3.getObject(params, (err, data) => {
  if (err) throw err;
  res.send(data.Body);
});

An attacker could manipulate the file parameter to access files in unintended locations within the S3 bucket.

Aws-Specific Detection

Detecting path traversal vulnerabilities in Aws applications requires both static code analysis and dynamic testing. Static analysis tools can identify dangerous patterns where user input is used in path construction without proper validation.

middleBrick's Aws-specific scanning identifies path traversal vulnerabilities by testing for common traversal patterns:

middlebrick scan https://api.example.com --profile aws

The scanner tests endpoints with various traversal payloads:

  • ../ sequences
  • URL-encoded variants like %2e%2e%2f
  • Windows-style ..\ sequences
  • Overlong UTF-8 encodings
  • Null byte injections

middleBrick specifically tests Aws applications for these patterns because they're common in Node.js/Express applications. The scanner examines how the application handles these inputs and whether it reveals sensitive file contents or application structure.

For development environments, you can use safe-path to detect potential traversal issues:

const safePath = require('safe-path');
const sanitized = safePath(filePath);
if (sanitized.startsWith('uploads')) {
  // Safe to use
}

During development, logging path resolution can help identify traversal attempts:

app.use((req, res, next) => {
  console.log('Requested path:', path.resolve(req.path));
  next();
});

This helps developers see when requests attempt to access files outside the application's root directory.

Automated testing with tools like OWASP ZAP or Burp Suite can also identify path traversal vulnerabilities by injecting traversal payloads and observing application responses. Look for differences in response times, error messages, or content that might indicate successful traversal.

Aws-Specific Remediation

Remediating path traversal vulnerabilities in Aws applications requires a defense-in-depth approach. The most effective strategy combines input validation, path normalization, and access control.

First, validate and sanitize user input before using it in file paths:

const path = require('path');
const { validateFileName } = require('./validators');

app.get('/files/:filename', (req, res) => {
  const filename = req.params.filename;
  
  // Validate filename - only allow alphanumeric, hyphens, underscores, and dots
  if (!validateFileName(filename)) {
    return res.status(400).send('Invalid filename');
  }
  
  // Construct path safely
  const safePath = path.join('uploads', filename);
  
  // Verify the resolved path is within the intended directory
  if (!safePath.startsWith(path.join(__dirname, 'uploads'))) {
    return res.status(403).send('Forbidden');
  }
  
  res.sendFile(safePath);
});

The validateFileName function should enforce strict naming conventions:

function validateFileName(name) {
  // Allow only basic filename characters, no directory separators
  const regex = /^[a-zA-Z0-9._-]+$/;
  return regex.test(name);
}

For more robust protection, use the path.normalize() method combined with explicit path validation:

const safeFilePath = (baseDir, userPath) => {
  const normalized = path.normalize(userPath);
  const resolved = path.resolve(baseDir, normalized);
  
  // Ensure the resolved path starts with the base directory
  if (!resolved.startsWith(baseDir)) {
    throw new Error('Path traversal attempt detected');
  }
  
  return resolved;
};

When working with the fs module, always use absolute paths and validate them:

const fs = require('fs');
const getSafeFilePath = (baseDir, relativePath) => {
  const absolutePath = path.resolve(baseDir, relativePath);
  if (!absolutePath.startsWith(baseDir)) {
    throw new Error('Invalid path');
  }
  return absolutePath;
};

const readFileSafely = (baseDir, relativePath) => {
  const safePath = getSafeFilePath(baseDir, relativePath);
  return fs.readFileSync(safePath, 'utf8');
};

For cloud storage interactions, implement similar validation:

const validateS3Key = (key) => {
  // Disallow traversal patterns in S3 keys
  if (key.includes('..') || key.includes('/') || key.includes('\')) {
    throw new Error('Invalid S3 key format');
  }
  return key;
};

const getSafeS3Object = (s3, bucket, key) => {
  const safeKey = validateS3Key(key);
  const params = { Bucket: bucket, Key: safeKey };
  return s3.getObject(params).promise();
};

Consider using dedicated libraries like filehound or glob with strict pattern matching instead of manual path construction. These libraries provide safer APIs for file operations.

Finally, implement proper error handling to avoid information disclosure:

app.get('/sensitive/:file', (req, res) => {
  try {
    const filePath = getSafeFilePath(__dirname, req.params.file);
    const content = fs.readFileSync(filePath, 'utf8');
    res.send(content);
  } catch (err) {
    // Don't reveal whether the file exists or path was invalid
    res.status(404).send('File not found');
  }
});

Related CWEs: inputValidation

CWE IDNameSeverity
CWE-20Improper Input Validation HIGH
CWE-22Path Traversal HIGH
CWE-74Injection CRITICAL
CWE-77Command Injection CRITICAL
CWE-78OS Command Injection CRITICAL
CWE-79Cross-site Scripting (XSS) HIGH
CWE-89SQL Injection CRITICAL
CWE-90LDAP Injection HIGH
CWE-91XML Injection HIGH
CWE-94Code Injection CRITICAL

Frequently Asked Questions

How can I test my Aws application for path traversal vulnerabilities?

Use middleBrick's automated scanning to test your API endpoints for path traversal vulnerabilities. The scanner tests common traversal patterns and Aws-specific code paths. For manual testing, use tools like OWASP ZAP to inject traversal payloads (../, URL-encoded variants) and observe how your application handles them. Look for differences in response times, error messages, or content that might indicate successful traversal.

Does path traversal affect Aws applications using TypeScript?

Yes, path traversal vulnerabilities affect TypeScript applications just as they affect JavaScript applications. The vulnerability exists at runtime regardless of whether your code is written in JavaScript or TypeScript. The same remediation techniques apply—validate and sanitize user input, use absolute paths with validation, and implement proper error handling. TypeScript's static typing can help catch some issues at compile time, but it won't prevent runtime path traversal if you're constructing paths from untrusted input.