QA
Beginner LevelWeb Security & Cyber Defense

What is Path Traversal (Directory Traversal) and how do you sanitize file path parameters?

❓ Interview Prompt: Explain Path Traversal (`../`), accessing restricted OS files (`/etc/passwd`), `path.basename()`, and path normalization.

Path Traversal (Directory Traversal) allows attackers to read arbitrary files on the server operating system by manipulating file path variables:

Attack Mechanics:

An API endpoint takes a filename parameter: 'GET /api/v1/download?file=report.pdf'.

An attacker requests: 'GET /api/v1/download?file=../../../../etc/passwd'.

If the code concatenates paths (''/var/www/uploads/' + filename'), the OS traverses parent directories and returns system files!

Code Implementation Example

typescript
import path from 'path';

app.get('/api/v1/download', (req, res) => {
  const filename = req.query.file as string;
  
  // ✅ Strip path traversal sequences using path.basename()
  const safeFilename = path.basename(filename);
  const safePath = path.join('/var/www/uploads', safeFilename);

  // Verify path stays inside base directory!
  if (!safePath.startsWith('/var/www/uploads')) {
    return res.status(403).json({ error: 'Invalid path' });
  }
  res.sendFile(safePath);
});
💡Sanitizing input file paths with path.basename() and base directory validation.
🎯 Interview Key Takeaway

Sanitize file path parameters with path.basename() to strip parent directory traversal sequences.

#Path Traversal#File Security#Sanitization#Beginner
Back to all Web Security & Cyber Defense Questions→

More Web Security & Cyber Defense Interview Questions

Beginner LevelSecurity & Web Security

Explain OWASP Top 10 vulnerabilities (XSS, CSRF, SQL Injection) and their defenses.

Beginner LevelSecurity & Web Security

What are the 3 types of XSS (Stored, Reflected, DOM-based) and how do they differ?

Beginner LevelSecurity & Web Security

How do Parameterized Queries (Prepared Statements) prevent SQL Injection attacks?