Ad Code

How to Zip and Unzip Folder or Directory in Android Studio | How to solve Zip Path Traversal, your app contains an unsafe unzipping pattern that may lead to a path traversal vulnerability

 Hello developers, if you want to implement Zip or Unzip Folder/Directory into your Android Studio Project then you are in the right place. In this Article we will provide you the proper code for safely implement Zip and Unzip program into your project. And if you are facing "Your app contains an unsafe unzipping pattern that may lead to a path traversal vulnerability" error in your play console release overview then you can also solve this error by implementing the given code into your project. This error is showing because your app contains unsafe unzipping patterns, which may potentially lead to a Zip Path Traversal attack. So, we have solved this problem and given below.

 


How to Zip and Unzip Folder or Directory in Android Studio

Add this zipMaker class into your project. This 'ZipMaker.java' file contains Zip and Unzip Folder or Directory both function.

ZipMaker.java
package com.study.m.html.utils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

public class ZipMaker {

    public static boolean zipFileAtPath(String sourcePath, String toLocation) {
        final int BUFFER = 2048;

        File sourceFile = new File(sourcePath);
        try {
            BufferedInputStream origin = null;
            FileOutputStream dest = new FileOutputStream(toLocation);
            ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(
                    dest));
            if (sourceFile.isDirectory()) {
                zipSubFolder(out, sourceFile, sourceFile.getParent().length());
            } else {
                byte data[] = new byte[BUFFER];
                FileInputStream fi = new FileInputStream(sourcePath);
                origin = new BufferedInputStream(fi, BUFFER);
                ZipEntry entry = new ZipEntry(getLastPathComponent(sourcePath));
                entry.setTime(sourceFile.lastModified()); // to keep modification time after unzipping
                out.putNextEntry(entry);
                int count;
                while ((count = origin.read(data, 0, BUFFER)) != -1) {
                    out.write(data, 0, count);
                }
            }
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    private static void zipSubFolder(ZipOutputStream out, File folder, int basePathLength) throws IOException {

        final int BUFFER = 2048;

        File[] fileList = folder.listFiles();
        BufferedInputStream origin = null;
        for (File file : fileList) {
            if (file.isDirectory()) {
                zipSubFolder(out, file, basePathLength);
            } else {
                byte data[] = new byte[BUFFER];
                String unmodifiedFilePath = file.getPath();
                String relativePath = unmodifiedFilePath
                        .substring(basePathLength);
                FileInputStream fi = new FileInputStream(unmodifiedFilePath);
                origin = new BufferedInputStream(fi, BUFFER);
                ZipEntry entry = new ZipEntry(relativePath);
                entry.setTime(file.lastModified()); // this will keep modification time after unzipping
                out.putNextEntry(entry);
                int count;
                while ((count = origin.read(data, 0, BUFFER)) != -1) {
                    out.write(data, 0, count);
                }
                origin.close();
            }
        }
    }

    public static String getLastPathComponent(String filePath) {
        String[] segments = filePath.split("/");
        if (segments.length == 0) {
            return "";
        }

        return segments[segments.length - 1];
    }

    public static void unzipFiles(File zipFile, File targetDirectory) throws IOException {
        ZipInputStream zis = new ZipInputStream(
                new BufferedInputStream(new FileInputStream(zipFile)));
        try {
            ZipEntry ze;
            int count;
            byte[] buffer = new byte[1024];
            while ((ze = zis.getNextEntry()) != null) {
                File file = new File(targetDirectory, ze.getName());

                try {
                    ensureZipPathSafety(file, targetDirectory.getPath());
                } catch (Exception e) {
                    throw new SecurityException(e);
                }

                File dir = ze.isDirectory() ? file : file.getParentFile();

                if (!dir.isDirectory() && !dir.mkdirs())

                    throw new FileNotFoundException("Failed to ensure directory: " + dir.getAbsolutePath());

                if (ze.isDirectory())
                    continue;
                FileOutputStream fout = new FileOutputStream(file);
                try {
                    while ((count = zis.read(buffer)) != -1)
                        fout.write(buffer, 0, count);
                } finally {
                    fout.close();
                }
            }
        } finally {
            zis.close();
        }
    }

    // You need to ensure zip path safety according to Google Play Policy
    private static void ensureZipPathSafety(final File outputFile, final String destDirectory) throws Exception {
        String destDirCanonicalPath = (new File(destDirectory)).getCanonicalPath();
        String outputFileCanonicalPath = outputFile.getCanonicalPath();
        if (!outputFileCanonicalPath.startsWith(destDirCanonicalPath)) {
            throw new SecurityException(String.format("Found Zip Path Traversal Vulnerability with %s", outputFileCanonicalPath));
        }
    }



}

Integration

Here is the uses of 'ZipMaker.java' which helps you to integrate thease function into your project.

Zip folder/Directory

Zip Folder
 String sourcePath = "paste source path"; // paste the directory path which you want to make zip
        File destDirectory = new File("paste dest directory path"); // paste the directory path where you want to create the zip file
        if(!destDirectory.exists()) {
            destDirectory.mkdirs();
        }
        File destFile = new File(destDirectory.getPath(), ("filename" + ".zip")); 
        
        zipFileAtPath(sourcePath, destFile.getPath());

Unzip folder/Directory

Unzip file
 File zipSourceFile = new File("paste your zip file location");
        File unzipDirectory = new File("paste the directory path where you want to unzip file");
        if(!unzipDirectory.exists()) {
            unzipDirectory.mkdirs();
        }
        try {
            unzipFiles(zipSourceFile, unzipDirectory);
        } catch (IOException e) {
            Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
        }

How to solve Zip Path Traversal, your app contains an unsafe unzipping pattern that may lead to a path traversal vulnerability

This error shows mainly in the Unzip function. So replace your previous zip and unzip program with the ZipMaker.class and it will solve your problem. We have provided the upper code after successfully tasting.

What is a Zip File?

Zip files are compressed files that contain one or more files or folders. They are commonly used to bundle files together for easier transfer or storage. In order to access the contents of a zip file, it must first be unzipped, or extracted. This can be done using a file compression utility or programmatically using code.

In Java, the java.util.zip package provides classes for working with zip files. The ZipOutputStream class can be used to create a new zip file, while the ZipInputStream class can be used to read the contents of an existing zip file.

Thank you for visiting this Article and home that your problem will solve after implementing this code in your project. You can contact us if you face any error.

Post a Comment

0 Comments

Ad Code