Video in progress
To read an archive, which do you pick, `ZipFile` or `ZipInputStream`, and what do you watch out for when extracting a user-uploaded zip?
ZipFile reads a file on disk through the central directory at its end, so you go straight to the entry you need. ZipInputStream reads the stream sequentially from the start, so you can work without saving the file. For an uploaded archive, you limit names, size and the number of entries against zip slip and zip bombs.
📖 Answer
ZipFile needs a file, but it is faster and more reliable: it gets the list of entries from the directory and can open any entry. To get one file you don't have to read the whole archive. ZipInputStream is handy for a stream coming from the network, but it only moves forward.
There are two dangers when extracting an uploaded archive. The first is an entry name like ../../etc/cron.d/job (zip slip). The second is a 40 KB archive that expands to terabytes (a zip bomb).
Path base = targetDir.toAbsolutePath().normalize();
long total = 0;
int count = 0;
try (var zin = new ZipInputStream(Files.newInputStream(upload))) {
ZipEntry e;
while ((e = zin.getNextEntry()) != null) {
if (++count > MAX_ENTRIES) throw new IOException("yozuv juda ko'p");
Path out = base.resolve(e.getName()).normalize();
if (!out.startsWith(base)) throw new IOException("ruxsatsiz yo'l: " + e.getName());
if (e.isDirectory()) { Files.createDirectories(out); continue; }
Files.createDirectories(out.getParent());
try (OutputStream os = Files.newOutputStream(out, StandardOpenOption.CREATE_NEW)) {
byte[] buf = new byte[8192];
int n;
while ((n = zin.read(buf)) > 0) {
total += n;
if (total > MAX_TOTAL) throw new IOException("arxiv juda katta");
os.write(buf, 0, n);
}
}
}
}
Note that we count the size from the bytes actually read, not from e.getSize(). getSize() can be -1, and it is in the hands of whoever created the archive.
Another way to read inside an archive is FileSystems.newFileSystem(zipPath) (Java 13+): you walk the zip with ordinary Paths. But the security checks are your job there too.
Sign up to mark studied questions and save your progress.