Improper limitation of a pathname to a restricted directory ('Path Traversal')
Description
The application dynamically constructs file or path information. If the path information comes from user-supplied input, it could be abused to read sensitive files, access other users' data, or aid in exploitation to gain further system access.
Examples
Insecure Code
typescript
const userData = {userFilename: userSuppliedFilename};
const fullPath = './' + userData.userFilename;Secure Code
typescript
const userData = {userFilename: userSuppliedFilename, id: crypto.randomUUID()};
const basePath = '/app/restricted/';
const joinedPath = path.join(basePath, userData.id);
const fullPath = path.normalize(joinedPath);
if (!fullPath.startsWith(basePath)) {
console.log("Invalid path specified!");
}Remediation
Use a whitelist approach to validate user input and ensure it does not contain malicious path traversal characters. Consider using `path.normalize` to resolve and validate the path information prior to processing any file functionality.
Rule Details
| Field | Value |
|---|---|
| ID | CODE-0196 |
| Category | Injection |
| Severity | MEDIUM |
| CWE | CWE-22 |
| Confidence | HIGH |
| Impact | HIGH |
| Likelihood | MEDIUM |
| Exploitability | EASY |
| Tags | Path Traversal, File System |
| OWASP | A5:2017-Broken Access Control, A01:2021-Broken Access Control |