Safe Zip Extraction With A Path Guard

Extract uploaded archives safely: resolve every entry against the target directory, normalize it, and reject any path that escapes the folder.

JavaSecurity Boundaries

Code

snippet
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

public class SafeZipExtractor {

    public static void main(String[] args) throws IOException {
        // 构造一个带恶意路径的压缩包:第一个 entry 试图跳出目标目录
        Path archive = Files.createTempFile("upload-", ".zip");
        try (ZipOutputStream out = new ZipOutputStream(Files.newOutputStream(archive))) {
            out.putNextEntry(new ZipEntry("../../evil.txt"));
            out.write("pwn".getBytes(StandardCharsets.UTF_8));
            out.closeEntry();
            out.putNextEntry(new ZipEntry("docs/readme.txt"));
            out.write("safe".getBytes(StandardCharsets.UTF_8));
            out.closeEntry();
        }

        Path target = Files.createTempDirectory("extract-");
        // safe extraction: reject entries that escape the target directory
        try (InputStream in = Files.newInputStream(archive);
             ZipInputStream zip = new ZipInputStream(in, StandardCharsets.UTF_8)) {
            for (ZipEntry entry; (entry = zip.getNextEntry()) != null; ) {
                // Zip Slip guard: resolve + normalize 后必须仍在 target 内
                Path resolved = target.resolve(entry.getName()).normalize();
                if (!resolved.startsWith(target)) {
                    System.out.println("blocked: " + entry.getName());
                } else if (entry.isDirectory()) {
                    Files.createDirectories(resolved);
                } else {
                    Files.createDirectories(resolved.getParent());
                    Files.copy(zip, resolved);
                    System.out.println("extracted: " + resolved.getFileName());
                }
            }
        }
    }
}

How the snippet works

The code’s whole job belongs to the class SafeZipExtractor.

A single loop drives the file — for (ZipEntry entry; (entry = zip.getNextEntry()) != null; ). Resources are declared in a try-with-resources header, so they close on every exit path without a finally block.

Watch out for

  • Zero-fetch snippet: every identifier resolves inside the language distribution.

Applying it

Output lines are prefixed (blocked:, extracted:), making each step’s effect easy to spot.

Statements that matter

Path resolved = target.resolve(entry.getName()).normalize();
Path archive = Files.createTempFile("upload-", ".zip");
Path target = Files.createTempDirectory("extract-");

Interactive Tools for This Topic

FAQ

What does Safe Zip Extraction With A Path Guard print when run?
No setup needed: run the file and look for labeled lines like `blocked:`, `extracted:` in the output.