Potential fix for code scanning alert no. 24: Uncontrolled data used in path expression #12
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.
Potential fix for https://github.com/xebia/ShipServiceApp/security/code-scanning/24
In general, to fix uncontrolled path usage, you must ensure that user input cannot cause the application to read or write outside an intended directory. This is typically done by combining the user input with a trusted base directory, resolving the combined path to its canonical form, and then checking that the resolved path is still inside the base directory. Alternatively, if the input should be just a simple filename, you can reject any input that contains path separators or
...For this endpoint, the intent is clearly to only serve files from
/var/www/files/. The minimal change that preserves existing behavior is to (1) define a base directory, (2) safely combine it withfilenameusingPath.Combine, (3) canonicalize the resulting path withPath.GetFullPath, and (4) verify that the canonical path starts with the canonical base directory plus a directory separator; if not, returnBadRequest. This prevents traversal using..or absolute paths while still allowing all legitimate filenames that live under the base directory.Concretely in
Controllers/VulnerableController.cs, insideDownloadFilewe will:baseDirectorystring set to"/var/www/files".System.IO.Path.Combine(baseDirectory, filename)and thenSystem.IO.Path.GetFullPath(...)to obtainfilePath.baseDirectoryFullPath = System.IO.Path.GetFullPath(baseDirectory)and checkfilePath.StartsWith(baseDirectoryFullPath + System.IO.Path.DirectorySeparatorChar). If this fails, returnBadRequest("Invalid file path.").We do not need any new
usingstatements because we already refer toSystem.IO.Filefully qualified, and we can similarly callSystem.IO.Pathfully qualified.Suggested fixes powered by Copilot Autofix. Review carefully before merging.