Pensar - auto fix for Path Traversal Vulnerability in File Writing Operations #20
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
The code had a path traversal vulnerability (CWE-22) in the
run_locally
function where filenames from user input were directly used to build file paths without proper validation. An attacker could exploit this by using filenames like "../../malicious_file" to write files outside the intended directory.Original vulnerable code:
To fix this, I've implemented:
A helper function
is_safe_path
that usesos.path.abspath
to normalize paths and checks if the resulting file path is safely contained within the specified base directory.Path validation logic in the
run_locally
function that:This approach maintains the core functionality while preventing files from being written outside the intended directory. Rather than rejecting potentially malicious filenames entirely, it sanitizes them to ensure the application continues to work as expected.