53 lines
1.2 KiB
Plaintext
Raw Normal View History

=== How to fix it in Java SE
:canonicalization_function: java.io.File.getCanonicalPath
include::../../common/fix/code-rationale.adoc[]
[cols="a"]
|===
h| Non-compliant code example
|
[source,java]
----
@RestController
public class ApiController
{
static private String targetDirectory = "/path/to/target/directory/";
@GetMapping(value = "/endpoint")
public void endpoint(@RequestParam("filename") filename) throws IOException {
File file = new File(targetDirectory + filename);
file.delete(); // Noncompliant
}
}
----
h| Compliant solution
|
[source,java]
----
@RestController
public class ApiController
{
static private String targetDirectory = "/path/to/target/directory/";
@GetMapping(value = "/endpoint")
public void endpoint(@RequestParam("filename") filename) throws IOException {
File file = new File(targetDirectory + filename);
String canonicalDestinationPath = file.getCanonicalPath();
if (!canonicalDestinationPath.startsWith(targetDirectory)) {
throw new IOException("Entry is outside of the target directory");
}
file.delete();
}
}
----
|===
=== How does this work?
include::../../common/fix/how-does-this-work.adoc[]