2022-07-26 15:09:13 +02:00
|
|
|
=== How to fix it in Java SE
|
|
|
|
|
2022-07-27 14:34:13 +02:00
|
|
|
:canonicalization_function: java.io.File.getCanonicalPath
|
|
|
|
include::../../common/fix/code-rationale.adoc[]
|
2022-07-26 15:09:13 +02:00
|
|
|
|
|
|
|
[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?
|
|
|
|
|
2022-07-27 14:34:13 +02:00
|
|
|
include::../../common/fix/how-does-this-work.adoc[]
|