diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 9900bd5..c39547d 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -26,6 +26,7 @@ android:name=".SizzleApp" android:allowBackup="true" android:icon="@mipmap/ic_launcher" + android:roundIcon="@mipmap/ic_launcher_round" android:label="@string/app_name" android:supportsRtl="false" android:theme="@style/Theme.Sizzletracker"> @@ -64,10 +65,19 @@ + when the UI is not visible, and drives the media notification. + + NOT exported: a MediaSessionService with exported="true" and no + permission can be bound by any app on the device, which would hand it + transport control over the session. Nothing here needs an external + controller — the system's own media notification and lockscreen + controls reach the MediaSession directly, not by binding the service, + and the app starts it from its own process. The cost is that external + media browsers (Android Auto, Assistant, Wear) can no longer discover + it, which this app never supported anyway. --> diff --git a/app/src/main/java/cc/tiredsysadmin/android/sizzle/audio/AudioEngine.kt b/app/src/main/java/cc/tiredsysadmin/android/sizzle/audio/AudioEngine.kt index 89815ed..c2a9659 100644 --- a/app/src/main/java/cc/tiredsysadmin/android/sizzle/audio/AudioEngine.kt +++ b/app/src/main/java/cc/tiredsysadmin/android/sizzle/audio/AudioEngine.kt @@ -820,10 +820,19 @@ class AudioEngine( if (!validIdx || tIdx == i) continue val tSlot = proj.toolbox.getOrNull(tIdx) ?: continue val params = tSlot.type?.params ?: continue - val key = target.substring(sep + 1) + // Match the param key by region rather than target.substring(sep + 1): + // this runs every block for each active LFO, and the slot-index parse + // above already goes to this trouble. regionMatches allocates nothing. + val keyFrom = sep + 1 + val keyLen = target.length - keyFrom // Indexed scan (not firstOrNull {}) so no Iterator allocates per block. var specIdx = -1 - for (pi in params.indices) if (params[pi].key == key) { specIdx = pi; break } + for (pi in params.indices) { + val k = params[pi].key + if (k.length == keyLen && target.regionMatches(keyFrom, k, 0, keyLen)) { + specIdx = pi; break + } + } if (specIdx < 0) continue val spec = params[specIdx] @@ -845,7 +854,7 @@ class AudioEngine( val half = (spec.max - spec.min) / 2.0 val modulated = (center + lfo.float("depth", 0.5f) * value * half) .coerceIn(spec.min.toDouble(), spec.max.toDouble()) - tSlot.set(key, modulated.toFloat()) + tSlot.set(spec.key, modulated.toFloat()) } } @@ -1272,22 +1281,35 @@ class AudioEngine( val vs = voiceSample(slot, midi) when { vs != null -> { - val v = (0 until BUS_POLYPHONY).map { busSampleVoices[base + it] } - .firstOrNull { !it.isActive } ?: busSampleVoices[base].also { it.kill() } + val v = freeBusVoice(busSampleVoices, base) v.noteOn(vs.sample, midi, velocity, vs.root, vs.sliceStart, vs.sliceEnd, vs.volume, vs.attack, vs.decay, vs.sustain, vs.release, vs.loop, vs.crossfadeMs) } // Sampler with an empty pad → silent (no synth fallback). type == ToolboxType.SAMPLER -> {} else -> { - val v = (0 until BUS_POLYPHONY).map { busVoices[base + it] } - .firstOrNull { !it.isActive } ?: busVoices[base].also { it.kill() } + val v = freeBusVoice(busVoices, base) v.noteOn(midi, velocity, synthPatch[ch] ?: patchForSlot(slot, proj.tempoBpm)) } } } } + // First idle voice in the bus's BUS_POLYPHONY slice, stealing slot 0 when all are + // busy. Indexed, because the obvious `(0 until N).map { … }.firstOrNull { … }` + // allocated a range iterator and an ArrayList for every incoming MIDI note — on + // the thread that is supposed to stay allocation-free. Two concrete overloads + // rather than a generic one: the voice pools are differently typed arrays. + private fun freeBusVoice(pool: Array, base: Int): SynthVoice { + for (i in 0 until BUS_POLYPHONY) if (!pool[base + i].isActive) return pool[base + i] + return pool[base].also { it.kill() } + } + + private fun freeBusVoice(pool: Array, base: Int): SampleVoice { + for (i in 0 until BUS_POLYPHONY) if (!pool[base + i].isActive) return pool[base + i] + return pool[base].also { it.kill() } + } + /** Release [midi] on every mixer channel listening on [midiChannel]. */ fun busNoteOff(midiChannel: Int, midi: Int) { val proj = project ?: return diff --git a/app/src/main/java/cc/tiredsysadmin/android/sizzle/audio/SoundFontLoader.kt b/app/src/main/java/cc/tiredsysadmin/android/sizzle/audio/SoundFontLoader.kt index 75bfd66..b04e74b 100644 --- a/app/src/main/java/cc/tiredsysadmin/android/sizzle/audio/SoundFontLoader.kt +++ b/app/src/main/java/cc/tiredsysadmin/android/sizzle/audio/SoundFontLoader.kt @@ -44,22 +44,36 @@ object SoundFontLoader { if (readTag(bb) != "sfbk") return null var smplOff = -1; var shdrOff = -1; var shdrBytes = 0 + // RIFF chunk walk over attacker-controlled sizes. Every seek is forced + // FORWARD: a negative (or merely small) size would otherwise move the cursor + // back to bytes already read, and the walk would re-read the same chunk + // header forever. That is not an exception runCatching can mop up — it is a + // thread that never returns, i.e. an ANR from a handful of crafted bytes. while (bb.remaining() >= 8) { + val chunkStart = bb.position() val id = readTag(bb) val size = bb.int - val chunkEnd = (bb.position() + size).coerceAtMost(bb.limit()) + if (size < 0) break // a size that cannot be honoured ends the walk + val chunkEnd = (bb.position().toLong() + size).coerceAtMost(bb.limit().toLong()).toInt() if (id == "LIST" && bb.remaining() >= 4) { val listType = readTag(bb) while (bb.position() + 8 <= chunkEnd) { + val subStart = bb.position() val sid = readTag(bb) val ssize = bb.int + if (ssize < 0) break val dataPos = bb.position() if (listType == "sdta" && sid == "smpl") smplOff = dataPos if (listType == "pdta" && sid == "shdr") { shdrOff = dataPos; shdrBytes = ssize } - bb.position((dataPos + ssize + (ssize and 1)).coerceAtMost(bb.limit())) + val next = (dataPos.toLong() + ssize + (ssize and 1)) + .coerceIn(0L, bb.limit().toLong()).toInt() + if (next <= subStart) break // no forward progress + bb.position(next) } } - bb.position((chunkEnd + (size and 1)).coerceAtMost(bb.limit())) + val next = (chunkEnd.toLong() + (size and 1)).coerceIn(0L, bb.limit().toLong()).toInt() + if (next <= chunkStart) break // no forward progress + bb.position(next) } if (smplOff < 0 || shdrOff < 0 || shdrBytes < SHDR_REC) return null @@ -78,8 +92,10 @@ object SoundFontLoader { val frames = (end - start).coerceIn(0L, MAX_FRAMES.toLong()).toInt() if (frames <= 0) return null val out = FloatArray(frames) - val db = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN) - .apply { position((smplOff + start.toInt() * 2).coerceIn(0, bytes.size)) } + // start is a 32-bit unsigned frame index: `start.toInt() * 2` would wrap for a + // hostile value and land the read at an arbitrary offset. Resolve in Long. + val readAt = (smplOff.toLong() + start * 2L).coerceIn(0L, bytes.size.toLong()).toInt() + val db = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN).apply { position(readAt) } var i = 0 while (i < frames && db.remaining() >= 2) { out[i] = db.short / 32768f; i++ } diff --git a/app/src/main/java/cc/tiredsysadmin/android/sizzle/io/BackupIo.kt b/app/src/main/java/cc/tiredsysadmin/android/sizzle/io/BackupIo.kt index 1bcf222..6442abb 100644 --- a/app/src/main/java/cc/tiredsysadmin/android/sizzle/io/BackupIo.kt +++ b/app/src/main/java/cc/tiredsysadmin/android/sizzle/io/BackupIo.kt @@ -47,17 +47,22 @@ object BackupIo { val stagingRoot = staging.canonicalPath + File.separator var any = false + // The zip-slip check below cannot see a decompression bomb — its entries are + // perfectly well-named, they are just enormous. Budget the extraction too, or + // a few hundred KB of nested zeroes fills the device's storage. + val budget = ZipLimits.forBackup() try { ZipInputStream(BufferedInputStream(input)).use { zin -> var entry: ZipEntry? = zin.nextEntry while (entry != null) { + budget.countEntry() val name = entry.name if (!entry.isDirectory && !name.contains("..")) { val target = File(staging, name) // Zip-slip guard: the resolved path must stay inside staging. if (target.canonicalPath.startsWith(stagingRoot)) { target.parentFile?.mkdirs() - target.outputStream().use { zin.copyTo(it) } + target.outputStream().use { budget.copy(zin, it) } any = true } } @@ -66,7 +71,8 @@ object BackupIo { } } } catch (e: Exception) { - // A truncated / non-ZIP file: bail out without touching the live data. + // A truncated / non-ZIP file, or one over budget: bail out without + // touching the live data, and drop whatever was staged. staging.deleteRecursively(); return false } diff --git a/app/src/main/java/cc/tiredsysadmin/android/sizzle/io/ProjectBundleIo.kt b/app/src/main/java/cc/tiredsysadmin/android/sizzle/io/ProjectBundleIo.kt index 6faf983..67d5b81 100644 --- a/app/src/main/java/cc/tiredsysadmin/android/sizzle/io/ProjectBundleIo.kt +++ b/app/src/main/java/cc/tiredsysadmin/android/sizzle/io/ProjectBundleIo.kt @@ -61,13 +61,18 @@ object ProjectBundleIo { var projectText: String? = null val manifest = HashMap() // sample index -> original id val wavByIndex = HashMap() // sample index -> WAV bytes + // Every entry is held in memory until the whole bundle is read, so an + // oversized or bomb archive is an OOM rather than a full disk here. Same + // budget, same outcome: reject the file and leave the project untouched. + val budget = ZipLimits.forBundle() try { ZipInputStream(BufferedInputStream(input)).use { zin -> var entry: ZipEntry? = zin.nextEntry while (entry != null) { + budget.countEntry() val name = entry.name if (!entry.isDirectory && !name.contains("..")) { - val bytes = zin.readBytes() + val bytes = budget.readBytes(zin) when { name == PROJECT_ENTRY -> projectText = String(bytes, Charsets.UTF_8) name == MANIFEST -> String(bytes, Charsets.UTF_8).lineSequence().forEach { ln -> diff --git a/app/src/main/java/cc/tiredsysadmin/android/sizzle/io/ZipLimits.kt b/app/src/main/java/cc/tiredsysadmin/android/sizzle/io/ZipLimits.kt new file mode 100644 index 0000000..23c3af8 --- /dev/null +++ b/app/src/main/java/cc/tiredsysadmin/android/sizzle/io/ZipLimits.kt @@ -0,0 +1,95 @@ +// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown +// SPDX-License-Identifier: GPL-3.0-or-later + +package cc.tiredsysadmin.android.sizzle.io + +import java.io.InputStream +import java.io.OutputStream + +/** + * Guards against decompression bombs in the two archives the user can hand the app + * from anywhere on the device: a full backup ([BackupIo]) and a shared project + * bundle ([ProjectBundleIo]). + * + * A ZIP reports its own sizes, and nothing obliges them to be true. A few hundred + * kilobytes of nested zeroes expands to gigabytes, which fills the device's storage + * in the backup case and exhausts the heap in the bundle case — neither of which the + * zip-slip path check catches, because every entry is perfectly well-named. The only + * reliable defence is to stop reading at a budget and treat overrun as a bad file. + * + * There are two budgets because the two paths fail differently: a restore streams + * to disk and runs out of storage, while a bundle accumulates in memory and runs out + * of heap. Both are set well above any real project — they exist to stop a bomb, not + * to cap a user. + */ +object ZipLimits { + + /** + * Budget for a whole-app restore, which streams each entry straight to disk. + * The threat is filling the device, so this can be generous: a phone-sized + * sample library sits far below it. + */ + const val MAX_BACKUP_BYTES = 512L * 1024 * 1024 + + /** + * Budget for a project bundle, which is held in memory until the archive has + * been read in full. The threat is the heap, not the disk, and an Android heap + * is typically a couple of hundred megabytes — so this is much tighter. One + * project's samples (a handful of pads, seconds each) are nowhere near it. + */ + const val MAX_BUNDLE_BYTES = 64L * 1024 * 1024 + + /** Entries allowed in one archive, so a bomb cannot be spread thinly either. */ + const val MAX_ENTRIES = 20_000 + + /** Raised when an archive exceeds a budget; callers reject the file. */ + class TooLarge(message: String) : Exception(message) + + /** Budget for a whole-app restore (streamed to disk). */ + fun forBackup() = Budget(MAX_BACKUP_BYTES) + + /** Budget for a project bundle (accumulated in memory). */ + fun forBundle() = Budget(MAX_BUNDLE_BYTES) + + /** + * A running total across the entries of one archive. Not thread-safe: an import + * is a single sequential pass. + */ + class Budget( + private val maxTotalBytes: Long, + private val maxEntries: Int = MAX_ENTRIES, + ) { + private var bytes = 0L + private var entries = 0 + + /** Count one entry. Throws [TooLarge] past [maxEntries]. */ + fun countEntry() { + if (++entries > maxEntries) throw TooLarge("archive has more than $maxEntries entries") + } + + /** Copy one entry's bytes to [out], charging them to the budget. */ + fun copy(input: InputStream, out: OutputStream) { + val buf = ByteArray(DEFAULT_BUFFER_SIZE) + while (true) { + val n = input.read(buf) + if (n <= 0) break + charge(n) + out.write(buf, 0, n) + } + } + + /** Read one entry fully into memory, charging it to the budget. */ + fun readBytes(input: InputStream): ByteArray { + val out = java.io.ByteArrayOutputStream() + copy(input, out) + return out.toByteArray() + } + + private fun charge(n: Int) { + bytes += n + if (bytes > maxTotalBytes) { + throw TooLarge("archive expands past ${maxTotalBytes / (1024 * 1024)} MB") + } + } + } +} diff --git a/app/src/main/java/cc/tiredsysadmin/android/sizzle/model/Arrangement.kt b/app/src/main/java/cc/tiredsysadmin/android/sizzle/model/Arrangement.kt index 6fdb3c7..b0ad77f 100644 --- a/app/src/main/java/cc/tiredsysadmin/android/sizzle/model/Arrangement.kt +++ b/app/src/main/java/cc/tiredsysadmin/android/sizzle/model/Arrangement.kt @@ -22,8 +22,6 @@ class Arrangement { * never sound) while its cells stay in place. Read live on the audio thread. */ val laneMuted: BooleanArray = BooleanArray(LANE_COUNT) - fun isLaneMuted(lane: Int): Boolean = lane in 0 until LANE_COUNT && laneMuted[lane] - /** Editable canvas width in *bars*. */ var lengthBars: Int = MAX_BARS diff --git a/app/src/main/java/cc/tiredsysadmin/android/sizzle/ui/toolbox/NesSynthEditor.kt b/app/src/main/java/cc/tiredsysadmin/android/sizzle/ui/toolbox/NesSynthEditor.kt index d4df217..0c16776 100644 --- a/app/src/main/java/cc/tiredsysadmin/android/sizzle/ui/toolbox/NesSynthEditor.kt +++ b/app/src/main/java/cc/tiredsysadmin/android/sizzle/ui/toolbox/NesSynthEditor.kt @@ -36,6 +36,7 @@ import cc.tiredsysadmin.android.sizzle.ui.components.RetroDropdown import cc.tiredsysadmin.android.sizzle.ui.theme.LocalRetro import kotlinx.coroutines.launch import kotlin.math.roundToInt +import java.util.Locale /** * The bespoke editor for the subtractive synth ([cc.tiredsysadmin.android.sizzle.model.ToolboxType.NES_SYNTH]). @@ -183,7 +184,7 @@ private fun ParamKnob( ) { @Suppress("UNUSED_PARAMETER") val ignored = rev val value = slot.float(key, default) - val text = if (isInt) "${value.roundToInt()}$unit" else String.format("%.2f", value) + unit + val text = if (isInt) "${value.roundToInt()}$unit" else String.format(Locale.US, "%.2f", value) + unit Knob(label, value, min, max, text, modifier, default) { nv -> slot.set(key, if (isInt) nv.roundToInt().toFloat() else nv) vm.bumpForToolbar() diff --git a/app/src/main/java/cc/tiredsysadmin/android/sizzle/ui/toolbox/ParamControl.kt b/app/src/main/java/cc/tiredsysadmin/android/sizzle/ui/toolbox/ParamControl.kt index 7671a8a..4f26331 100644 --- a/app/src/main/java/cc/tiredsysadmin/android/sizzle/ui/toolbox/ParamControl.kt +++ b/app/src/main/java/cc/tiredsysadmin/android/sizzle/ui/toolbox/ParamControl.kt @@ -19,6 +19,7 @@ import cc.tiredsysadmin.android.sizzle.ui.AppViewModel import cc.tiredsysadmin.android.sizzle.ui.components.RetroDropdown import cc.tiredsysadmin.android.sizzle.ui.theme.LocalRetro import kotlin.math.roundToInt +import java.util.Locale /** * One editable parameter row. Enumerated params ([ParamSpec.isEnum]) render as a @@ -66,4 +67,4 @@ fun ParamControl(vm: AppViewModel, slot: ToolboxSlot, spec: ParamSpec) { } private fun formatValue(v: Float): String = - if (v == v.toInt().toFloat()) v.toInt().toString() else String.format("%.2f", v) + if (v == v.toInt().toFloat()) v.toInt().toString() else String.format(Locale.US, "%.2f", v) diff --git a/app/src/main/java/cc/tiredsysadmin/android/sizzle/ui/toolbox/SoundFontEditor.kt b/app/src/main/java/cc/tiredsysadmin/android/sizzle/ui/toolbox/SoundFontEditor.kt index 87ac01e..f0fa345 100644 --- a/app/src/main/java/cc/tiredsysadmin/android/sizzle/ui/toolbox/SoundFontEditor.kt +++ b/app/src/main/java/cc/tiredsysadmin/android/sizzle/ui/toolbox/SoundFontEditor.kt @@ -43,6 +43,7 @@ import cc.tiredsysadmin.android.sizzle.ui.components.PianoOctave import cc.tiredsysadmin.android.sizzle.ui.components.RepeatButton import cc.tiredsysadmin.android.sizzle.ui.components.RetroButton import cc.tiredsysadmin.android.sizzle.ui.theme.LocalRetro +import java.util.Locale /** Upper bound (ms) for the SoundFont loop crossfade stepper. */ private const val MAX_XFADE_MS = 500 @@ -203,7 +204,7 @@ private fun VerticalSlider( } private fun formatSliderValue(v: Float): String = - if (v == v.toInt().toFloat()) v.toInt().toString() else String.format("%.2f", v) + if (v == v.toInt().toFloat()) v.toInt().toString() else String.format(Locale.US, "%.2f", v) /** A slot-auditioning keyboard, laid out and sized like the shared audition / * punch-in keyboard ([cc.tiredsysadmin.android.sizzle.ui.StackedKeyboard]): a small octave diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 7588bf8..6b16e13 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -1,12 +1,3 @@ Sizzletracker - - - TRACKER - MIX - TOOLBOX - SETUP - - - Playback diff --git a/app/src/test/java/cc/tiredsysadmin/android/sizzle/audio/SoundFontLoaderTest.kt b/app/src/test/java/cc/tiredsysadmin/android/sizzle/audio/SoundFontLoaderTest.kt new file mode 100644 index 0000000..b161e83 --- /dev/null +++ b/app/src/test/java/cc/tiredsysadmin/android/sizzle/audio/SoundFontLoaderTest.kt @@ -0,0 +1,106 @@ +// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown +// SPDX-License-Identifier: GPL-3.0-or-later + +package cc.tiredsysadmin.android.sizzle.audio + +import org.junit.Assert.assertNull +import org.junit.Test +import java.io.ByteArrayOutputStream +import java.nio.ByteBuffer +import java.nio.ByteOrder + +/** + * [SoundFontLoader] parses files the user picked from anywhere on the device, so it + * is the app's largest untrusted-input surface. These tests feed it hostile headers + * and require it to fail fast rather than hang or crash. + * + * The timeouts matter as much as the assertions: a RIFF walker that trusts a chunk + * size will seek *backwards* on a negative one and re-read the same bytes forever. + * `runCatching` cannot save a caller from that — there is no exception, just a + * thread that never returns. + */ +class SoundFontLoaderTest { + + private fun sf2(body: ByteArrayOutputStream.() -> Unit): ByteArray = + ByteArrayOutputStream().apply { + write("RIFF".toByteArray()) + write(le32(0)) + write("sfbk".toByteArray()) + body() + }.toByteArray() + + private fun le32(v: Int): ByteArray = + ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN).putInt(v).array() + + /** The hang: a chunk whose size walks the cursor back to where it started. */ + @Test(timeout = 5_000) fun negativeChunkSizeDoesNotHang() { + val bytes = sf2 { + write("LIST".toByteArray()) + write(le32(-8)) + write(ByteArray(64)) + } + assertNull(SoundFontLoader.load(bytes)) + } + + /** The same trap one level down, in the walk over a LIST's sub-chunks. */ + @Test(timeout = 5_000) fun negativeSubChunkSizeDoesNotHang() { + val bytes = sf2 { + write("LIST".toByteArray()) + write(le32(256)) + write("pdta".toByteArray()) + write("shdr".toByteArray()) + write(le32(-16)) + write(ByteArray(240)) + } + assertNull(SoundFontLoader.load(bytes)) + } + + /** A zero-size chunk must still advance, or the walk stalls on it. */ + @Test(timeout = 5_000) fun zeroSizeChunkDoesNotHang() { + val bytes = sf2 { + repeat(8) { + write("junk".toByteArray()) + write(le32(0)) + } + } + assertNull(SoundFontLoader.load(bytes)) + } + + /** A header claiming a gigantic sample region must be capped, not allocated. */ + @Test(timeout = 10_000) fun hugeSampleRegionIsCapped() { + val bytes = sf2 { + write("LIST".toByteArray()) + write(le32(12)) + write("sdta".toByteArray()) + write("smpl".toByteArray()) + write(le32(0)) + write("LIST".toByteArray()) + write(le32(4 + 8 + 46)) + write("pdta".toByteArray()) + write("shdr".toByteArray()) + write(le32(46)) + write(ByteArray(20)) // sample name + write(le32(0)) // start + write(le32(Int.MAX_VALUE)) // end — a 2-billion-frame claim + write(le32(0)); write(le32(0)) + write(le32(44100)) + write(ByteArray(46 - 40)) + } + // Must return (capped or rejected) without trying to allocate 8 GB. + SoundFontLoader.load(bytes) + } + + /** Truncated garbage of every length must be rejected, never crash. */ + @Test(timeout = 10_000) fun truncatedInputIsRejected() { + val full = sf2 { + write("LIST".toByteArray()) + write(le32(12)) + write("sdta".toByteArray()) + write("smpl".toByteArray()) + write(le32(0)) + } + for (n in 0..full.size) { + SoundFontLoader.load(full.copyOf(n)) // must not throw + } + } +} diff --git a/app/src/test/java/cc/tiredsysadmin/android/sizzle/io/ZipBombTest.kt b/app/src/test/java/cc/tiredsysadmin/android/sizzle/io/ZipBombTest.kt new file mode 100644 index 0000000..9d77d79 --- /dev/null +++ b/app/src/test/java/cc/tiredsysadmin/android/sizzle/io/ZipBombTest.kt @@ -0,0 +1,100 @@ +// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown +// SPDX-License-Identifier: GPL-3.0-or-later + +package cc.tiredsysadmin.android.sizzle.io + +import cc.tiredsysadmin.android.sizzle.model.Project +import org.junit.After +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test +import java.io.ByteArrayInputStream +import java.io.ByteArrayOutputStream +import java.io.File +import java.util.zip.ZipEntry +import java.util.zip.ZipOutputStream + +/** + * Both import paths take an archive the user picked from anywhere on the device. A + * ZIP states its own sizes and nothing makes them true: highly compressible filler + * expands by orders of magnitude, which the zip-slip path check cannot see because + * the entries are perfectly well-named. The budget must stop it, and — just as + * important — must leave the existing data alone when it does. + */ +class ZipBombTest { + + private val tmp = File(System.getProperty("java.io.tmpdir"), "sizzle-zipbomb-${System.nanoTime()}") + + @After fun cleanUp() { tmp.deleteRecursively() } + + /** An archive whose entries expand far past the budget. Zeroes deflate ~1000:1, + * so this is a few hundred KB on the wire and 2 GB on the way out. */ + private fun bomb(entryName: String): ByteArray { + val chunk = ByteArray(1024 * 1024) // 1 MB of zeroes + return ByteArrayOutputStream().also { bytes -> + ZipOutputStream(bytes).use { zip -> + repeat(4) { n -> + zip.putNextEntry(ZipEntry("$entryName$n")) + repeat(512) { zip.write(chunk) } // 512 MB per entry + zip.closeEntry() + } + } + }.toByteArray() + } + + /** An archive with an absurd number of tiny entries. */ + private fun manyEntries(): ByteArray = ByteArrayOutputStream().also { bytes -> + ZipOutputStream(bytes).use { zip -> + repeat(ZipLimits.MAX_ENTRIES + 10) { n -> + zip.putNextEntry(ZipEntry("songs/$n.sng")) + zip.write(1) + zip.closeEntry() + } + } + }.toByteArray() + + @Test(timeout = 120_000) fun backupRestoreRejectsABomb() { + val filesDir = File(tmp, "files").apply { mkdirs() } + val keep = File(filesDir, "songs").apply { mkdirs() }.let { File(it, "mine.sng") } + keep.writeText("do not lose me") + + val ok = BackupIo.read(filesDir, ByteArrayInputStream(bomb("songs/big"))) + + assertFalse("a bomb must be rejected", ok) + assertTrue("existing songs must survive a rejected restore", keep.isFile) + assertTrue("staging must be cleaned up", !File(filesDir, ".restore_tmp").exists()) + // Nothing may be left behind on disk beyond what was already there. + val leftover = filesDir.walkTopDown().filter { it.isFile }.sumOf { it.length() } + assertTrue("a rejected restore must not fill the disk (left $leftover bytes)", + leftover < 10L * 1024 * 1024) + } + + @Test(timeout = 120_000) fun backupRestoreRejectsTooManyEntries() { + val filesDir = File(tmp, "files2").apply { mkdirs() } + assertFalse(BackupIo.read(filesDir, ByteArrayInputStream(manyEntries()))) + assertTrue(!File(filesDir, ".restore_tmp").exists()) + } + + @Test(timeout = 120_000) fun bundleImportRejectsABomb() { + val project = Project() + val before = project.name + val samples = File(tmp, "samples").apply { mkdirs() } + + val ok = ProjectBundleIo.read(project, ByteArrayInputStream(bomb("samples/")), samples) + + assertFalse("a bomb must be rejected", ok) + assertTrue("the open project must be untouched", project.name == before) + } + + /** The budget must not reject an ordinary archive. */ + @Test fun anOrdinaryBackupStillRestores() { + val src = File(tmp, "src").apply { mkdirs() } + File(src, "songs").mkdirs() + File(src, "songs/a.sng").writeText("hello") + val zipped = ByteArrayOutputStream().also { BackupIo.write(src, it) }.toByteArray() + + val dst = File(tmp, "dst").apply { mkdirs() } + assertTrue(BackupIo.read(dst, ByteArrayInputStream(zipped))) + assertTrue(File(dst, "songs/a.sng").readText() == "hello") + } +} diff --git a/versions.properties b/versions.properties index cda0663..6cc7d31 100644 --- a/versions.properties +++ b/versions.properties @@ -8,8 +8,8 @@ # or polish. android.versionCode is monotonic and bumps by 1 on every release, # because F-Droid and the Android package manager order installs by it alone. -android.versionName = 0.23.1 -android.versionCode = 52 +android.versionName = 0.24.0 +android.versionCode = 53 # No desktop builds exist yet. These lines are the agreed slots so a port starts # with a version instead of inventing one; `-` means "not built on this