Harden untrusted-file parsing, drop two audio-thread allocations, prune dead code (v0.24.0)

SECURITY

A crafted .sf2 hung the app. SoundFontLoader's RIFF walk trusted the chunk
sizes in the file: a negative size moved the cursor BACKWARDS, so the walk
re-read the same chunk header forever. runCatching cannot catch that — there is
no exception, just a thread that never returns. 76 bytes was enough. Every seek
in both the chunk and sub-chunk loops is now forced forward, negative sizes end
the walk, and the sample offset is resolved in Long so a hostile 32-bit start
index can no longer wrap Int and land the read somewhere arbitrary.

Neither ZIP import had a decompression budget. The zip-slip path check does not
see a bomb, because its entries are perfectly well-named — they are just
enormous. A restore streams to disk and filled the device; a project bundle
accumulates in memory and exhausted the heap. New ZipLimits budgets both, with
different limits because they fail differently: 512 MB for a restore, 64 MB for
a bundle, 20k entries either way. An over-budget archive is rejected like any
other bad file, leaving existing data untouched.

PlaybackService was exported with no permission, so any app on the device could
bind the MediaSessionService and take transport control. Now exported="false".
Verified on an emulator that this changes nothing that matters: the session is
still the system's media button session, the notification still posts, the
foreground service survives backgrounding, no SecurityException. The only loss
is discovery by external media browsers (Auto, Assistant, Wear), which this app
never supported.

String.format("%.2f") in three parameter readouts used the default locale, so a
comma-decimal locale rendered knob values inconsistently with the rest of the
monospace UI. Pinned to Locale.US.

PERFORMANCE

Two allocations removed from threads documented as allocation-free:
  - applyLfos() called target.substring(sep + 1) every block for each active
    LFO (~250/s each), in a function that already parses the slot index
    character-by-character to avoid exactly this. Now matched with
    regionMatches, which allocates nothing.
  - busNoteOn() built `(0 until N).map { … }.firstOrNull { … }` twice — a range
    iterator plus an ArrayList per incoming MIDI note. Replaced with an indexed
    freeBusVoice() scan, matching the style used elsewhere in the file.

DEAD CODE

Arrangement.isLaneMuted had no callers (everything reads laneMuted[] directly).
Four tab-title strings and a notification-channel name were left over from an
earlier design — the tabs are composed with literals and media3 names its own
channel. Added the missing android:roundIcon, which is why lint thought
ic_launcher_round was unused; the asset was always meant to be referenced.

Lint is clean of UnusedResources, DefaultLocale and ExportedService. Its
remaining ObsoleteSdkInt advice — merge mipmap-anydpi-v26 into mipmap-anydpi —
is wrong for this AGP version and was reverted: aapt then fails to resolve the
launcher icons at all.

NOT CHANGED, flagged for a decision: android:allowBackup is still true, so
projects, presets, themes and the settings/bindings DataStore go to Google's
cloud backup. That is a standard hardening finding, but it is also a data
portability feature, and the app now has its own backup/restore — a product
call rather than a defect.

New tests: SoundFontLoaderTest (hostile SF2 headers, with timeouts — the hang
reproduces as a TestTimedOutException without the fix) and ZipBombTest (both
import paths, plus a guard that an ordinary backup still restores).

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
Reactorcoremeltdown
2026-11-03 21:16:29 +01:00
co-authored by Claude Opus 5
parent 3453f9f003
commit deb582727f
14 changed files with 385 additions and 33 deletions
@@ -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
}
}
}
@@ -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")
}
}