32 examples
Path traversal
Unauthorized directory access via manipulated paths.
[ FAQ1 ]
What is path traversal?
Path traversal, also known as directory traversal, is a security vulnerability where an attacker crafts malicious input to exploit insecure file handling, allowing them to navigate outside the intended directory structure. By using special characters like
../
in file paths, attackers attempt to access sensitive system files, configuration data, or other restricted resources. Path traversal vulnerabilities occur due to inadequate validation and sanitization of user-supplied file paths, leading to potential data breaches, information disclosure, or even full system compromise.[ FAQ2 ]
How to prevent path traversal vulnerabilities
To prevent path traversal vulnerabilities, always validate and sanitize user inputs thoroughly before using them to access the file system. Use strict allowlisting to ensure file operations remain confined within secure, intended directories. Normalize file paths to resolve and eliminate special characters (
../
, ./
) and ensure final paths remain within defined directory boundaries. Employ secure APIs or built-in language methods specifically designed for safe file handling, reducing the risk of traversal attacks. Regularly review and test your application's file-handling logic and adopt secure coding practices, consistently applying file path validation across all parts of your system.
diff block
greptile
logic: Using string.includes() for URL path matching is vulnerable to path traversal attacks. Consider using exact path matching or a URL parser.
suggested fix
// Authentication is handled on a route-level here.
+ if (req.url === "/api/v1/workflow-integrations/microsoft-teams/message-endpoint") {
return;
}
diff block
greptile
logic: potential path traversal vulnerability - file_path should be sanitized before use in file operations
suggested fix
file_path = req.url_match.group(1)
+ # Prevent path traversal by removing path separators and parent directory references
+ file_path = file_path.replace('..', '').replace('/', '').replace('\\', '')
diff block
greptile
logic: Path traversal vulnerability: video_filename needs to be sanitized before joining with VIDEOS_DIR
suggested fix
+ if "/" in video_filename or "\\" in video_filename:
+ raise HTTPException(status_code=400, detail="Invalid filename")
video_path = VIDEOS_DIR / video_filename
diff block
greptile
logic: Path traversal vulnerability: fileName should be sanitized before joining with storageDir
suggested fix
+ const updatedFileName = fileName.replace('local://', '').replace(/\.\./g, '')
+ const normalizedPath = path.normalize(updatedFileName)
+ if (normalizedPath.startsWith('..')) throw new Error('Invalid file path')
+ const filePath = path.join(this.storageDir, normalizedPath)
if (!fs.existsSync(filePath)) return null
diff block
greptile
logic: Key parameter in delete URL path is not escaped. Use encodeURIComponent to prevent path traversal attacks.
```suggestion
buildConfig
+ ? `${instanceUrl}/app/rest/buildTypes/${encodeURIComponent(buildConfig)}/parameters/${encodeURIComponent(key)}`
+ : `${instanceUrl}/app/rest/projects/id:${encodeURIComponent(project)}/parameters/${encodeURIComponent(key)}`,
```
diff block
greptile
logic: Project ID is not properly escaped in URL path. Use encodeURIComponent for project and buildConfig parameters to prevent path traversal.
```suggestion
const { data } = await request.get<TTeamCityListVariablesResponse>(
buildConfig
+ ? `${instanceUrl}/app/rest/buildTypes/${encodeURIComponent(buildConfig)}/parameters`
+ : `${instanceUrl}/app/rest/projects/id:${encodeURIComponent(project)}/parameters`,
{
```
diff block
greptile
logic: path.join with req.path could allow path traversal attacks. Use path.normalize and validate the path doesn't escape the build directory
suggested fix
+ const normalizedPath = path.normalize(req.path).replace(/^\.+/g, '');
+ const filePath = path.join(__dirname, 'build', normalizedPath);
+ if (!filePath.startsWith(path.join(__dirname, 'build'))) {
+ return res.status(403).send('Forbidden');
}
diff block
greptile
logic: Potential security risk - classpath resource loading without path validation could allow path traversal if templateName contains '../' sequences
suggested fix
+ if (templateName.contains("../")) {
+ throw new IllegalArgumentException("Invalid template name: " + templateName);
+ }
try (InputStream is = resourceLoader.getResource("classpath:/" + templateName).getInputStream()) {
diff block
greptile
logic: Potential path traversal vulnerability by directly concatenating fileLocation into the resource path. Consider using Path.normalize() or similar sanitization.
suggested fix
+ registry.addResourceHandler("/files/**").addResourceLocations("file:///" + new File(fileLocation).toPath().normalize().toString() + "/");
diff block
greptile
logic: No validation that newName is a valid filename. Could allow injection of path traversal characters.
suggested fix
async (_event, projectRoot: string, imageName: string, newName: string) => {
+ if (newName.includes('/') || newName.includes('\\')) {
+ throw new Error('Invalid filename: must not contain path separators');
+ }
const imagePath = await renameImageInProject(projectRoot, imageName, newName);
return imagePath;
diff block
greptile
logic: Vimeo ID extraction is unsafe - could allow path traversal if URL is malformed. Add URL validation before splitting.
diff block
greptile
style: URL path components (upload_id and file_name) should be properly URL-encoded to prevent path traversal attacks and handle special characters
suggested fix
"{}/media/user-avatar/{}/{}",
util::url::to_string_without_slash(
&config.server().unwrap().rivet.api_public.public_origin()
),
+ url::form_urlencoded::byte_serialize(upload_id.as_bytes()).collect::<String>(),
+ url::form_urlencoded::byte_serialize(file_name.as_bytes()).collect::<String>()
)
diff block
greptile
style: No validation on file name or content type before saving, potential path traversal vulnerability
suggested fix
+ destinationDir.mkdirs();
+ String sanitizedFileName = new File(myFile.getOriginalFilename()).getName();
+ myFile.transferTo(new File(destinationDir, sanitizedFileName));
diff block
greptile
logic: Path traversal vulnerability - filename is not sanitized before resolving against the destination path
suggested fix
+ var sanitizedFilename = new File(multipartFile.getOriginalFilename()).getName(); // Get just the filename part
+ var destinationFile = destinationDir.toPath().resolve(sanitizedFilename);
Files.deleteIfExists(destinationFile);
diff block
greptile
logic: Add input validation to prevent path traversal via malicious context names
suggested fix
name: string;
+ if (input.name.includes('/') || input.name.includes('\\')) {
+ return 'Invalid context name';
+ }
Want to avoid this bug in your codebase? Try Greptile.
Avoid this bug!