path traversal attack - file upload vulnerability

Path Traversal in File Uploads: How Developers Create Their Own Exploits

When File Uploads Turn into File Access

A single insecure upload handler can open the door to a full path traversal attack and file upload vulnerability. When developers concatenate filenames directly with upload paths, attackers can submit malicious filenames like ../../etc/passwd to escape directories and access sensitive files. This type of path traversal turns a simple upload API into a powerful file access exploit, especially when the application runs with elevated permissions.

⚠️Insecure example, for educational purposes only. Do not use in production.

// Vulnerable upload handler, file upload vulnerability
[HttpPost("/upload")]
public async Task<IActionResult> Upload(IFormFile file)
{
    var path = Path.Combine("uploads/", file.FileName);  // No validation
    using var stream = new FileStream(path, FileMode.Create);
    await file.CopyToAsync(stream);
    return Ok("File uploaded!");
}

An attacker can upload a file named ../../web.config to overwrite or read restricted files,  a classic path traversal attack.

Secure version:

// Safe upload with validation and canonicalization
[HttpPost("/upload")]
public async Task<IActionResult> Upload(IFormFile file)
{
    var fileName = Path.GetFileName(file.FileName); // strip directories
    var targetDir = Path.GetFullPath("uploads/");
    var safePath = Path.Combine(targetDir, fileName);


    if (!safePath.StartsWith(targetDir))
        return BadRequest("Invalid file path");


    using var stream = new FileStream(safePath, FileMode.Create);
    await file.CopyToAsync(stream);
    return Ok("File securely uploaded!");
}

Educational note: Always canonicalize paths with Path.GetFullPath() and check that the result stays within your upload directory. Never trust a file.FileName directly.

Developer Mistakes That Enable Path Traversal

Most file upload vulnerabilities that lead to path traversal come from rushed code and missing validation. Common developer errors include:

  • Concatenating user input directly into filesystem paths
  • Trusting Content-Type or extension validation alone
  • Skipping normalization of paths before saving

Reusing temporary folders across requests or microservices

⚠️Insecure example, for educational purposes only. Do not use in production.

# Flask example vulnerable to path traversal attack
@app.route('/upload', methods=['POST'])
def upload():
    file = request.files['file']
    file.save('uploads/' + file.filename)
    return 'Uploaded'

Attackers can bypass this simple concatenation to traverse directories (../../app.py) and write or overwrite arbitrary files. Secure version:

# Safe file upload validation
from werkzeug.utils import secure_filename
@app.route('/upload', methods=['POST'])
def upload():
    file = request.files['file']
    name = secure_filename(file.filename)
    path = os.path.join('uploads', name)
    file.save(path)
    return 'Securely uploaded'

Educational note: Use framework-provided helpers like secure_filename and enforce allowlisted extensions. Never manually concatenate input into file paths.

Exploitation in Real Pipelines and Microservices

Path traversal attacks don’t only happen in public endpoints. They often appear inside CI/CD systems, artifact repositories, or microservices that manage uploaded files. For example, a file upload vulnerability in a build artifact manager may let an attacker overwrite build scripts or inject malicious files into shared runners.

⚠️Insecure example, for educational purposes only. Do not use in production.

# Never expose real tokens, credentials, or internal URLs in pipelines
- name: Store build artifact
  run: cp $UPLOAD_PATH/$FILENAME /var/artifacts/$FILENAME

If $FILENAME isn’t validated, a crafted ../../../etc/passwd value can overwrite critical system files during deployment, a real-world path traversal attack. Secure version: 

# Safer artifact storage guardrail
- name: Store build artifact securely
  run: |
    SAFE_NAME=$(basename "$FILENAME")
    cp "$UPLOAD_PATH/$SAFE_NAME" /var/artifacts/"$SAFE_NAME"

Educational note: In pipelines, sanitize all dynamic path variables. Limit write operations to controlled directories to prevent filesystem escape during builds or deployments.

Preventing Path Traversal in Upload Logic

Mitigating path traversal starts with strong input validation and isolation. Treat filenames and paths as untrusted input from the start, especially when handling uploaded files.

Best Practices

  1. Normalize and canonicalize all paths before using them.
  2. Restrict uploads to a dedicated directory outside the web root.
  3. Enforce allowlists for file extensions and MIME types.
  4. Never reuse temporary folders between sessions or users.
  5. Use containerized storage for uploaded files when possible.

Mini preventive checklist

  • Validate every filename with Path.GetFileName() or equivalent.
  • Resolve full paths and verify directory boundaries.
  • Apply extension and MIME allowlists.
  • Use separate upload folders per user or session.
  • Include upload scanning and validation in CI/CD tests.

Educational note: Every file upload handler is a potential path traversal attack vector. Build defense-in-depth by validating, isolating, and scanning all file-handling code.

How Xygeni Detects and Blocks Unsafe Upload Flows

Xygeni Code Security scans codebases and pipelines to detect path traversal patterns before they reach production. It flags insecure path concatenation, missing canonicalization, and dangerous file operations in both code and CI/CD scripts.

Functional snippet, with control guardrail:

# Secure enforcement with Xygeni
- name: Enforce secure upload and path handling
  run: dotnet xygeni enforce --rules uploads,path,security --fail-on-risk

Educational note: Integrating Xygeni into your pipeline ensures that file upload vulnerabilities and path traversal attacks are caught automatically during build validation.

Closing the Gap: Preventing Your Next Path Traversal Attack

A single path traversal bug in a file upload endpoint can give attackers access to your server’s filesystem. Review upload handlers for unsafe concatenations, normalize all paths, and never trust user-controlled filenames. Add vulnerability scanning tools like Xygeni Code Security to your DevSecOps pipeline to detect path traversal attacks and file upload vulnerabilities before they ship. In security, every file saved must be treated as code executed!

sca-tools-software-composition-analysis-tools
Prioritize, remediate, and secure your software risks
7-day free trial
No credit card required

Secure your Software Development and Delivery

with Xygeni Product Suite