Skip to content

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

FieldValue
IDCODE-0196
CategoryInjection
SeverityMEDIUM
CWECWE-22
ConfidenceHIGH
ImpactHIGH
LikelihoodMEDIUM
ExploitabilityEASY
TagsPath Traversal, File System
OWASPA5:2017-Broken Access Control, A01:2021-Broken Access Control