Creating file paths from untrusted input might give a malicious actor access to sensitive files by manipulating the file name to access an arbitrary file on disk.
1public void createFileNoncompliant(HttpServletRequest request, HttpServletResponse response) {
2 String basePath = "/var/data/images/";
3 String desiredCategory = request.getParameter("category");
4 // Noncompliant: user-supplied relative path is not sanitized and could contain malicious characters.
5 File fileTarget = new File(basePath + desiredCategory);
6}
1public void createFileCompliant(HttpServletRequest request) {
2 String basePath = "/var/data/images/";
3 String desiredCategory = request.getParameter("category");
4 // Compliant: user-supplied relative path is sanitized before use.
5 if (desiredCategory.matches("[a-z]+")) {
6 File fileTarget = new File(basePath + desiredCategory);
7 } else {
8 throw new IllegalArgumentException("Invalid category name");
9 }
10}