Secure zip

This commit is contained in:
Thomas 2022-12-27 18:00:24 +01:00
parent eb78c80925
commit e265078210

View file

@ -136,14 +136,22 @@ public class ZipHelper {
f.mkdirs(); f.mkdirs();
} }
boolean successful = true; boolean successful = true;
try (ZipInputStream zin = new ZipInputStream(new FileInputStream(fullPath + ".zip"))) { FileInputStream fileInputStream = new FileInputStream(fullPath + ".zip");
try (ZipInputStream zin = new ZipInputStream(new BufferedInputStream(fileInputStream))) {
ZipEntry ze; ZipEntry ze;
while ((ze = zin.getNextEntry()) != null) { while ((ze = zin.getNextEntry()) != null) {
if (!successful) { if (!successful) {
break; break;
} }
String path = fullPath + ze.getName(); File unzipFile = new File(fullPath, ze.getName());
File unzipFile = new File(path); boolean sure = ensureZipPathSafety(unzipFile, fullPath);
if (!sure) {
Handler mainHandler = new Handler(Looper.getMainLooper());
Runnable myRunnable = () -> Toasty.error(context, context.getString(R.string.toast_error), Toasty.LENGTH_SHORT).show();
mainHandler.post(myRunnable);
return;
}
FileOutputStream out = new FileOutputStream(unzipFile, false); FileOutputStream out = new FileOutputStream(unzipFile, false);
BufferedOutputStream fout = new BufferedOutputStream(out, BUFFER_SIZE); BufferedOutputStream fout = new BufferedOutputStream(out, BUFFER_SIZE);
try { try {
@ -157,9 +165,9 @@ public class ZipHelper {
fout.close(); fout.close();
} }
if (ze.getName().contains("settings")) { if (ze.getName().contains("settings")) {
successful = restoreSettings(context, Uri.fromFile(new File(path))); successful = restoreSettings(context, Uri.fromFile(new File(unzipFile.getAbsolutePath())));
} else if (ze.getName().contains("database")) { } else if (ze.getName().contains("database")) {
successful = importDB(context, path); successful = importDB(context, unzipFile.getAbsolutePath());
} else { } else {
break; break;
} }
@ -183,6 +191,18 @@ public class ZipHelper {
} }
private static boolean ensureZipPathSafety(final File outputFile, final String destDirectory) {
String destDirCanonicalPath;
try {
destDirCanonicalPath = (new File(destDirectory)).getCanonicalPath();
String outputFilecanonicalPath = outputFile.getCanonicalPath();
return outputFilecanonicalPath.startsWith(destDirCanonicalPath);
} catch (IOException e) {
e.printStackTrace();
}
return true;
}
private static String storeSettings(Context context, String suffix) { private static String storeSettings(Context context, String suffix) {
boolean res = false; boolean res = false;
ObjectOutputStream output = null; ObjectOutputStream output = null;