Potential fix for code scanning alert no. 1: Arbitrary file access during archive extraction ("Zip Slip")#1087
Potential fix for code scanning alert no. 1: Arbitrary file access during archive extraction ("Zip Slip")#1087smals-jy wants to merge 2 commits into
Conversation
…ring archive extraction ("Zip Slip")
Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com>
|
Warning Review limit reached
More reviews will be available in 22 minutes and 49 seconds. Learn how PR review limits work. Your organization has used up its prepaid credits, and credit purchases are no longer available. Enable the review add-on in the billing tab to keep reviews running — you're only billed for reviews past your plan's rate limits ($0.25/file). ⌛ How to resolve this issue?After more reviews become available, a review can be triggered using the To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based credits. 🚦 How do rate limits work?CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan refill rate. For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, the refill rate gradually slows as usage increases. The highest same-day bursts are limited more strictly. Please see our Fair Usage Limits Policy for further information. ℹ️ Review info⚙️ Run configurationConfiguration used: defaults Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (1)
📝 WalkthroughWalkthroughTwo resource-scanning methods gain path-normalization guards against directory traversal. ChangesDirectory Traversal Prevention
Estimated code review effort🎯 2 (Simple) | ⏱️ ~8 minutes Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
|
@coderabbitai Code doesn't compile because of this change, can you give full code & sutff that must be changed because of that ? Thx |
|
Tip For best results, initiate chat on the files or code changes. 🧩 Analysis chain🏁 Script executed: #!/bin/bash
# Get the PR diff
gh pr view 1087 --repo smals-jy/evs --json files,body,titleLength of output: 1695 🏁 Script executed: #!/bin/bash
# Find ResourceResolver.java
fd ResourceResolver.java --exec cat {}Length of output: 4664 🏁 Script executed: #!/bin/bash
# Get the PR diff to see exactly what changed
gh api repos/smals-jy/evs/pulls/1087/files | jq -r '.[] | "=== " + .filename + " ===\n" + .patch'Length of output: 2635 🏁 Script executed: #!/bin/bash
# Find and cat TableDefinitionReader.java
fd TableDefinitionReader.java --exec cat {}Length of output: 11134
The good news is the actual Zip Slip fix in Here is the corrected private List<File> getFilesWithSuffix(String folderToScan, String fileEndsWith) {
List<File> files = new ArrayList<>();
String fileSeparatorInJarFile = "/";
log.trace("Will try to find this folder on disk: " + folderToScan);
File dirOnDisk = null;
try {
dirOnDisk = IOUtils.getFile(this.getClass().getClassLoader(), folderToScan);
} catch (RuntimeException e) {
}
if (dirOnDisk != null && dirOnDisk.exists()) {
log.trace("folder exists on disk: " + folderToScan);
try {
Files.list(Paths.get(dirOnDisk.getAbsolutePath()))
.filter(path -> StringUtils.endsWith(path.toString(), fileEndsWith))
.forEach(path -> files.add(
IOUtils.getResourceAsFile(path.toString(),
TABLE_NAME_MARKER + StringUtils.substringAfterLast(path.toString(), File.separator))
));
} catch (IOException e) {
e.printStackTrace();
}
} else {
log.trace("Folder does not exist on disk. Will look in jar file for table definitions using path: " + folderToScan);
List<String> matchingJarEntries = ResourceResolver.getMatchingJarEntries(OSUtils.adaptFilePath(folderToScan, fileSeparatorInJarFile));
if (matchingJarEntries != null) {
log.trace("Found " + matchingJarEntries.size() + " jar entries.");
for (String matchingJarEntry : matchingJarEntries) {
String tempFileName = TABLE_NAME_MARKER + StringUtils.substringAfterLast(matchingJarEntry, fileSeparatorInJarFile);
log.trace("Adding matching jar entry: " + matchingJarEntry + ". Name to be used for temp file: " + tempFileName);
File resourceAsFile = IOUtils.getResourceAsFile(fileSeparatorInJarFile + matchingJarEntry, tempFileName);
// NOTE: No path check here — Zip Slip is already prevented upstream in
// ResourceResolver.getMatchingJarEntries() before entries are returned.
log.trace("resource as file: " + resourceAsFile.getAbsolutePath());
files.add(resourceAsFile);
}
}
}
log.info("Found " + files.size() + " files at location: " + folderToScan);
return files;
}And the In summary: just revert the 4 added lines in 🐇 (╯°□°)╯ Revert the 4 added lines in The requested changes have been implemented and a pull request has been created: View PR |
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In
`@core/src/main/java/org/imec/ivlab/core/kmehr/tables/TableDefinitionReader.java`:
- Around line 274-277: The path traversal validation on line 276 is checking the
wrong thing: it validates the extracted temp file path (resourceAsFile) against
folderToScan, but these don't have a parent-child relationship for valid jar
resources, causing all valid resources to be rejected. Instead of validating
resourceAsFile's path, validate the jar entry name directly for directory
traversal patterns (such as containing ".." or starting with "/"). Additionally,
the IOException being thrown will cause a compilation error if not caught or
declared in the method signature, so ensure proper error handling.
In `@core/src/main/java/org/imec/ivlab/core/util/ResourceResolver.java`:
- Around line 92-96: The startsWithIgnoreCase check on line 92 in the
ResourceResolver class allows sibling entries with matching text prefixes (e.g.,
kmehr/tables-old matching kmehr/tables) to pass through, which then fails the
normalized path check on lines 94-95 and aborts the entire scan. Replace the
loose text prefix check with the normalized path comparison logic as the actual
match predicate instead of using it only for validation, and instead of throwing
an exception when a non-contained entry is found, skip it by continuing to the
next iteration of the loop.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: c5a9a018-703b-409a-a601-1368ff947b76
📒 Files selected for processing (2)
core/src/main/java/org/imec/ivlab/core/kmehr/tables/TableDefinitionReader.javacore/src/main/java/org/imec/ivlab/core/util/ResourceResolver.java
| // Validate the resource file path to prevent directory traversal | ||
| if (!resourceAsFile.toPath().normalize().startsWith(new File(folderToScan).toPath().normalize())) { | ||
| throw new IOException("Invalid resource file path: " + resourceAsFile.getAbsolutePath()); | ||
| } |
There was a problem hiding this comment.
Validate the jar entry name, not the extracted temp file path.
Line 276 introduces an uncaught checked IOException, so this method will not compile. Also, resourceAsFile is the extracted/temp file from IOUtils.getResourceAsFile(...), not a child of the classpath folder string in folderToScan, so valid jar resources will be rejected.
Proposed fix
- File resourceAsFile = IOUtils.getResourceAsFile(fileSeparatorInJarFile + matchingJarEntry, tempFileName);
- // Validate the resource file path to prevent directory traversal
- if (!resourceAsFile.toPath().normalize().startsWith(new File(folderToScan).toPath().normalize())) {
- throw new IOException("Invalid resource file path: " + resourceAsFile.getAbsolutePath());
- }
+ Path normalizedFolderToScan = Paths.get(OSUtils.adaptFilePath(folderToScan, fileSeparatorInJarFile)).normalize();
+ Path normalizedJarEntry = Paths.get(matchingJarEntry).normalize();
+ if (!normalizedJarEntry.startsWith(normalizedFolderToScan)) {
+ throw new IllegalArgumentException("Invalid jar entry: " + matchingJarEntry);
+ }
+ File resourceAsFile = IOUtils.getResourceAsFile(fileSeparatorInJarFile + matchingJarEntry, tempFileName);🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In
`@core/src/main/java/org/imec/ivlab/core/kmehr/tables/TableDefinitionReader.java`
around lines 274 - 277, The path traversal validation on line 276 is checking
the wrong thing: it validates the extracted temp file path (resourceAsFile)
against folderToScan, but these don't have a parent-child relationship for valid
jar resources, causing all valid resources to be rejected. Instead of validating
resourceAsFile's path, validate the jar entry name directly for directory
traversal patterns (such as containing ".." or starting with "/"). Additionally,
the IOException being thrown will cause a compilation error if not caught or
declared in the method signature, so ensure proper error handling.
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Potential fix for https://github.com/smals-jy/evs/security/code-scanning/1
To fix the problem, we need to ensure that the file paths constructed from jar entry names are validated to prevent directory traversal attacks. This can be achieved by verifying that the normalized full path of the output file starts with a prefix that matches the destination directory. We will use
java.nio.file.Path.normalize()andjava.nio.file.Path.startsWith()for this purpose.getMatchingJarEntriesmethod inResourceResolver.javato validate the jar entry names.Suggested fixes powered by Copilot Autofix. Review carefully before merging.
Summary by CodeRabbit