Skip to content

Commit 947b094

Browse files
author
Max Schaefer
committed
Add additional example.
1 parent 009d580 commit 947b094

File tree

3 files changed

+31
-0
lines changed

3 files changed

+31
-0
lines changed

java/ql/src/Security/CWE/CWE-022/TaintedPath.qhelp

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,11 @@ not contain ".." and starts with the public folder.</p>
4646

4747
<sample src="TaintedPathGood.java" />
4848

49+
<p>Alternatively, if we only want to allow simple filenames without a path component, we can remove all path
50+
separators ("/" or "\") and all ".." sequences from the input before using it to construct a file path.</p>
51+
52+
<sample src="TaintedPathGood2.java" />
53+
4954
</example>
5055
<references>
5156

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
public void sendUserFileGood(Socket sock, String user) {
2+
BufferedReader filenameReader = new BufferedReader(
3+
new InputStreamReader(sock.getInputStream(), "UTF-8"));
4+
String filename = filenameReader.readLine();
5+
// GOOD: remove all ".." sequences and path separators from the filename
6+
filename = filename.replaceAll("\\.\\.|[/\\\\]", "");
7+
BufferedReader fileReader = new BufferedReader(new FileReader(filename));
8+
String fileLine = fileReader.readLine();
9+
while(fileLine != null) {
10+
sock.getOutputStream().write(fileLine.getBytes());
11+
fileLine = fileReader.readLine();
12+
}
13+
}

java/ql/test/query-tests/security/CWE-022/semmle/tests/TaintedPath.java

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,4 +32,17 @@ public void sendUserFileGood(Socket sock, String user) throws IOException {
3232
}
3333
}
3434
}
35+
36+
public void sendUserFileGood2(Socket sock, String user) throws IOException {
37+
BufferedReader filenameReader = new BufferedReader(new InputStreamReader(sock.getInputStream(), "UTF-8"));
38+
String filename = filenameReader.readLine();
39+
// GOOD: remove all ".." sequences and path separators from the filename
40+
filename = filename.replaceAll("\\.\\.|[/\\\\]", "");
41+
BufferedReader fileReader = new BufferedReader(new FileReader(filename));
42+
String fileLine = fileReader.readLine();
43+
while(fileLine != null) {
44+
sock.getOutputStream().write(fileLine.getBytes());
45+
fileLine = fileReader.readLine();
46+
}
47+
}
3548
}

0 commit comments

Comments
 (0)