Archive extraction path traversal (Zip Slip)

Archive extraction path traversal (Zip Slip)

Description

Before creating a file from a ZIP entry, restrict the write to the extraction directory. Absolute paths, parent components, or symbolic links can otherwise redirect it.

Potential impact

Overwriting a file the service account can modify may change settings or interrupt service. If a more privileged process later reads or runs that file, the effects may include disclosure or privilege escalation.

Remediation

  • Start with a new private directory under a trusted parent. Allow only the expected file structure and avoid restoring archive links.
  • Reject absolute paths and parent traversal. Check base.resolve(entryName).normalize() with Path.startsWith(base). If subdirectories are needed, open each parent relative to a trusted directory without following links before creating children.
  • Extract with minimal privileges. Create files with CREATE_NEW and NOFOLLOW_LINKS.

Examples

Before

java
import java.io.*;
import java.util.zip.*;
public class UnsafeUnzipper {
    public void extract(InputStream zipStream, File destDir) throws IOException {
        ZipInputStream zis = new ZipInputStream(zipStream);
        ZipEntry entry;
        while ((entry = zis.getNextEntry()) != null) {
            // Combine the raw entry name with the destination.
            File outFile = new File(destDir, entry.getName());
            if (entry.isDirectory()) {
                outFile.mkdirs();
                continue;
            }
            outFile.getParentFile().mkdirs();
            try (OutputStream os = new FileOutputStream(outFile)) {
                byte[] buf = new byte[8192];
                int len;
                while ((len = zis.read(buf)) != -1) {
                    os.write(buf, 0, len);
                }
            }
        }
    }
}

After

This example requires Java 11 or later and a destDir that other users cannot change. Limit actual expanded bytes and entry count separately.

java
import java.io.*;
import java.nio.channels.*;
import java.nio.file.*;
import java.util.*;
import java.util.zip.*;
public class SafeUnzipper {
    public void extract(InputStream zipStream, File destDir) throws IOException {
        // Create a private directory for this extraction under application control.
        Path serviceRoot = destDir.toPath().toRealPath();
        Path base = Files.createTempDirectory(serviceRoot, "extract-")
                .toRealPath();
        try (ZipInputStream zis = new ZipInputStream(zipStream)) {
            ZipEntry entry;
            byte[] buf = new byte[8192];
            while ((entry = zis.getNextEntry()) != null) {
                String name = entry.getName();
                Path entryPath = Path.of(name);
                // Accept only plain filenames, without parent directories that could be links.
                if (entry.isDirectory() || name.isBlank() || entryPath.isAbsolute()
                        || name.indexOf('/') >= 0 || name.indexOf('\\') >= 0
                        || name.equals(".") || name.equals("..")) {
                    throw new IOException("Invalid zip entry name: " + name);
                }

                Path target = base.resolve(entryPath).normalize();
                if (!target.startsWith(base) || !target.getParent().equals(base)) {
                    throw new IOException("Zip Slip detected: " + name);
                }

                Set<OpenOption> options = Set.of(
                        StandardOpenOption.CREATE_NEW,
                        StandardOpenOption.WRITE,
                        LinkOption.NOFOLLOW_LINKS);
                try (SeekableByteChannel channel = Files.newByteChannel(target, options);
                     OutputStream os = Channels.newOutputStream(channel)) {
                    int len;
                    while ((len = zis.read(buf)) != -1) {
                        os.write(buf, 0, len);
                    }
                }
            }
        }
    }
}

Each entry must be a single-component filename. The code creates each file directly in a new directory. CREATE_NEW rejects a duplicate name.

References