Modern Apps git

← Modern-Apps.git

library: backup restore rejects zip entries escaping the restore directory

Commit
865110f76e93c23e21e177d552693f57724a4147
Author
Vayun Mathur <[email protected]>
When
2026-12-01 10:23 UTC (5 days ago)
Parents
f61b537
BackupHelper.unzipFiles built each destination with
File(targetDir, entry.name) and streamed straight to it —
no containment check. An entry like ../escaped.db in a
malicious or untrusted backup archive landed outside the
restore temp dir (which sits under the app cache dir, so
../../ entries can reach database/datastore payloads), and
the restore's finally-deleteRecursively cleanup never
removed it. zipFiles can never produce such an entry (it
names by relativeTo), so the reader accepting one was a
provable write/read asymmetry. performFullRestore,
BaseBackupAgent.onRestore and ZipBackupFormat.import all
inherit the hole.

Each destination is now canonicalised against the canonical
target root and required to be the root or a descendant,
throwing before any write to that entry. Four regression
tests failed 2/4 pre-fix (both escape shapes written
outside); normal nested archives still round-trip.
Navigation, AppMessages, DatabaseHelper, streak reporting
and DataStore were audited and cleared. Verified:
:library:testDebugUnitTest 211 tests pass; lint BUILD
SUCCESSFUL.

Diff

library/src/main/java/com/vayunmathur/library/util/BackupHelper.kt
diff --git a/library/src/main/java/com/vayunmathur/library/util/BackupHelper.kt b/library/src/main/java/com/vayunmathur/library/util/BackupHelper.ktindex 29e8321e85..47222536c4 100644--- a/library/src/main/java/com/vayunmathur/library/util/BackupHelper.kt+++ b/library/src/main/java/com/vayunmathur/library/util/BackupHelper.kt@@ -55,10 +55,21 @@ object BackupHelper {     }      fun unzipFiles(inputStream: InputStream, targetDir: File) {+        val targetRoot = targetDir.canonicalFile         ZipInputStream(BufferedInputStream(inputStream)).use { zis ->             var entry: ZipEntry? = zis.nextEntry             while (entry != null) {-                val file = File(targetDir, entry.name)+                // A backup is an imported, untrusted stream: an entry name+                // containing `..` (or an absolute path) would otherwise write+                // outside the restore temp dir, where the caller's cleanup+                // never reaches. Zips written by zipFiles only ever contain+                // relative names under baseDir, so rejecting escapes cannot+                // break a legitimate backup.+                val file = File(targetRoot, entry.name).canonicalFile+                require(+                    file.path == targetRoot.path ||+                        file.path.startsWith(targetRoot.path + File.separator)+                ) { "Zip entry escapes target directory: ${entry.name}" }                 if (entry.isDirectory) {                     file.mkdirs()                 } else {
library/src/test/java/com/vayunmathur/library/util/LibraryBackupZipSlipTest.kt
diff --git a/library/src/test/java/com/vayunmathur/library/util/LibraryBackupZipSlipTest.kt b/library/src/test/java/com/vayunmathur/library/util/LibraryBackupZipSlipTest.ktnew file mode 100644index 0000000000..9465c9e832--- /dev/null+++ b/library/src/test/java/com/vayunmathur/library/util/LibraryBackupZipSlipTest.kt@@ -0,0 +1,72 @@+package com.vayunmathur.library.util++import java.io.ByteArrayInputStream+import java.io.ByteArrayOutputStream+import java.io.File+import java.util.zip.ZipEntry+import java.util.zip.ZipOutputStream+import kotlin.test.Test+import kotlin.test.assertFalse+import kotlin.test.assertFailsWith+import kotlin.test.assertTrue++/** BackupHelper unzip containment: entries must never write outside the target dir. */+class LibraryBackupZipSlipTest {++    private fun createTempDir(name: String): File =+        java.nio.file.Files.createTempDirectory(name).toFile()++    private fun zipBytes(entries: Map<String, String>): ByteArray {+        val out = ByteArrayOutputStream()+        ZipOutputStream(out).use { zos ->+            entries.forEach { (name, body) ->+                zos.putNextEntry(ZipEntry(name))+                zos.write(body.toByteArray())+                zos.closeEntry()+            }+        }+        return out.toByteArray()+    }++    @Test fun unzipRejectsParentTraversalEntryAndWritesNothingOutside() {+        val target = createTempDir("zipslip-target")+        val escaped = File(target.parentFile, "zipslip-escaped.txt")+        escaped.delete()+        val bytes = zipBytes(mapOf("../zipslip-escaped.txt" to "pwned"))+        assertFailsWith<Exception> {+            BackupHelper.unzipFiles(ByteArrayInputStream(bytes), target)+        }+        assertFalse(escaped.exists(), "entry ../zipslip-escaped.txt must not write outside target dir")+        assertFalse(File(target, "zipslip-escaped.txt").exists())+    }++    @Test fun unzipAbsoluteEntryNeverWritesAtTheAbsoluteLocation() {+        val target = createTempDir("zipslip-abs-target")+        val escaped = File(createTempDir("zipslip-abs"), "abs-escaped.txt")+        val bytes = zipBytes(mapOf(escaped.absolutePath to "pwned"))+        // File(parent, absoluteName) joins under the parent on this platform,+        // so the entry may either be rejected or land inside the target; it+        // must never be written at the absolute location it names.+        runCatching { BackupHelper.unzipFiles(ByteArrayInputStream(bytes), target) }+        assertFalse(escaped.exists(), "absolute entry must not write outside target dir")+    }++    @Test fun unzipRejectsNestedTraversalEntry() {+        val target = createTempDir("zipslip-nested-target")+        val escaped = File(target.parentFile, "zipslip-nested-escaped.txt")+        escaped.delete()+        val bytes = zipBytes(mapOf("sub/../../zipslip-nested-escaped.txt" to "pwned"))+        assertFailsWith<Exception> {+            BackupHelper.unzipFiles(ByteArrayInputStream(bytes), target)+        }+        assertFalse(escaped.exists(), "nested ../ entry must not write outside target dir")+    }++    @Test fun unzipStillAcceptsNormalNestedEntries() {+        val target = createTempDir("zipslip-ok-target")+        val bytes = zipBytes(mapOf("a.txt" to "alpha", "sub/b.txt" to "beta"))+        BackupHelper.unzipFiles(ByteArrayInputStream(bytes), target)+        assertTrue(File(target, "a.txt").readText() == "alpha")+        assertTrue(File(target, "sub/b.txt").readText() == "beta")+    }+}