Skip to content

Debloat your Android TV, install apps, browse and transfer files on it, all from your phone. Just 3 MB, no tracking, no root, no PC.

Treat every list source as hostile at the point of use

jesse-agent-821b91fb1767024
diff --git a/adb/src/main/kotlin/app/tellyscope/adb/Actions.kt b/adb/src/main/kotlin/app/tellyscope/adb/Actions.kt
index 1177211..76962ac 100644
--- a/adb/src/main/kotlin/app/tellyscope/adb/Actions.kt
+++ b/adb/src/main/kotlin/app/tellyscope/adb/Actions.kt
@@ -130,6 +130,7 @@ class Actions(private val shell: AdbShell) {
setHome(from)
return HomeResult.Failed("the TV kept its own home screen, so nothing was turned off")
}
+ require(PACKAGE.matches(old)) { "not a package name: $old" } // read from the TV, and it goes into a shell line
val off = exec("pm disable-user --user 0 $old", undo = null) { "disabled-user" in it }
if (off is ActionResult.Failed) {
setHome(from)
@@ -293,8 +294,10 @@ class Actions(private val shell: AdbShell) {
* HOME, for a launcher with no icon of its own.
*/
private suspend fun open(pkg: String): ActionResult {
+ require(PACKAGE.matches(pkg)) { "not a package name: $pkg" }
var last = ""
for (category in listOf("android.intent.category.LEANBACK_LAUNCHER", "android.intent.category.LAUNCHER", "android.intent.category.HOME")) {
+ require(CATEGORY.matches(category)) { "not an intent category: $category" } // both go into the shell line
val r = shell.shell("monkey -p $pkg -c $category 1 2>&1")
if (r.exitCode == 0 && "No activities found" !in r.output && "aborted" !in r.output) {
return ActionResult.Done(undo = null)
@@ -312,6 +315,7 @@ class Actions(private val shell: AdbShell) {
internal companion object {
val PACKAGE = Regex("[A-Za-z][A-Za-z0-9_]*(\\.[A-Za-z0-9_]+)+|android")
val ACTIVITY = Regex("(${PACKAGE.pattern})/[A-Za-z0-9_.$]+")
+ private val CATEGORY = Regex("android\\.intent\\.category\\.[A-Z_]+")
/**
* Android's SecurityException when ADB tries to turn on an app the TV disabled itself:
diff --git a/app/src/main/java/app/tellyscope/data/AdbDeviceSource.kt b/app/src/main/java/app/tellyscope/data/AdbDeviceSource.kt
index 37ff15f..1f3d8f0 100644
--- a/app/src/main/java/app/tellyscope/data/AdbDeviceSource.kt
+++ b/app/src/main/java/app/tellyscope/data/AdbDeviceSource.kt
@@ -487,7 +487,7 @@ class AdbDeviceSource(context: Context) : DeviceSource {
val label = labels[packageName] ?: AppNames.fallback(packageName)
val service = packageName.takeIf { it in serviceLaunchers }?.let { actions.homeService(it) }
?: throw IllegalStateException("$label has no accessibility service")
- if (!actions.setService(service, true)) throw IllegalStateException(serviceNotOn(label))
+ if (!actions.grant(service)) throw IllegalStateException(serviceNotOn(label))
// Undo of the switch to it turns it off again, as if the switch had turned it on.
openSwitch(deviceId, packageName)?.let { book.amend(it, mapOf("service" to service)) }
Unit
@@ -771,7 +771,7 @@ class AdbDeviceSource(context: Context) : DeviceSource {
if (from == null || !actions.setHome(from)) {
homeLeft = true
errors += "the TV kept ${labelOf(to.substringBefore('/'))} as the home screen"
- } else p[ResetRecord.SERVICE]?.let { if (!actions.setService(it, true)) errors += serviceNotOn(name) }
+ } else p[ResetRecord.SERVICE]?.let { if (!actions.grant(it)) errors += serviceNotOn(name) }
}
val ownHome = p[ResetRecord.TO]?.substringBefore('/')?.takeIf { homeLeft }
suspend fun each(pkgs: List<String>, change: suspend (String) -> Unit) = pkgs.filter { pkg ->
@@ -1122,7 +1122,7 @@ internal suspend fun switchHome(
is HomeResult.Switched -> {
// Where the TV sends Home to its own launcher, the new one holds it with this service.
val service = pkg.takeIf { withService && it in serviceLaunchers }?.let { actions.homeService(it) }?.takeUnless { actions.serviceOn(it) }
- val on = service?.let { actions.setService(it, true) }
+ val on = service?.let { actions.grant(it) }
val was = r.from?.substringBefore('/')?.takeIf { r.kept }
val old = was?.takeIf { it in serviceLaunchers }?.let { actions.homeService(it) }?.takeIf { actions.serviceOn(it) }
val off = old?.let { actions.setService(it, false) }
@@ -1149,6 +1149,14 @@ internal suspend fun switchHome(
is HomeResult.Failed -> throw ActionFailed(r.output.ifEmpty { "the TV refused" }, r.details)
}
+/**
+ * Turns accessibility [service] on, only for a launcher in [ACCESSIBILITY_LAUNCHERS]. Every path that
+ * turns one on comes here, so neither a fetched list nor a saved record can name another; false
+ * for any other, as for a TV that refused.
+ */
+internal suspend fun Actions.grant(service: String): Boolean =
+ service.substringBefore('/') in ACCESSIBILITY_LAUNCHERS && setService(service, true)
+
/**
* The rest of [switch]'s Undo once its old launcher is on again: Home back to that launcher, the
* service the switch turned on off, and the old one's back on. False when Home didn't go back.
@@ -1156,7 +1164,7 @@ internal suspend fun switchHome(
internal suspend fun undoHomeSwitch(actions: Actions, switch: HistoryEntry): Boolean {
val back = switch.previous?.get("from")?.let { actions.setHome(it) }
switch.previous?.get("service")?.let { actions.setService(it, false) }
- switch.previous?.get("fromService")?.let { actions.setService(it, true) }
+ switch.previous?.get("fromService")?.let { actions.grant(it) }
return back != false
}
diff --git a/app/src/main/java/app/tellyscope/data/DeviceLists.kt b/app/src/main/java/app/tellyscope/data/DeviceLists.kt
index 19d4257..0222305 100644
--- a/app/src/main/java/app/tellyscope/data/DeviceLists.kt
+++ b/app/src/main/java/app/tellyscope/data/DeviceLists.kt
@@ -156,6 +156,9 @@ private val FILE = Regex("devices/[A-Za-z0-9][A-Za-z0-9._-]*\\.json")
private val LIST_FILE = Regex("lists/[a-z]+\\.json")
private val LOGO_FILE = Regex("logos/[a-z0-9]+\\.png")
private val SHA256 = Regex("[0-9a-f]{64}")
+/** A list id goes into `picks.tsv`, one tab-separated line per TV, so no tab or newline. */
+private val LIST_ID = Regex("[A-Za-z0-9][A-Za-z0-9._-]{0,63}")
+private val COMMIT = Regex("[0-9a-f]{7,40}")
private const val SCHEMA = 1
/** The props a match rule may name, read from `ro.product.*`; brand also finds the maker's lists. */
@@ -175,18 +178,18 @@ fun matches(rule: Map<String, List<String>>?, props: Map<String, String?>): Bool
fun parseIndex(text: String): ListIndex? = try {
val o = jsonObject(text)
if (o.optInt("schema") != SCHEMA) null else ListIndex(
- commit = o.optJSONObject("source")?.optStringOrNull("commit"),
+ commit = o.optJSONObject("source")?.optStringOrNull("commit")?.takeIf { COMMIT.matches(it) },
devices = o.getJSONArray("devices").objectsOrSkip { d ->
ListEntry(
id = d.getString("id"),
- name = d.getString("name"),
+ name = plainText(d.getString("name"), NAME_MAX),
match = d.optJSONObject("match")?.let { m ->
m.keys().asSequence().associateWith { k -> m.getJSONArray(k).strings() }
},
sdk = d.optIntOrNull("sdk"),
file = d.getString("file"),
sha256 = d.getString("sha256"),
- ).takeIf { FILE.matches(it.file) && SHA256.matches(it.sha256) }
+ ).takeIf { LIST_ID.matches(it.id) && it.name.isNotEmpty() && FILE.matches(it.file) && SHA256.matches(it.sha256) }
},
lists = o.files("lists", LIST_FILE),
logos = o.files("logos", LOGO_FILE),
@@ -212,16 +215,16 @@ private fun JSONObject.files(key: String, pattern: Regex): Map<String, ListFile>
fun parseList(text: String, id: String): DeviceList? = try {
val o = jsonObject(text)
val tested = o.optJSONObject("tested")
- fun packages(a: JSONArray?) = a?.objectsOrSkip { ListPackage(it.getString("pkg"), it.optStringOrNull("note"), it.optBoolean("optional")) }
+ fun packages(a: JSONArray?) = a?.objectsOrSkip { ListPackage(it.getString("pkg"), it.optStringOrNull("note")?.let { n -> plainText(n, NOTE_MAX) }, it.optBoolean("optional")) }
.orEmpty().filter { PACKAGE.matches(it.pkg) }
if (o.optInt("schema") != SCHEMA || o.optString("id") != id) null else DeviceList(
id = id,
- name = o.getString("name"),
- testedOs = tested?.optStringOrNull("os"),
+ name = plainText(o.getString("name"), NAME_MAX),
+ testedOs = tested?.optStringOrNull("os")?.let { plainText(it, NAME_MAX) },
sdk = tested?.optIntOrNull("sdk"),
keep = packages(o.optJSONArray("keep")).map { it.pkg }.toSet(),
groups = o.getJSONArray("groups").objectsOrSkip { g ->
- ListGroup(g.optString("title"), packages(g.optJSONArray("packages")))
+ ListGroup(plainText(g.optString("title"), NAME_MAX), packages(g.optJSONArray("packages")))
}.filter { it.packages.isNotEmpty() },
)
} catch (_: org.json.JSONException) {
@@ -260,8 +263,8 @@ class DeviceLists(
private val picks = File(dir, "picks.tsv")
private val sourceFile = File(dir, "source.txt")
- /** The folder holding `index.json`: one the user set, else [LISTS_BASE]. */
- val base: String get() = custom() ?: LISTS_BASE
+ /** The folder holding `index.json`: one the user set, else [LISTS_BASE]. Checked again here, so a stored address that isn't `https` is never used. */
+ val base: String get() = custom()?.let(::normalize) ?: LISTS_BASE
/** The user's own source, or null for tellyscope-devices. */
@Synchronized
@@ -323,9 +326,10 @@ class DeviceLists(
return SharedFiles(get("launchers"), get("labels"), get("streaming"))
}
- /** The lists as last cached, without the network, for the moment before [shared] answers. */
+ /** The lists as last cached, without the network, for the moment before [shared] answers; each only while it matches the cached index. */
suspend fun cachedShared(): SharedFiles = withContext(Dispatchers.IO) {
- fun read(name: String) = File(dir, "lists/$name.json").takeIf { it.exists() }?.readText()
+ val lists = File(dir, "index.json").takeIf { it.exists() }?.readText()?.let(::parseIndex)?.lists.orEmpty()
+ fun read(name: String) = lists[name]?.let { f -> cached(f.file)?.takeIf { sha256(it) == f.sha256 } }?.decodeToString()
SharedFiles(read("launchers"), read("labels"), read("streaming"))
}
@@ -336,17 +340,30 @@ class DeviceLists(
*/
suspend fun logo(name: String): ByteArray? {
val known = index ?: withContext(Dispatchers.IO) { File(dir, "index.json").takeIf { it.exists() }?.readText()?.let(::parseIndex) }
- return known?.logos?.get(name)?.let { file(it.file, it.sha256) }
+ return known?.logos?.get(name)?.let { file(it.file, it.sha256, Png::ok) }
}
- /** [path] under [dir] when its bytes match [sha], else fetched from [base] and cached if they do. */
- private suspend fun file(path: String, sha: String): ByteArray? = withContext(Dispatchers.IO) {
- val cache = File(dir, path) // lists/devices/<id>.json and the like, apart from index.json
- cache.takeIf { it.exists() }?.readBytes()?.takeIf { sha256(it) == sha }
- ?: attempt { fetch(base + path) }?.takeIf { sha256(it) == sha }
+ /**
+ * [path] under [dir] when its bytes match [sha] and pass [valid], else fetched from [base] and
+ * cached if they do. Null for a path that isn't one the index may name or that leaves [dir].
+ */
+ private suspend fun file(path: String, sha: String, valid: (ByteArray) -> Boolean = { true }): ByteArray? = withContext(Dispatchers.IO) {
+ val cache = cacheFile(path) ?: return@withContext null
+ fun ok(b: ByteArray) = sha256(b) == sha && valid(b)
+ cache.takeIf { it.exists() }?.readBytes()?.takeIf(::ok)
+ ?: attempt { fetch(base + path) }?.takeIf(::ok)
?.also { cache.parentFile?.mkdirs(); cache.writeBytes(it) }
}
+ private fun cached(path: String): ByteArray? = cacheFile(path)?.takeIf { it.exists() }?.readBytes()
+
+ /** Where [path] is cached: only a name [parseIndex] keeps, and only inside [dir] once resolved. */
+ private fun cacheFile(path: String): File? {
+ if (!FILE.matches(path) && !LIST_FILE.matches(path) && !LOGO_FILE.matches(path)) return null
+ val root = dir.canonicalFile
+ return File(root, path).canonicalFile.takeIf { it.path.startsWith(root.path + File.separator) }
+ }
+
/**
* The list for a TV: the one picked by hand for [key], else the first whose rule matches
* [props], else the one named after its model. Without one, every list from its maker.
@@ -422,14 +439,23 @@ fun sourceName(base: String): String {
}
private const val MAX_BYTES = 2 shl 20 // 2 MiB; the index is ~60 KB
+private const val MAX_MILLIS = 30_000L
-/** Plain GET with short timeouts, so a slow network falls back to the cache rather than hanging. */
+/**
+ * Plain GET with short timeouts, so a slow network falls back to the cache rather than hanging.
+ * `https` only, where it ends up too: a redirect to anything else fails. A server that sends a
+ * byte every few seconds still gives up after [MAX_MILLIS].
+ */
internal suspend fun download(url: String): ByteArray = withContext(Dispatchers.IO) {
+ require(url.startsWith("https://", ignoreCase = true)) { "not https: $url" }
val c = URL(url).openConnection() as HttpURLConnection
c.connectTimeout = 10_000
c.readTimeout = 10_000
+ val start = System.nanoTime()
try {
check(c.responseCode == 200) { "HTTP ${c.responseCode}" }
+ check(c.url.protocol.equals("https", ignoreCase = true)) { "redirected off https" }
+ check(c.contentLengthLong <= MAX_BYTES) { "too large" }
c.inputStream.use { s ->
val out = java.io.ByteArrayOutputStream()
val buf = ByteArray(8192)
@@ -437,6 +463,7 @@ internal suspend fun download(url: String): ByteArray = withContext(Dispatchers.
val n = s.read(buf).takeIf { it >= 0 } ?: break
out.write(buf, 0, n)
check(out.size() <= MAX_BYTES) { "too large" }
+ check(System.nanoTime() - start <= MAX_MILLIS * 1_000_000) { "too slow" }
}
out.toByteArray()
}
@@ -450,7 +477,7 @@ private fun sha256(b: ByteArray) = MessageDigest.getInstance("SHA-256").digest(b
/** Real lists nest about four deep; org.json parses recursively, so a deeply nested file would overflow the stack. */
private const val MAX_DEPTH = 32
-private fun jsonObject(text: String): JSONObject {
+internal fun jsonObject(text: String): JSONObject {
if (depth(text) > MAX_DEPTH) throw org.json.JSONException("nested deeper than $MAX_DEPTH")
return JSONObject(text)
}
@@ -476,6 +503,24 @@ internal fun depth(text: String): Int {
return max
}
+internal const val NAME_MAX = 80
+internal const val NOTE_MAX = 300
+
+/**
+ * Fetched text as it may be shown: no control characters, no bidi controls that would make it
+ * read in another order ("\u202Egnp.exe"), no line breaks of Unicode's own, at most [max]
+ * characters, trimmed.
+ */
+internal fun plainText(s: String, max: Int): String {
+ val clean = s.filterNot { Character.getType(it) == Character.CONTROL.toInt() || it in BIDI || it == '\u2028' || it == '\u2029' }.trim()
+ if (clean.length <= max) return clean
+ // Never half a surrogate pair at the cut.
+ val end = if (Character.isHighSurrogate(clean[max - 1])) max - 1 else max
+ return clean.substring(0, end).trimEnd()
+}
+
+private val BIDI = setOf('\u061C', '\u200E', '\u200F') + ('\u202A'..'\u202E') + ('\u2066'..'\u2069')
+
/** [f] over each element, leaving out any that isn't an object or that [f] can't read. */
internal fun <T : Any> JSONArray.objectsOrSkip(f: (JSONObject) -> T?): List<T> = (0 until length()).mapNotNull {
try {
diff --git a/app/src/main/java/app/tellyscope/data/Launchers.kt b/app/src/main/java/app/tellyscope/data/Launchers.kt
index b3ff46a..1585f70 100644
--- a/app/src/main/java/app/tellyscope/data/Launchers.kt
+++ b/app/src/main/java/app/tellyscope/data/Launchers.kt
@@ -6,7 +6,6 @@ import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
-import org.json.JSONObject
/**
* Launchers that keep Home with their own accessibility service, for TVs whose Home button opens
@@ -35,13 +34,13 @@ data class KnownLauncher(
/** Empty unless it is schema 1; entries that can't be read or aren't package names are dropped. */
fun parseLaunchers(text: String): List<KnownLauncher> = try {
- val o = JSONObject(text)
+ val o = jsonObject(text)
if (o.optInt("schema") != 1) emptyList() else o.getJSONArray("launchers").objectsOrSkip { l ->
KnownLauncher(
pkg = l.getString("package"),
- name = l.getString("name"),
- about = l.optStringOrNull("about"),
- ).takeIf { PACKAGE.matches(it.pkg) }
+ name = plainText(l.getString("name"), NAME_MAX),
+ about = l.optStringOrNull("about")?.let { plainText(it, NOTE_MAX) }?.ifEmpty { null },
+ ).takeIf { PACKAGE.matches(it.pkg) && it.name.isNotEmpty() }
}
} catch (_: org.json.JSONException) {
emptyList()
@@ -53,12 +52,12 @@ fun parseLaunchers(text: String): List<KnownLauncher> = try {
* are dropped.
*/
fun parseLabels(text: String): Map<String, String> = try {
- val o = JSONObject(text)
+ val o = jsonObject(text)
if (o.optInt("schema") != 1) emptyMap() else buildMap {
o.getJSONArray("groups").objectsOrSkip { it.getJSONObject("labels") }.forEach { labels ->
for (pkg in labels.keys()) {
if (pkg != "android" && !PACKAGE.matches(pkg)) continue
- labels.optStringOrNull(pkg)?.let { put(pkg, it) }
+ labels.optStringOrNull(pkg)?.let { plainText(it, NAME_MAX) }?.ifEmpty { null }?.let { put(pkg, it) }
}
}
}
diff --git a/app/src/main/java/app/tellyscope/data/Png.kt b/app/src/main/java/app/tellyscope/data/Png.kt
new file mode 100644
index 0000000..d57b90a
--- /dev/null
+++ b/app/src/main/java/app/tellyscope/data/Png.kt
@@ -0,0 +1,47 @@
+// SPDX-License-Identifier: GPL-3.0-only
+
+package app.tellyscope.data
+
+import android.graphics.Bitmap
+import android.graphics.BitmapFactory
+
+/**
+ * The checks a fetched logo passes before it is cached or decoded. A PNG's width and height sit in
+ * its header, so a small file that would decode to a huge bitmap is refused unread.
+ */
+object Png {
+ /** The largest logo today is about 9 KB. */
+ const val MAX_BYTES = 64 * 1024
+
+ /** Logos are drawn at four times their size in dp, about 280 × 80 px. */
+ const val MAX_SIDE = 1024
+
+ private val MAGIC = byteArrayOf(0x89.toByte(), 'P'.code.toByte(), 'N'.code.toByte(), 'G'.code.toByte(), 0x0D, 0x0A, 0x1A, 0x0A)
+ private val IHDR = "IHDR".toByteArray()
+
+ /** Width and height from the header, or null when [b] doesn't start like a PNG. */
+ fun size(b: ByteArray): Pair<Int, Int>? {
+ if (b.size < 24 || !b.copyOfRange(0, 8).contentEquals(MAGIC) || !b.copyOfRange(12, 16).contentEquals(IHDR)) return null
+ return int(b, 16) to int(b, 20)
+ }
+
+ /** A PNG no larger than [MAX_BYTES] whose sides are 1 to [MAX_SIDE] pixels. */
+ fun ok(b: ByteArray): Boolean = b.size <= MAX_BYTES && fits(size(b))
+
+ /**
+ * [b] as a bitmap after [ok], with the size the decoder itself reads (`inJustDecodeBounds`)
+ * checked again before the pixels are; null for anything that fails either.
+ */
+ fun decode(b: ByteArray): Bitmap? {
+ if (!ok(b)) return null
+ val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
+ BitmapFactory.decodeByteArray(b, 0, b.size, bounds)
+ if (bounds.outMimeType != "image/png" || !fits(bounds.outWidth to bounds.outHeight)) return null
+ return BitmapFactory.decodeByteArray(b, 0, b.size)
+ }
+
+ fun fits(size: Pair<Int, Int>?): Boolean = size != null && size.first in 1..MAX_SIDE && size.second in 1..MAX_SIDE
+
+ private fun int(b: ByteArray, at: Int) =
+ (b[at].toInt() and 0xFF shl 24) or (b[at + 1].toInt() and 0xFF shl 16) or (b[at + 2].toInt() and 0xFF shl 8) or (b[at + 3].toInt() and 0xFF)
+}
diff --git a/app/src/main/java/app/tellyscope/data/Streaming.kt b/app/src/main/java/app/tellyscope/data/Streaming.kt
index c906e06..e46b86d 100644
--- a/app/src/main/java/app/tellyscope/data/Streaming.kt
+++ b/app/src/main/java/app/tellyscope/data/Streaming.kt
@@ -35,13 +35,13 @@ private fun JSONObject.colorOrNull(k: String): Long? =
* name is dropped, and so are packages that aren't package names.
*/
fun parseStreaming(text: String): List<StreamingService> = try {
- val o = JSONObject(text)
+ val o = jsonObject(text)
if (o.optInt("schema") != 1) emptyList() else o.getJSONArray("groups").objectsOrSkip { it }.flatMap { g ->
- val group = g.getString("name")
+ val group = plainText(g.getString("name"), NAME_MAX)
g.getJSONArray("services").objectsOrSkip { s ->
val pkgs = s.optJSONArray("packages")?.let { a -> (0 until a.length()).map { a.optString(it) } }.orEmpty().filter { PACKAGE.matches(it) }
StreamingService(
- name = s.getString("name"),
+ name = plainText(s.getString("name"), NAME_MAX),
packages = pkgs,
color = s.colorOrNull("color") ?: return@objectsOrSkip null,
color2 = s.colorOrNull("color2"),
diff --git a/app/src/main/java/app/tellyscope/ui/RemoteScreen.kt b/app/src/main/java/app/tellyscope/ui/RemoteScreen.kt
index 7789b05..3cc950b 100644
--- a/app/src/main/java/app/tellyscope/ui/RemoteScreen.kt
+++ b/app/src/main/java/app/tellyscope/ui/RemoteScreen.kt
@@ -138,7 +138,7 @@ import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.graphics.luminance
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.LocalDensity
-import android.graphics.BitmapFactory
+import app.tellyscope.data.Png
import app.tellyscope.data.SharedLists
import app.tellyscope.data.RemoteButtons
import app.tellyscope.data.StreamingService
@@ -776,7 +776,7 @@ private fun ServicePill(s: StreamingService, modifier: Modifier = Modifier, inte
val look = RemoteButtons.look(s, c.surfaceContainerLow.toArgb().toLong() and 0xFFFFFFFF, dark)
// The name stands in until the logo is downloaded, or for good when it can't be.
val logo = produceState<ImageBitmap?>(null, s.logo) {
- value = SharedLists.logo(s.logo)?.let { BitmapFactory.decodeByteArray(it, 0, it.size) }?.asImageBitmap()
+ value = SharedLists.logo(s.logo)?.let(Png::decode)?.asImageBitmap()
}.value
val fill = look.fill2?.let { Brush.linearGradient(listOf(Color(look.fill), Color(it))) } ?: SolidColor(Color(look.fill))
Box(
diff --git a/app/src/test/java/app/tellyscope/DeviceListsTest.kt b/app/src/test/java/app/tellyscope/DeviceListsTest.kt
index 94e52d3..28ff814 100644
--- a/app/src/test/java/app/tellyscope/DeviceListsTest.kt
+++ b/app/src/test/java/app/tellyscope/DeviceListsTest.kt
@@ -262,7 +262,9 @@ class DeviceListsTest {
}
private val launchers = """{"schema": 1, "launchers": [{"package": "com.good.launcher", "name": "Good"}]}""".toByteArray()
- private val logo = byteArrayOf(0x89.toByte(), 'P'.code.toByte(), 'N'.code.toByte(), 'G'.code.toByte())
+ /** A PNG signature and an IHDR for 1 × 1, which is all [app.tellyscope.data.Png.ok] reads. */
+ private val logo = byteArrayOf(0x89.toByte(), 'P'.code.toByte(), 'N'.code.toByte(), 'G'.code.toByte(), 0x0D, 0x0A, 0x1A, 0x0A) +
+ byteArrayOf(0, 0, 0, 13) + "IHDR".toByteArray() + byteArrayOf(0, 0, 0, 1, 0, 0, 0, 1, 8, 6, 0, 0, 0)
/** An index with only lists and logos; [bad] adds entries whose file is outside lists/ or logos/. */
private fun sharedIndex(launchersSha: String = sha256(launchers), bad: Boolean = false) = """
diff --git a/app/src/test/java/app/tellyscope/HostileSourceTest.kt b/app/src/test/java/app/tellyscope/HostileSourceTest.kt
new file mode 100644
index 0000000..ca72ce4
--- /dev/null
+++ b/app/src/test/java/app/tellyscope/HostileSourceTest.kt
@@ -0,0 +1,240 @@
+// SPDX-License-Identifier: GPL-3.0-only
+
+package app.tellyscope
+
+import app.tellyscope.adb.Action as AdbAction
+import app.tellyscope.adb.Actions
+import app.tellyscope.adb.ShellResult
+import app.tellyscope.data.DeviceLists
+import app.tellyscope.data.LISTS_BASE
+import app.tellyscope.data.Png
+import app.tellyscope.data.SourceResult
+import app.tellyscope.data.download
+import app.tellyscope.data.grant
+import app.tellyscope.data.parseIndex
+import app.tellyscope.data.parseLabels
+import app.tellyscope.data.parseLaunchers
+import app.tellyscope.data.parseList
+import app.tellyscope.data.parseStreaming
+import kotlinx.coroutines.test.runTest
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Assert.fail
+import org.junit.Rule
+import org.junit.Test
+import org.junit.rules.TemporaryFolder
+import org.junit.runner.RunWith
+import org.robolectric.RobolectricTestRunner
+import org.robolectric.annotation.Config
+import java.io.File
+import java.io.IOException
+import java.security.MessageDigest
+
+/**
+ * A list source written by an attacker: a fork, where the tellyscope-devices checks never run.
+ * Each test serves one hostile file and checks it never reaches the TV's shell, the disk outside
+ * the cache, the bitmap decoder or the screen as sent.
+ */
+@RunWith(RobolectricTestRunner::class)
+@Config(sdk = [35])
+class HostileSourceTest {
+ @get:Rule val tmp = TemporaryFolder()
+
+ private val ran = mutableListOf<String>()
+ private val actions = Actions { command -> ran += command; ShellResult("", 0) }
+
+ private fun sha256(b: ByteArray) = MessageDigest.getInstance("SHA-256").digest(b).joinToString("") { "%02x".format(it) }
+
+ /** The files of a source at [LISTS_BASE]; every URL asked for is kept in [asked]. */
+ private val asked = mutableListOf<String>()
+ private fun served(files: Map<String, ByteArray>): suspend (String) -> ByteArray = { url ->
+ asked += url
+ files[url.removePrefix(LISTS_BASE)] ?: throw IOException("404 $url")
+ }
+
+ private fun index(logos: Map<String, Pair<String, ByteArray>> = emptyMap(), lists: Map<String, Pair<String, ByteArray>> = emptyMap()): ByteArray {
+ fun files(m: Map<String, Pair<String, ByteArray>>) = m.entries.joinToString(",") { (k, v) -> "\"$k\": {\"file\": \"${v.first}\", \"sha256\": \"${sha256(v.second)}\"}" }
+ return """{"schema": 1, "devices": [], "lists": {${files(lists)}}, "logos": {${files(logos)}}}""".toByteArray()
+ }
+
+ /** A PNG header (signature and IHDR) claiming [w] × [h], padded to [size] bytes. */
+ private fun png(w: Int, h: Int, size: Int = 64): ByteArray {
+ val b = ByteArray(maxOf(size, 33))
+ byteArrayOf(0x89.toByte(), 'P'.code.toByte(), 'N'.code.toByte(), 'G'.code.toByte(), 0x0D, 0x0A, 0x1A, 0x0A).copyInto(b)
+ byteArrayOf(0, 0, 0, 13, 'I'.code.toByte(), 'H'.code.toByte(), 'D'.code.toByte(), 'R'.code.toByte()).copyInto(b, 8)
+ fun int(v: Int, at: Int) = (0..3).forEach { b[at + it] = (v shr (24 - 8 * it)).toByte() }
+ int(w, 16)
+ int(h, 20)
+ b[24] = 8 // bit depth
+ b[25] = 6 // RGBA
+ return b
+ }
+
+ // a.b;reboot
+
+ @Test fun aPackageWithAShellCommandIsDroppedFromEveryList() {
+ val evil = "a.b;reboot"
+ assertTrue(parseLaunchers("""{"schema": 1, "launchers": [{"package": "$evil", "name": "Evil", "about": "x"}]}""").isEmpty())
+ assertTrue(parseLabels("""{"schema": 1, "groups": [{"labels": {"$evil": "Evil"}}]}""").isEmpty())
+ assertTrue(parseStreaming("""{"schema": 1, "groups": [{"name": "G", "services": [{"name": "Evil", "packages": ["$evil"], "color": "#000000", "logo": "evil"}]}]}""").isEmpty())
+ val list = parseList("""{"schema": 1, "id": "x", "name": "X", "groups": [{"title": "T", "packages": [{"pkg": "$evil"}]}]}""", "x")
+ assertTrue(list!!.groups.isEmpty())
+ }
+
+ @Test fun aPackageWithAShellCommandNeverReachesTheShell() = runTest {
+ for (action in AdbAction.entries) {
+ try {
+ actions.run(action, "a.b;reboot")
+ fail("$action ran")
+ } catch (_: IllegalArgumentException) {
+ }
+ }
+ for (call in listOf<suspend () -> Unit>(
+ { actions.makeHome("a.b;reboot") },
+ { actions.openStore("a.b;reboot") },
+ { actions.installed("a.b;reboot") },
+ { actions.setHome("a.b/.Main;reboot") },
+ { actions.handOff(null, "a.b/.Main';reboot;'") },
+ )) {
+ try {
+ call()
+ fail("ran")
+ } catch (_: IllegalArgumentException) {
+ }
+ }
+ assertEquals(emptyList<String>(), ran)
+ }
+
+ // ../../x.png
+
+ @Test fun aLogoPathOutOfTheCacheIsDroppedAndNeverFetched() = runTest {
+ val dir = tmp.newFolder("lists")
+ val bytes = png(10, 10)
+ val lists = DeviceLists(dir, served(mapOf("index.json" to index(logos = mapOf("x" to ("logos/../../x.png" to bytes))), "logos/../../x.png" to bytes)))
+ assertTrue(lists.index()!!.logos.isEmpty())
+ assertNull(lists.logo("x"))
+ assertEquals(listOf(LISTS_BASE + "index.json"), asked)
+ assertFalse(File(tmp.root, "x.png").exists())
+ // And a logo name from streaming.json can't name a path either.
+ assertTrue(parseStreaming("""{"schema": 1, "groups": [{"name": "G", "services": [{"name": "S", "packages": ["a.b"], "color": "#000000", "logo": "../../x"}]}]}""").isEmpty())
+ }
+
+ // An oversized PNG, and a 20000 × 20000 one
+
+ @Test fun anOversizedPngIsNeitherCachedNorDecoded() = runTest {
+ val big = png(100, 100, size = Png.MAX_BYTES + 1)
+ val dir = tmp.newFolder()
+ val lists = DeviceLists(dir, served(mapOf("index.json" to index(logos = mapOf("big" to ("logos/big.png" to big))), "logos/big.png" to big)))
+ lists.index()
+ assertNull(lists.logo("big"))
+ assertFalse(File(dir, "logos/big.png").exists())
+ assertNull(Png.decode(big))
+ }
+
+ @Test fun aDecompressionBombIsRefusedFromItsHeader() = runTest {
+ val bomb = png(20000, 20000)
+ assertEquals(20000 to 20000, Png.size(bomb))
+ assertFalse(Png.ok(bomb))
+ assertNull(Png.decode(bomb))
+ val dir = tmp.newFolder()
+ val lists = DeviceLists(dir, served(mapOf("index.json" to index(logos = mapOf("bomb" to ("logos/bomb.png" to bomb))), "logos/bomb.png" to bomb)))
+ lists.index()
+ assertNull(lists.logo("bomb"))
+ assertFalse(File(dir, "logos/bomb.png").exists())
+ }
+
+ @Test fun somethingElseCalledPngIsRefused() {
+ assertFalse(Png.ok("<svg onload=alert(1)>".toByteArray()))
+ assertFalse(Png.ok(png(0, 10)))
+ assertFalse(Png.ok(png(-1, 10)))
+ assertTrue(Png.ok(png(278, 76)))
+ }
+
+ // A label with an RTL override
+
+ @Test fun controlAndBidiCharactersAreStrippedAndNamesCapped() {
+ val rlo = "\u202Egnp.exe"
+ assertEquals("gnp.exe", parseLabels("""{"schema": 1, "groups": [{"labels": {"com.acme.app": "$rlo"}}]}""")["com.acme.app"])
+ val l = parseLaunchers("""{"schema": 1, "launchers": [{"package": "com.acme.home", "name": "Acme\u2066\u0007 Home\u2028", "about": "${"a".repeat(1000)}"}]}""").single()
+ assertEquals("Acme Home", l.name)
+ assertEquals(300, l.about!!.length)
+ val s = parseStreaming("""{"schema": 1, "groups": [{"name": "\u200FG", "services": [{"name": "${"N".repeat(200)}", "packages": ["a.b"], "color": "#000000", "logo": "n"}]}]}""").single()
+ assertEquals(80, s.name.length)
+ assertEquals("G", s.group)
+ // A name that is nothing but controls is no name.
+ assertTrue(parseLaunchers("""{"schema": 1, "launchers": [{"package": "com.acme.home", "name": "\u202E\u202C"}]}""").isEmpty())
+ }
+
+ @Test fun coloursAreStrictHex() {
+ fun service(color: String) = parseStreaming("""{"schema": 1, "groups": [{"name": "G", "services": [{"name": "S", "packages": ["a.b"], "color": "$color", "logo": "s"}]}]}""")
+ assertEquals(1, service("#E50914").size)
+ for (bad in listOf("red", "#E5091", "#E50914FF", "#E50914;", "E50914", "#GGGGGG")) assertTrue(bad, service(bad).isEmpty())
+ }
+
+ @Test fun anIndexIdThatCouldSplitThePicksFileIsDropped() {
+ val sha = "0".repeat(64)
+ val idx = parseIndex("""{"schema": 1, "source": {"commit": "x\u202Eevil"}, "devices": [{"id": "a\tb\nc", "name": "X", "file": "devices/x.json", "sha256": "$sha"}]}""")!!
+ assertTrue(idx.devices.isEmpty())
+ assertNull(idx.commit)
+ }
+
+ // An http:// source
+
+ @Test fun anHttpSourceIsRefused() = runTest {
+ val lists = DeviceLists(tmp.newFolder(), served(emptyMap()))
+ assertEquals(SourceResult.NotHttps, lists.setSource("http://example.com/lists/"))
+ assertEquals(LISTS_BASE, lists.base)
+ assertTrue(asked.isEmpty())
+ }
+
+ @Test fun anHttpSourceStoredOnDiskIsNotUsed() {
+ val dir = tmp.newFolder()
+ File(dir, "source.txt").writeText("http://example.com/lists/")
+ assertEquals(LISTS_BASE, DeviceLists(dir).base)
+ }
+
+ @Test fun theDownloaderRefusesAnythingButHttps() = runTest {
+ for (url in listOf("http://example.com/index.json", "file:///etc/hosts", "jar:https://x/!/y", "ftp://x/y")) {
+ try {
+ download(url)
+ fail(url)
+ } catch (_: IllegalArgumentException) {
+ }
+ }
+ }
+
+ // A sha mismatch
+
+ @Test fun aListOrLogoWithTheWrongShaIsNeitherCachedNorUsed() = runTest {
+ val dir = tmp.newFolder()
+ val launchers = """{"schema": 1, "launchers": [{"package": "com.acme.home", "name": "Acme"}]}""".toByteArray()
+ val logo = png(10, 10)
+ val idx = index(lists = mapOf("launchers" to ("lists/launchers.json" to launchers)), logos = mapOf("acme" to ("logos/acme.png" to logo)))
+ val swapped = """{"schema": 1, "launchers": [{"package": "com.evil.home", "name": "Evil"}]}""".toByteArray()
+ val lists = DeviceLists(dir, served(mapOf("index.json" to idx, "lists/launchers.json" to swapped, "logos/acme.png" to png(11, 10))))
+ assertNull(lists.shared().launchers)
+ assertNull(lists.logo("acme"))
+ assertFalse(File(dir, "lists/launchers.json").exists())
+ assertFalse(File(dir, "logos/acme.png").exists())
+ }
+
+ @Test fun aCachedListThatNoLongerMatchesTheIndexIsNotRead() = runTest {
+ val dir = tmp.newFolder()
+ val launchers = """{"schema": 1, "launchers": [{"package": "com.acme.home", "name": "Acme"}]}""".toByteArray()
+ val lists = DeviceLists(dir, served(mapOf("index.json" to index(lists = mapOf("launchers" to ("lists/launchers.json" to launchers))), "lists/launchers.json" to launchers)))
+ assertEquals(launchers.decodeToString(), lists.shared().launchers)
+ File(dir, "lists/launchers.json").writeText("""{"schema": 1, "launchers": [{"package": "com.evil.home", "name": "Evil"}]}""")
+ assertNull(DeviceLists(dir) { throw IOException("offline") }.cachedShared().launchers)
+ }
+
+ // A launcher entry asking for accessibility
+
+ @Test fun aLauncherEntryCannotAskForAccessibility() = runTest {
+ val l = parseLaunchers("""{"schema": 1, "launchers": [{"package": "com.evil.home", "name": "Evil", "about": "x", "accessibility": true, "service": "com.evil.home/.Spy"}]}""").single()
+ assertFalse(l.accessibility)
+ assertFalse(actions.grant("com.evil.home/.Spy"))
+ assertEquals(emptyList<String>(), ran)
+ }
+}