001package org.hl7.fhir.utilities;
002
003import java.io.File;
004import java.io.IOException;
005import java.io.InputStream;
006import java.nio.file.Files;
007import java.nio.file.Path;
008import java.nio.file.StandardCopyOption;
009import java.util.zip.ZipEntry;
010import java.util.zip.ZipInputStream;
011
012public class CompressionUtilities {
013  public static void unzip(InputStream zip, String target) throws IOException {
014    unzip(zip, Path.of(target));
015  }
016
017  public static void unzip(InputStream zip, Path target) throws IOException {
018    try (ZipInputStream zis = new ZipInputStream(zip)) {
019      ZipEntry zipEntry = zis.getNextEntry();
020      while (zipEntry != null) {
021        boolean isDirectory = false;
022
023        String n = makeOSSafe(zipEntry.getName());
024
025        if (n.endsWith(File.separator)) {
026          isDirectory = true;
027        }
028        Path newPath = zipSlipProtect(n, target);
029        if (isDirectory) {
030          Files.createDirectories(newPath);
031        } else {
032          if (newPath.getParent() != null) {
033            if (Files.notExists(newPath.getParent())) {
034              Files.createDirectories(newPath.getParent());
035            }
036          }
037          Files.copy(zis, newPath, StandardCopyOption.REPLACE_EXISTING);
038        }
039        zipEntry = zis.getNextEntry();
040      }
041      zis.closeEntry();
042    }
043  }
044
045  public static Path zipSlipProtect(String zipName, Path targetDir)
046      throws IOException {
047
048    // test zip slip vulnerability
049    // Path targetDirResolved = targetDir.resolve("../../" + zipEntry.getName());
050
051    Path targetDirResolved = targetDir.resolve(zipName);
052
053    // make sure normalized file still has targetDir as its prefix
054    // else throws exception
055    Path normalizePath = targetDirResolved.normalize();
056    if (!normalizePath.startsWith(targetDir)) {
057      throw new IOException("Bad zip entry: " + zipName);
058    }
059
060    return normalizePath;
061  }
062
063  public static String makeOSSafe(String name) {
064    return name.replace("\\", File.separator).replace("/", File.separator);
065  }
066}