Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Java: add File.getName as a path injection sanitizer #18214

Merged
merged 2 commits into from
Dec 11, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions java/ql/lib/change-notes/2024-12-06-file-getname.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
---
category: minorAnalysis
---
* Added `java.io.File.getName()` as a path injection sanitizer.
15 changes: 15 additions & 0 deletions java/ql/lib/semmle/code/java/security/PathSanitizer.qll
Original file line number Diff line number Diff line change
Expand Up @@ -333,3 +333,18 @@ private Method getSourceMethod(Method m) {
not exists(Method src | m = src.getKotlinParameterDefaultsProxy()) and
result = m
}

/**
* A sanitizer that protects against path injection vulnerabilities
* by extracting the final component of the user provided path.
*
* TODO: convert this class to models-as-data if sanitizer support is added
*/
private class FileGetNameSanitizer extends PathInjectionSanitizer {
FileGetNameSanitizer() {
exists(MethodCall mc |
mc.getMethod().hasQualifiedName("java.io", "File", "getName") and
this.asExpr() = mc
)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -71,4 +71,19 @@ public void sendUserFileGood3(Socket sock, String user) throws Exception {
fileLine = fileReader.readLine();
}
}

public void sendUserFileGood4(Socket sock, String user) throws IOException {
BufferedReader filenameReader =
new BufferedReader(new InputStreamReader(sock.getInputStream(), "UTF-8"));
String filename = filenameReader.readLine();
File file = new File(filename);
String baseName = file.getName();
// GOOD: only use the final component of the user provided path
BufferedReader fileReader = new BufferedReader(new FileReader(baseName));
String fileLine = fileReader.readLine();
while (fileLine != null) {
sock.getOutputStream().write(fileLine.getBytes());
fileLine = fileReader.readLine();
}
}
}
Loading