Course contentsShow
← Security
Lesson 1233 of 3,05225. Application Security - Secure CodingFree lesson

File Path and Filesystem API Risks

Identify dangerous filesystem operations that enable path traversal and learn to safely construct and validate file paths.

File Path and Filesystem API Risks

You'll learn how seemingly innocent file operations can become gateways for attackers to read, write, or delete files anywhere on your system.

The Core Risk

When your application accepts file paths from users—whether explicitly (like a filename in a form) or implicitly (like a URL parameter)—you're allowing them to tell your code which files to access. Without proper validation, an attacker can use special path sequences like ../ (parent directory) to "traverse" out of your intended directory and access sensitive files anywhere on the filesystem.

How Path Traversal Works

Imagine you run a photo gallery where users request images like /images/profile.jpg. Your code might construct:

filepath = "/var/www/images/" + user_input

If an attacker submits ../../../etc/passwd as input, the final path becomes:

/var/www/images/../../../etc/passwd

This resolves to /etc/passwd—your system's password file!

Dangerous Operations

Any filesystem API that opens, reads, writes, or deletes files based on user input is risky:

  • Opening files without path validation
  • Using user input directly in path construction
  • Trusting filename extensions or MIME types
  • Not canonicalizing paths before validation

The Safe Path Forward

  1. Never concatenate user input directly into file paths
  2. Validate against an allowlist of permitted filenames or directories
  3. Canonicalize paths first, then check they're within your base directory
  4. Use framework-provided safe file APIs that abstract path handling
  5. Reject paths containing .., absolute paths, or symbolic links

Key Takeaway: File operations with user-controlled paths are extremely dangerous—always validate that the resolved, canonical path stays within your intended directory boundary before any filesystem access occurs.