Information Security 16 min read

Understanding Compression Bombs and How to Prevent Them in Java

This article explains what a compression bomb is, outlines its potential harms such as resource exhaustion and system crashes, describes detection methods, and provides detailed Java code examples for preventing compression bomb attacks by limiting unzip size, using safe libraries, and applying security policies.

Rare Earth Juejin Tech Community
Rare Earth Juejin Tech Community
Rare Earth Juejin Tech Community
Understanding Compression Bombs and How to Prevent Them in Java

A compression bomb (also called a zip bomb) is a tiny archive that expands to gigabytes or even terabytes when decompressed, potentially exhausting CPU, memory, and disk resources and causing system crashes.

The main dangers include resource exhaustion, disk space depletion, system crashes, denial‑of‑service attacks, and possible data loss.

Detection methods include using security/antivirus software, imposing file‑size limits, and filtering unknown file types before extraction.

In Java, prevention can be achieved by limiting the unzip algorithm, setting resource limits, using trusted libraries, validating file types, performing asynchronous extraction, and enforcing strict security policies.

Below is a flow diagram of the unzip‑size‑checking logic:

graph TD
    A(开始) --> B[创建 ZipFile 对象]
    B --> C[打开要解压缩的 ZIP 文件]
    C --> D[初始化 zipFileSize 变量为 0]
    D --> E{是否有更多的条目}
    E -- 是 --> F[获取 ZIP 文件的下一个条目]
    F --> G[获取当前条目的未压缩大小]
    G --> H[将解压大小累加到 zipFileSize 变量]
    H --> I{zipFileSize 是否超过指定的大小}
    I -- 是 --> J[调用 deleteDir 方法删除已解压的文件夹]
    J --> K[抛出 IllegalArgumentException 异常]
    K --> L(结束)
    I -- 否 --> M[保存解压文件] --> E
    E -- 否 --> L

The implementation class FileBombUtil provides a static unzip method that iterates over each ZipEntry , accumulates the uncompressed size, and aborts with an exception if the total exceeds a configurable limit. It also includes a helper deleteDir method for recursive directory removal.

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

/**
 * File bomb utility class
 */
public class FileBombUtil {
    public static final Long FILE_LIMIT_SIZE = 1024 * 1024 * 1L; // 1 MB limit
    public static final String FILE_LIMIT_SIZE_MSG = "The file size exceeds the limit";

    /**
     * Unzip with size limitation
     */
    public static void unzip(File file, File outputfolder, Long size) throws Exception {
        ZipFile zipFile = new ZipFile(file);
        FileOutputStream fos = null;
        try {
            Enumeration
zipEntries = zipFile.entries();
            long zipFileSize = 0L;
            while (zipEntries.hasMoreElements()) {
                ZipEntry entry = zipEntries.nextElement();
                zipFileSize += entry.getSize();
                if (zipFileSize > size) {
                    deleteDir(outputfolder);
                    throw new IllegalArgumentException(FILE_LIMIT_SIZE_MSG);
                }
                File unzipped = new File(outputfolder, entry.getName());
                if (entry.isDirectory() && !unzipped.exists()) {
                    unzipped.mkdirs();
                    continue;
                } else if (!unzipped.getParentFile().exists()) {
                    unzipped.getParentFile().mkdirs();
                }
                fos = new FileOutputStream(unzipped);
                InputStream in = zipFile.getInputStream(entry);
                byte[] buffer = new byte[4096];
                int count;
                while ((count = in.read(buffer, 0, buffer.length)) != -1) {
                    fos.write(buffer, 0, count);
                }
            }
        } finally {
            if (fos != null) fos.close();
            zipFile.close();
        }
    }

    private static boolean deleteDir(File dir) {
        if (dir.isDirectory()) {
            for (String child : dir.list()) {
                if (!deleteDir(new File(dir, child))) return false;
            }
        }
        return dir.delete();
    }
}

A simple test class demonstrates usage and handles the IllegalArgumentException when the size limit is exceeded.

import java.io.File;

public class Test {
    public static void main(String[] args) {
        File bomb = new File("D:\temp\3\zbsm.zip");
        File tempFile = new File("D:\temp\3\4");
        try {
            FileBombUtil.unzip(bomb, tempFile, FileBombUtil.FILE_LIMIT_SIZE * 60);
        } catch (IllegalArgumentException e) {
            if (FileBombUtil.FILE_LIMIT_SIZE_MSG.equalsIgnoreCase(e.getMessage())) {
                FileBombUtil.deleteDir(tempFile);
                System.out.println("Original file too large");
            } else {
                System.out.println("Invalid zip format");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

In summary, compression bombs are malicious files that can exhaust system resources; developers should detect them early, enforce size limits, use safe extraction libraries, and apply strict security policies to mitigate the risk.

Relevant Chinese laws such as the Criminal Law, Cybersecurity Law, and the Regulations on the Security Protection of Computer Information Systems explicitly prohibit the creation, distribution, and use of malicious programs like compression bombs.
Javaresource exhaustionsecurityzipcompression bomb
Rare Earth Juejin Tech Community
Written by

Rare Earth Juejin Tech Community

Juejin, a tech community that helps developers grow.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.