Scrivio Interview library
CodingFoundations6 min read · updated 12 November 2026

Write Java code that unzips an uploaded archive into a target directory safely. What attack must you guard against?

We read the archive entry by entry with ZipInputStream, resolve each entry name against the target directory, normalise the result and refuse any path that does not start with the target, which stops Zip Slip, where a name like ../../etc/cron.d/x escapes the folder. While copying we also count the bytes we actually write and stop when the total size, the number of entries or the compression ratio passes a limit, which stops zip bombs.

Why this question is asked

Unzipping an upload looks like a five-line job, and the five-line version is how many real vulnerabilities started: files written outside the upload folder, overwritten configuration, a small upload that fills the disk. Interviewers ask this coding question because it tests whether we treat data from users as hostile, and whether we know two specific, well-documented attacks. In this answer, we will recap how a ZIP entry name becomes a path, write the naive version and see how it is attacked, fix path traversal properly, add limits against zip bombs, and look at the remaining details: directories, resources and symbolic links.

1A Quick Recap: Entry Names Are Just Strings

A ZIP archive is a list of entries, each with a name and compressed data. The name is any string the archive's creator chose, such as docs/readme.txt. Our code turns that name into a path on our disk. Nothing in the ZIP format stops a name from being ../../etc/cron.d/backdoor or an absolute path like /home/app/.ssh/authorized_keys. Equally, nothing stops a 40 KB archive from containing an entry that expands to many gigabytes, because compression of repetitive data can reach ratios above 1000 to 1.

2The Naive Version and How It Is Attacked

Here is the version many tutorials show.

Java
try (ZipInputStream zin = new ZipInputStream(upload)) {
ZipEntry e;
while ((e = zin.getNextEntry()) != null) {
Path out = target.resolve(e.getName()); // "../../etc/cron.d/x" -> outside target!
Files.createDirectories(out.getParent());
Files.copy(zin, out); // no limit on how much is written
}
}

With target = /srv/uploads/42 and an entry named ../../../etc/cron.d/x, resolve gives /srv/uploads/42/../../../etc/cron.d/x, which the file system treats as /etc/cron.d/x. If the process can write there, the attacker has just installed a scheduled job. This is the Zip Slip attack. The second problem is that Files.copy writes whatever the entry decompresses to, so a zip bomb fills the disk or takes the service down.

3Fixing Path Traversal With normalize and startsWith

The fix is to compute the final path first and check where it really lands. normalize() removes the . and .. segments, so the path we check is the path that will be written.

Java
Path root = target.toAbsolutePath().normalize(); // /srv/uploads/42
Path out = root.resolve(e.getName()).normalize(); // /etc/cron.d/x after normalising
if (!out.startsWith(root)) {
throw new IOException("Entry outside target: " + e.getName()); // rejected
}

Notice that this uses Path.startsWith, which compares whole path elements, not String.startsWith. With String.startsWith, /srv/uploads/42-evil/x would pass a check against /srv/uploads/42, because the text matches. Path.startsWith knows that 42-evil is a different directory. An absolute entry name is also caught: resolve returns the absolute path unchanged, and it does not start with root.

4The Complete Safe Extraction

Now we add the zip bomb limits. The important rule is to count bytes as we write them and not to trust the sizes declared in the archive, because the attacker writes those numbers too. We wrap the upload in a small counting stream so we also know how many compressed bytes we have consumed, which gives us the real compression ratio.

Java
public final class SafeUnzip {
static final long MAX_TOTAL = 1L << 30; // 1 GiB written in total
static final int MAX_ENTRIES = 10_000;
static final long MAX_RATIO = 100; // uncompressed / compressed
public static void unzip(InputStream upload, Path target) throws IOException {
Path root = target.toAbsolutePath().normalize();
Files.createDirectories(root);
CountingInputStream counted = new CountingInputStream(upload);
byte[] buf = new byte[64 * 1024];
long total = 0;
int entries = 0;
try (ZipInputStream zin = new ZipInputStream(counted)) {
ZipEntry e;
while ((e = zin.getNextEntry()) != null) {
if (++entries > MAX_ENTRIES) throw new IOException("Too many entries");
Path out = root.resolve(e.getName()).normalize();
if (!out.startsWith(root)) throw new IOException("Entry outside target: " + e.getName());
if (e.isDirectory()) { Files.createDirectories(out); continue; }
Files.createDirectories(out.getParent());
try (OutputStream os = Files.newOutputStream(out, StandardOpenOption.CREATE_NEW)) {
int n;
while ((n = zin.read(buf)) > 0) {
total += n;
if (total > MAX_TOTAL) throw new IOException("Archive too large when unpacked");
if (total > 1_000_000 && total > MAX_RATIO * counted.count())
throw new IOException("Suspicious compression ratio");
os.write(buf, 0, n);
}
}
}
}
}
static final class CountingInputStream extends FilterInputStream {
private long count;
CountingInputStream(InputStream in) { super(in); }
long count() { return count; }
@Override public int read() throws IOException {
int b = super.read(); if (b >= 0) count++; return b;
}
@Override public int read(byte[] b, int off, int len) throws IOException {
int n = super.read(b, off, len); if (n > 0) count += n; return n;
}
}
}
Step throughFor every entry in the archive
  1. Too many entries so far?
    Yesreject the archiveNoresolve and normalise the name
  2. Inside the target directory?
    Yescreate parents, open with CREATE_NEWNoreject: Zip Slip
  3. Is it a directory entry?
    Yescreate it and continueNocopy in 64 KB chunks
  4. Total or ratio over the limit?
    Yesreject: zip bombNowrite the chunk

4 steps in order. Play them, or step through them one at a time.

Each check has a reason. The entry limit stops archives with millions of tiny files that exhaust inodes. The total limit caps disk use regardless of what the headers claim. The ratio check, applied only after the first megabyte so small text files are not flagged, catches a bomb early, long before it reaches the total limit. CREATE_NEW refuses to overwrite a file that already exists, which also blocks an archive that contains the same name twice. If anything fails, the caller should delete the partly extracted directory.

5Directories, Resources and Symbolic Links

Directory entries end with a slash and have no data, so we create them; file entries in nested folders may arrive before, or without, their directory entry, which is why we always create the parent directories. try-with-resources closes the ZipInputStream and each output file even when a check throws.

ZipInputStream itself never creates symbolic links, but other ways of extracting can. The zip file system provider, opened with FileSystems.newFileSystem, and libraries such as Apache Commons Compress can expose Unix symlink entries. A symlink entry pointing to /etc followed by a file entry inside it is a two-step escape that the startsWith check alone does not see, so with those tools we reject symlink entries outright, and we never extract an upload into a directory that already contains links.

6Follow-up questions

Is checking for .. in the name enough?

No. Names can be absolute, use different separators, or contain encoded forms that a simple text check misses. Resolving, normalising and comparing the final Path is reliable because it checks the outcome, not the spelling.

Why not use ZipFile and trust getSize()?

ZipFile reads the central directory and gives sizes up front, which is useful for a quick early rejection. But those sizes come from the archive, which the attacker controls, so we must still count real bytes while copying.

Should extraction happen inside the web request?

For small, trusted-size uploads it can. For anything large or untrusted, it is better done in a separate worker with its own disk quota, memory limit and timeout, so even a bypassed check cannot take down the service that handles requests.

7Conclusion

In this answer, we saw that ZIP entry names are attacker-controlled strings, so the naive resolve and copy allows Zip Slip and zip bombs. We fixed traversal by resolving, normalising and checking the result with Path.startsWith, and stopped bombs by counting the bytes we actually write against limits on total size, number of entries and compression ratio. We also created parent directories, used try-with-resources and CREATE_NEW, and rejected symlink entries when using tools that can create them.

What to say in the interviewAbout 80 seconds aloud

Open with

I would read the upload with ZipInputStream and loop over getNextEntry. The attack to guard against is Zip Slip: the entry name is just a string from the attacker, so a name like ../../etc/cron.d/x, or an absolute path, resolves outside my target directory and overwrites something important.

Then, if they want more

So for each entry I take the target as an absolute, normalised path, resolve the entry name against it, normalise again, and reject the archive if the result does not startsWith the target, using Path.startsWith, which compares path elements, not String.startsWith, which can be fooled by a sibling folder with a longer name.

The second attack is a zip bomb, a small archive that expands to gigabytes. I never trust the sizes in the headers; I copy in 64 KB chunks and count real bytes, with limits on total uncompressed size, number of entries, and the ratio of written bytes to compressed bytes consumed.

Directory entries get created, files get their parent directories created first and are opened with CREATE_NEW so nothing is overwritten, and everything is inside try-with-resources. If I used the zip file system or a library that understands symlinks, I would reject symlink entries.

For large untrusted uploads I would also run extraction in a separate worker with its own disk quota.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Write Java code that unzips an uploaded archive into a target directory safely. What...": https://scrivio-interview-library.netlify.app/java/io-and-nio/0444f3104d/