Expanding archive files is security-sensitive. For example, expanding archive files has led in the past to the following vulnerabilities:

Applications that expand archive files (zip, tar, jar, war, 7z, ...) should verify the path where the archive's files are expanded and not trust blindly the content of the archive. Archive's files should not be expanded outside of the root directory where the archive is supposed to be expanded. Also, applications should control the size of the expanded data to not be a victim of Zip Bomb attack. Failure to do so could allow an attacker to use a specially crafted archive that holds directory traversal paths (e.g. ../../attacker.sh) or the attacker could overload the file system, processors or memory of the operating system where the archive is expanded making the target OS completely unusable.

This rule raises an issue when code handle archives. The goal is to guide security code reviews.

Ask Yourself Whether

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

String canonicalDirPath = outputDir.getCanonicalPath();
String canonicalDestPath = targetFile.getCanonicalPath();

if (!canonicalDestPath.startsWith(canonicalDirPath + File.separator)) { // Sanitizer
  throw new ArchiverException("Entry is trying to leave the target dir: " + zipEntry.getName());
}

Sensitive Code Example

java.util.zip.ZipFile zipFile = new ZipFile(zipFileName);

Enumeration<? extends ZipEntry> entries = zipFile.entries();
while (entries.hasMoreElements()) {
  ZipEntry e = entries.nextElement(); // Sensitive
  File f = new File(outputDir, e.getName());
  InputStream input = zipFile.getInputStream(e);
  extractFile(new ZipInputStream(input), outputDir, e.getName());
}

Exceptions

This rule doesn't raise an issue when a ZipEntry or a ArchiveEntry:

See