|
| 1 | +// Copyright (c) Microsoft Corporation. |
| 2 | +// Licensed under the MIT License. |
| 3 | + |
| 4 | +package com.microsoft.hydralab.common.util; |
| 5 | + |
| 6 | +import java.io.ByteArrayOutputStream; |
| 7 | +import java.io.File; |
| 8 | +import java.io.FileInputStream; |
| 9 | +import java.io.FileOutputStream; |
| 10 | +import java.util.zip.ZipEntry; |
| 11 | +import java.util.zip.ZipInputStream; |
| 12 | + |
| 13 | +public class ZipBombChecker { |
| 14 | + private static final long MAX_UNCOMPRESSED_SIZE = 1024 * 1024 * 1024; // 1024 MB |
| 15 | + private static final int MAX_ENTRIES = 10000; |
| 16 | + private static final int MAX_NESTING_DEPTH = 5; |
| 17 | + |
| 18 | + public static boolean isZipBomb(File file) { |
| 19 | + return isZipBomb(file, 0); |
| 20 | + } |
| 21 | + |
| 22 | + private static boolean isZipBomb(File file, int depth) { |
| 23 | + if (depth > MAX_NESTING_DEPTH) { |
| 24 | + return true; |
| 25 | + } |
| 26 | + |
| 27 | + long totalUncompressedSize = 0; |
| 28 | + int entryCount = 0; |
| 29 | + |
| 30 | + try (ZipInputStream zis = new ZipInputStream(new FileInputStream(file))) { |
| 31 | + ZipEntry entry; |
| 32 | + byte[] buffer = new byte[8192]; |
| 33 | + |
| 34 | + while ((entry = zis.getNextEntry()) != null) { |
| 35 | + entryCount++; |
| 36 | + if (entryCount > MAX_ENTRIES) { |
| 37 | + return true; |
| 38 | + } |
| 39 | + |
| 40 | + if (!entry.isDirectory()) { |
| 41 | + ByteArrayOutputStream baos = new ByteArrayOutputStream(); |
| 42 | + int read; |
| 43 | + while ((read = zis.read(buffer)) != -1) { |
| 44 | + baos.write(buffer, 0, read); |
| 45 | + totalUncompressedSize += read; |
| 46 | + if (totalUncompressedSize > MAX_UNCOMPRESSED_SIZE) { |
| 47 | + return true; |
| 48 | + } |
| 49 | + } |
| 50 | + // check if the entry is a nested zip file |
| 51 | + if (entry.getName().toLowerCase().endsWith(".zip")) { |
| 52 | + byte[] nestedZipBytes = baos.toByteArray(); |
| 53 | + File tempZip = File.createTempFile("nested", ".zip"); |
| 54 | + try (FileOutputStream fos = new FileOutputStream(tempZip)) { |
| 55 | + fos.write(nestedZipBytes); |
| 56 | + } |
| 57 | + boolean nestedBomb = isZipBomb(tempZip, depth + 1); |
| 58 | + tempZip.delete(); |
| 59 | + if (nestedBomb) { |
| 60 | + return true; |
| 61 | + } |
| 62 | + } |
| 63 | + } |
| 64 | + zis.closeEntry(); |
| 65 | + } |
| 66 | + } catch (Exception e) { |
| 67 | + return true; // If there's an error reading the zip, treat it as a potential zip bomb |
| 68 | + } |
| 69 | + return false; |
| 70 | + } |
| 71 | +} |
0 commit comments