← Back to Baseline

Why it Matters

Path traversal happens when attackers use sequences like ../ in file paths to move outside the intended directory. If the code does not check paths, attackers may read sensitive files (e.g., /etc/passwd, app/etc/env.php) or overwrite important data.

File access in Magento must be restricted to safe directories. Validating and normalizing file paths stops attackers from escaping into system folders. Adding these protections keeps secrets, configs, and code safe from unauthorized access.

Verification Steps

Manual

# Search for unsafe file access in custom modules
grep -R "file_get_contents(" app/code
grep -R "fopen(" app/code
grep -R "require" app/code

# Check if user input is validated before being used in file paths

Remediation / Fix Guidance

  1. Always normalize file paths using realpath() before use.
  2. Restrict file operations to known safe base directories.
  3. Reject any path that resolves outside of the expected folder.
  4. Use Magento’s file storage APIs instead of raw PHP functions when possible.

Examples

Fail Example
// Unsafe, uses user input directly
$path = $_GET['file'];
echo file_get_contents('media/' . $path);
Pass Example
// Safe, normalize and check path
$baseDir = realpath('media/');
$file = realpath($baseDir . '/' . $path);

if ($file !== false && strpos($file, $baseDir) === 0) {
    echo file_get_contents($file);
} else {
    throw new Exception("Invalid file path");
}

References