Skip to content

Commit aaeef85

Browse files
authored
Improve path traversal example with stronger sanitization (#63)
1 parent f07d776 commit aaeef85

File tree

1 file changed

+11
-7
lines changed

1 file changed

+11
-7
lines changed

src/java/detectors/path_traversal/PathTraversal.java

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -13,19 +13,23 @@ public class PathTraversal {
1313

1414
// {fact rule=path-traversal@v1.0 defects=1}
1515
public void createFileNoncompliant(HttpServletRequest request, HttpServletResponse response) {
16-
String basePath = "/var/example/base/";
17-
String relativePath = request.getParameter("relativePath");
18-
// Noncompliant: user-supplied relative path is not sanitized and could contain malicious special characters.
19-
File fileTarget = new File(basePath + relativePath);
16+
String basePath = "/var/data/images/";
17+
String desiredCategory = request.getParameter("category");
18+
// Noncompliant: user-supplied relative path is not sanitized and could contain malicious characters.
19+
File fileTarget = new File(basePath + desiredCategory);
2020
}
2121
// {/fact}
2222

2323
// {fact rule=path-traversal@v1.0 defects=0}
2424
public void createFileCompliant(HttpServletRequest request) {
25-
String basePath = "/var/example/base/";
25+
String basePath = "/var/data/images/";
26+
String desiredCategory = request.getParameter("category");
2627
// Compliant: user-supplied relative path is sanitized before use.
27-
String relativePath = request.getParameter("relativePath").replaceAll("..", "");
28-
File fileTarget = new File(basePath + relativePath);
28+
if (desiredCategory.matches("[a-z]+")) {
29+
File fileTarget = new File(basePath + desiredCategory);
30+
} else {
31+
throw new IllegalArgumentException("Invalid category name");
32+
}
2933
}
3034
// {/fact}
3135
}

0 commit comments

Comments
 (0)