Skip to content

Commit

Permalink
Java: add File.getName as a path injection sanitizer
Browse files Browse the repository at this point in the history
  • Loading branch information
Jami Cogswell authored and Jami Cogswell committed Dec 4, 2024
1 parent ccfb32e commit 1e0ef81
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
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.getQualifier()
)
}
}
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 1e0ef81

Please sign in to comment.