Skip to content

Commit

Permalink
Merge pull request #18214 from jcogs33/jcogs33/java/file-getname-path…
Browse files Browse the repository at this point in the history
…-sanitizer

Java: add File.getName as a path injection sanitizer
  • Loading branch information
jcogs33 authored Dec 11, 2024
2 parents 066cfa3 + 214da9e commit 538dee8
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 0 deletions.
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 @@ -337,3 +337,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();
}
}
}

0 comments on commit 538dee8

Please sign in to comment.