== Why is this an issue?

include::../description.adoc[]

=== Noncompliant code example

[source,java]
----
Enumeration<? extends ZipEntry> entries = zipFile.entries();
while (entries.hasMoreElements()) {
  ZipEntry entry = entries.nextElement();
  File extractedFile = new File(toDir, entry.getName()); 

  FileOutputStream fos = new FileOutputStream(extractedFile); // Noncompliant; entry.getName() that was used to created "extractedFile" may be tainted with "../../../../../../../../tmp/evil.sh"
  InputStream input = zipFile.getInputStream(entry);
  IOUtils.copy(input, fos);
}
----

=== Compliant solution

[source,java]
----
Enumeration<? extends ZipEntry> entries = zipFile.entries();
while (entries.hasMoreElements()) {
  ZipEntry zipEntry = entries.nextElement();
  String fileName = zipEntry.getName();
  File extractedFile = new File(toDir, fileName);

  String canonicalDirPath = toDir.getCanonicalPath();
  String canonicalDestPath = extractedFile.getCanonicalPath();

  sanitizeAgainstZipFlipVulnerability(fileName, canonicalDestPath, canonicalDirPath); // Compliant

  FileOutputStream fos = new FileOutputStream(extractedFile);
  InputStream input = zipFile.getInputStream(entry);
  IOUtils.copy(input, fos);
}

public static void sanitizeAgainstZipFlipVulnerability(String fileName, String canonicalDestPath, String canonicalDirPath) throws ArchiverException {
    if (fileName.indexOf("..") != -1 && !canonicalDestPath.startsWith(canonicalDirPath + File.separator)) { // Sanitizer
      throw new ArchiverException("The file " + fileName + " is trying to leave the target output directory.");
    }
  }
----

== Resources

* OWASP - https://owasp.org/Top10/A01_2021-Broken_Access_Control/[Top 10 2021 Category A1 - Broken Access Control]
* OWASP - https://owasp.org/Top10/A03_2021-Injection/[Top 10 2021 Category A3 - Injection]
* OWASP - https://owasp.org/www-project-top-ten/2017/A1_2017-Injection[Top 10 2017 Category A1 - Injection]
* OWASP - https://owasp.org/www-project-top-ten/2017/A5_2017-Broken_Access_Control[Top 10 2017 Category A5 - Broken Access Control]
* CWE - https://cwe.mitre.org/data/definitions/20[CWE-20 - Improper Input Validation]
* CWE - https://cwe.mitre.org/data/definitions/22[CWE-22 - Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')]
* https://wiki.sei.cmu.edu/confluence/display/java/IDS04-J.+Safely+extract+files+from+ZipInputStream[CERT, IDS04-J.] - Safely extract files from ZipInputStream
* Snyk Research Team: https://snyk.io/research/zip-slip-vulnerability[Zip Slip Vulnerability]
* https://nvd.nist.gov/vuln/detail/CVE-2016-0709
* https://nvd.nist.gov/vuln/detail/CVE-2017-5946

ifdef::env-github,rspecator-view[]

'''
== Implementation Specification
(visible only on this page)

include::../message.adoc[]

'''
== Comments And Links
(visible only on this page)

include::../comments-and-links.adoc[]

endif::env-github,rspecator-view[]
