From c3387e952bd377e0ac88a2d987a850bccd844abb Mon Sep 17 00:00:00 2001 From: Mudsir Wazir Date: Wed, 11 Nov 2026 14:02:46 +0500 Subject: [PATCH 1/4] security: validate force-stop package, honor Plugin API switch, real shell timeouts - Force-stop built "am force-stop " from rule text with no validation, so a rule (or an imported recipe) could inject shell commands. Names must now match a strict package-name pattern - The "Plugin API" switch only gated outgoing broadcasts; the exported PluginReceiver ignored it, so any installed app could fire triggers or run rules even when the user had turned it off. It now checks the switch - Elevated.drain read the process output to EOF before applying its timeout, so a hung su/sh blocked the caller forever; output is now read on a helper thread and the process is destroyed on timeout. hasSu() shares the same timeout and is cached for 30 s instead of spawning su on every call - RuleLogic gains pure helpers (package name, http(s) URL, host-only log) with tests Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01KBS1KApo9NfNebojzAwAS2 --- .../java/com/endroid/latch/engine/Elevated.kt | 63 +++++++++++++------ .../com/endroid/latch/engine/RuleLogic.kt | 23 +++++++ .../endroid/latch/receiver/LatchReceivers.kt | 6 +- .../java/com/endroid/latch/RuleLogicTest.kt | 28 +++++++++ 4 files changed, 97 insertions(+), 23 deletions(-) diff --git a/app/src/main/java/com/endroid/latch/engine/Elevated.kt b/app/src/main/java/com/endroid/latch/engine/Elevated.kt index 0bea5b2..9ef8b7d 100644 --- a/app/src/main/java/com/endroid/latch/engine/Elevated.kt +++ b/app/src/main/java/com/endroid/latch/engine/Elevated.kt @@ -3,8 +3,6 @@ package com.endroid.latch.engine import android.content.pm.PackageManager import android.util.Log import rikka.shizuku.Shizuku -import java.io.BufferedReader -import java.io.InputStreamReader import java.lang.reflect.Method import java.util.concurrent.TimeUnit import java.util.concurrent.atomic.AtomicReference @@ -13,13 +11,22 @@ object Elevated { private const val TAG = "LatchElevated" private val newProcessMethod = AtomicReference() - fun hasSu(): Boolean = try { - val p = Runtime.getRuntime().exec(arrayOf("su", "-c", "echo ok")) - val out = BufferedReader(InputStreamReader(p.inputStream)).readLine() - p.waitFor(3, TimeUnit.SECONDS) - out?.contains("ok") == true - } catch (_: Exception) { - false + @Volatile private var suCache: Pair? = null + private const val SU_CACHE_MS = 30_000L + + /** su probe with a hard timeout (a su that waits for a prompt used to hang the caller). */ + fun hasSu(): Boolean { + val now = System.currentTimeMillis() + suCache?.let { (ok, at) -> if (now - at < SU_CACHE_MS) return ok } + val ok = try { + val p = Runtime.getRuntime().exec(arrayOf("su", "-c", "echo ok")) + val r = drain(p, 3) + r.first == 0 && r.second.contains("ok") + } catch (_: Exception) { + false + } + suCache = ok to now + return ok } fun shizukuAvailable(): Boolean = try { @@ -91,20 +98,35 @@ object Elevated { } } + /** + * Reads output on a helper thread so [timeoutSec] is real: the old version read the + * stream to EOF first, so a hung process blocked the caller forever. + */ private fun drain(p: Process, timeoutSec: Long): Pair { - val out = StringBuilder() - try { - p.inputStream.bufferedReader().use { out.append(it.readText()) } - } catch (_: Exception) { } - val ok = try { + val out = StringBuffer() + val reader = Thread { + try { + p.inputStream.bufferedReader().use { r -> + val buf = CharArray(1024) + while (true) { + val n = r.read(buf) + if (n < 0) break + if (out.length < 4000) out.append(buf, 0, n) + } + } + } catch (_: Exception) { } + }.apply { isDaemon = true; start() } + val finished = try { p.waitFor(timeoutSec, TimeUnit.SECONDS) - } catch (_: Exception) { + } catch (_: InterruptedException) { false } - if (!ok) { - p.destroy() + if (!finished) { + p.destroyForcibly() + reader.join(500) return -1 to out.toString().take(4000) } + reader.join(1000) return p.exitValue() to out.toString().take(4000) } @@ -152,6 +174,9 @@ object Elevated { fun setMobileData(enable: Boolean, preferShizuku: Boolean, allowSu: Boolean) = runShell(if (enable) "svc data enable" else "svc data disable", preferShizuku, allowSu) - fun forceStop(packageName: String, preferShizuku: Boolean, allowSu: Boolean) = - runShell("am force-stop ${packageName.trim()}", preferShizuku, allowSu) + fun forceStop(packageName: String, preferShizuku: Boolean, allowSu: Boolean): Pair { + val pkg = packageName.trim() + if (!RuleLogic.isValidPackageName(pkg)) return -1 to "invalid package name" + return runShell("am force-stop $pkg", preferShizuku, allowSu) + } } diff --git a/app/src/main/java/com/endroid/latch/engine/RuleLogic.kt b/app/src/main/java/com/endroid/latch/engine/RuleLogic.kt index 268b720..9d5c190 100644 --- a/app/src/main/java/com/endroid/latch/engine/RuleLogic.kt +++ b/app/src/main/java/com/endroid/latch/engine/RuleLogic.kt @@ -4,6 +4,29 @@ package com.endroid.latch.engine * Pure rule matching helpers — no Android deps so JVM unit tests can cover them. */ object RuleLogic { + private val PACKAGE_NAME = Regex("^[A-Za-z][A-Za-z0-9_]*(\\.[A-Za-z0-9_]+)+$") + + /** + * True only for a well-formed Android package name. Anything else must never be + * placed on a shell command line (force-stop builds "am force-stop "). + */ + fun isValidPackageName(name: String?): Boolean = + name != null && name.length <= 255 && PACKAGE_NAME.matches(name) + + /** Only plain http(s) URLs may be requested by the HTTP GET action. */ + fun isHttpUrl(url: String): Boolean { + val u = url.trim() + return (u.startsWith("http://", ignoreCase = true) || u.startsWith("https://", ignoreCase = true)) && + u.length > 8 && u.none { it.isWhitespace() } + } + + /** Host only (no path/query) so secrets in a URL never reach the on-device log. */ + fun hostForLog(url: String): String = try { + java.net.URI(url.trim()).host ?: "?" + } catch (_: Exception) { + "?" + } + fun batteryBelow(percent: Int, threshold: Int): Boolean = percent <= threshold fun batteryAbove(percent: Int, threshold: Int): Boolean = percent >= threshold diff --git a/app/src/main/java/com/endroid/latch/receiver/LatchReceivers.kt b/app/src/main/java/com/endroid/latch/receiver/LatchReceivers.kt index 0bccdac..df872bb 100644 --- a/app/src/main/java/com/endroid/latch/receiver/LatchReceivers.kt +++ b/app/src/main/java/com/endroid/latch/receiver/LatchReceivers.kt @@ -172,6 +172,8 @@ class PluginReceiver : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent?) { if (intent == null) return val app = context.applicationContext + // The Settings switch "Plugin API" used to only gate outgoing broadcasts. + if (!com.endroid.latch.data.SettingsStore(app).pluginApiEnabled) return when (intent.action) { ACTION_FIRE_TRIGGER -> { val custom = intent.getStringExtra(EXTRA_TRIGGER) @@ -183,10 +185,6 @@ class PluginReceiver : BroadcastReceiver() { RuleEngine.run(app, it) } } - else -> { - // Treat any matching action string as custom broadcast trigger param - intent.action?.let { RuleEngine.onCustomBroadcast(app, it) } - } } } diff --git a/app/src/test/java/com/endroid/latch/RuleLogicTest.kt b/app/src/test/java/com/endroid/latch/RuleLogicTest.kt index 2753f13..fa6ad37 100644 --- a/app/src/test/java/com/endroid/latch/RuleLogicTest.kt +++ b/app/src/test/java/com/endroid/latch/RuleLogicTest.kt @@ -108,4 +108,32 @@ class RuleLogicTest { assertFalse(RuleLogic.cooldownOk(1, 1000L, 1999L)) assertTrue(RuleLogic.cooldownOk(1, 1000L, 2000L)) } + + @Test fun packageNameAcceptsRealNames() { + assertTrue(RuleLogic.isValidPackageName("com.android.chrome")) + assertTrue(RuleLogic.isValidPackageName("org.example.app_2")) + } + + @Test fun packageNameRejectsShellMetacharacters() { + val bad = listOf( + null, "", "chrome", "com.a;reboot", "com.a && id", "com.a|id", "com.a\nid", + "\$(id).app", "com.a`id`", "com.a b", "com.a>x", "-f.com.a", ".com.a", "com.a.", + "com..a", "1com.a", "a".repeat(300) + ".b", + ) + for (b in bad) assertFalse("accepted: $b", RuleLogic.isValidPackageName(b)) + } + + @Test fun httpUrlOnlyHttpAndHttps() { + assertTrue(RuleLogic.isHttpUrl("https://example.com/hook?x=1")) + assertTrue(RuleLogic.isHttpUrl("http://192.168.1.5/on")) + assertFalse(RuleLogic.isHttpUrl("httpfoo://x")) + assertFalse(RuleLogic.isHttpUrl("file:///etc/passwd")) + assertFalse(RuleLogic.isHttpUrl("https://a b")) + assertFalse(RuleLogic.isHttpUrl("https://")) + } + + @Test fun hostForLogDropsPathAndQuery() { + assertEquals("example.com", RuleLogic.hostForLog("https://example.com/hook?token=SECRET")) + assertEquals("?", RuleLogic.hostForLog("not a url")) + } } From cb07a8a7207279dd5e9070c6173d9d361eebc5a0 Mon Sep 17 00:00:00 2001 From: Mudsir Wazir Date: Wed, 11 Nov 2026 14:03:54 +0500 Subject: [PATCH 2/4] fix: HTTP GET action accepts http(s) only, logs host only, always disconnects - startsWith("http") also accepted "httpfoo://"; only http:// and https:// are used now - The run log stored the whole URL, including query-string tokens; it stores the host - The connection is now closed in a finally block even when the request throws - Rejected URLs are logged instead of silently ignored Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01KBS1KApo9NfNebojzAwAS2 --- .../java/com/endroid/latch/engine/RuleEngine.kt | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/app/src/main/java/com/endroid/latch/engine/RuleEngine.kt b/app/src/main/java/com/endroid/latch/engine/RuleEngine.kt index 70d5df1..5be39fc 100644 --- a/app/src/main/java/com/endroid/latch/engine/RuleEngine.kt +++ b/app/src/main/java/com/endroid/latch/engine/RuleEngine.kt @@ -471,20 +471,26 @@ object RuleEngine { } ActionType.HTTP_GET -> { val url = action.param.trim().ifBlank { action.text.trim() } - if (url.startsWith("http")) { + if (RuleLogic.isHttpUrl(url)) { + val app = context.applicationContext thread { + var c: java.net.HttpURLConnection? = null try { - val c = java.net.URL(url).openConnection() as java.net.HttpURLConnection + c = java.net.URL(url).openConnection() as java.net.HttpURLConnection c.connectTimeout = 8000 c.readTimeout = 8000 c.requestMethod = "GET" val code = c.responseCode - SettingsStore(context).appendLog("HTTP $code $url") - c.disconnect() + // Host only: query strings often carry tokens. + SettingsStore(app).appendLog("HTTP $code ${RuleLogic.hostForLog(url)}") } catch (e: Exception) { - SettingsStore(context).appendLog("HTTP ERR ${e.message}") + SettingsStore(app).appendLog("HTTP ERR ${RuleLogic.hostForLog(url)}: ${e.javaClass.simpleName}") + } finally { + c?.disconnect() } } + } else { + SettingsStore(context).appendLog("HTTP skipped: not an http(s) URL") } } } From 12a58d846d0525ea145084165944ec236b973aaf Mon Sep 17 00:00:00 2001 From: Mudsir Wazir Date: Wed, 11 Nov 2026 14:05:23 +0500 Subject: [PATCH 3/4] ci: Gradle cache, timeout, concurrency, signature check, fork-friendly signing - PRs build only the stable release; branch and tag builds build everything - Gradle cache (read-only on PRs), 40 min timeout, newer PR pushes cancel older runs - Tag releases on wized2/Latch fail without signing secrets; forks fall back to debug signing - apksigner verifies the APK whenever a release key is present - Test reports are uploaded when the build fails Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01KBS1KApo9NfNebojzAwAS2 --- .github/workflows/build.yml | 46 +++++++++++++++++++++++++++++++++---- 1 file changed, 42 insertions(+), 4 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index fdf8f25..37f68aa 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -20,9 +20,18 @@ on: permissions: contents: write +# A newer push to the same PR/branch cancels the older run; tag builds are never cancelled. +concurrency: + group: build-${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +env: + IS_RELEASE: ${{ github.event_name == 'push' && startsWith(github.ref, 'refs/tags/v') }} + jobs: build: runs-on: ubuntu-latest + timeout-minutes: 40 steps: - uses: actions/checkout@v4 @@ -31,6 +40,10 @@ jobs: distribution: temurin java-version: "17" + - uses: gradle/actions/setup-gradle@v4 + with: + cache-read-only: ${{ github.event_name == 'pull_request' }} + - name: Setup Android SDK path run: | echo "ANDROID_HOME=${ANDROID_HOME:-$ANDROID_SDK_ROOT}" >> "$GITHUB_ENV" @@ -55,6 +68,11 @@ jobs: else echo "present=false" >> "$GITHUB_OUTPUT" echo "Secrets missing — debug signing fallback." + # Forks and contributors build debug-signed. Only the official repo must sign releases. + if [ "$IS_RELEASE" = "true" ] && [ "$GITHUB_REPOSITORY" = "wized2/Latch" ]; then + echo "::error::Release tag without signing secrets; refusing to publish a debug-signed APK." + exit 1 + fi fi - name: Unit tests @@ -72,9 +90,29 @@ jobs: if [ "${{ steps.keystore.outputs.present }}" = "true" ]; then export RELEASE_STORE_FILE="$GITHUB_WORKSPACE/release.jks" fi - ./gradlew assembleStableDebug assembleBetaDebug assembleStableRelease assembleBetaRelease --stacktrace + if [ "${{ github.event_name }}" = "pull_request" ]; then + ./gradlew assembleStableRelease --stacktrace + else + ./gradlew assembleStableDebug assembleBetaDebug assembleStableRelease assembleBetaRelease --stacktrace + fi ls -la app/build/outputs/apk/stable/release/ app/build/outputs/apk/beta/release/ || true + - name: Verify APK signature + if: steps.keystore.outputs.present == 'true' + run: | + APKSIGNER=$(ls "$ANDROID_HOME"/build-tools/*/apksigner | sort -V | tail -1) + for f in app/build/outputs/apk/stable/release/*.apk; do + "$APKSIGNER" verify --verbose "$f" + done + + - name: Upload test reports on failure + if: failure() + uses: actions/upload-artifact@v4 + with: + name: test-reports + path: app/build/reports/tests + if-no-files-found: ignore + - name: Upload artifact uses: actions/upload-artifact@v4 with: @@ -82,7 +120,7 @@ jobs: path: app/build/outputs/apk/stable/release/*.apk - name: Version - if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/v') + if: env.IS_RELEASE == 'true' id: ver run: | VN=$(grep -E 'versionName\s*=' app/build.gradle.kts | head -1 | sed -E 's/.*"([^"]+)".*/\1/') @@ -90,13 +128,13 @@ jobs: echo "tag=v$VN" >> "$GITHUB_OUTPUT" - name: Prepare assets - if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/v') + if: env.IS_RELEASE == 'true' run: | mkdir -p release-assets cp app/build/outputs/apk/stable/release/*.apk release-assets/Latch-release.apk - name: GitHub Release - if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/v') + if: env.IS_RELEASE == 'true' uses: softprops/action-gh-release@v2 with: tag_name: ${{ steps.ver.outputs.tag }} From 717842a3df248fbfb3bddc48999a970bf03d0c64 Mon Sep 17 00:00:00 2001 From: Mudsir Wazir Date: Wed, 11 Nov 2026 14:06:08 +0500 Subject: [PATCH 4/4] docs: privacy section matches manifest, Plugin API switch, threat model; bump to 0.8.0 Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01KBS1KApo9NfNebojzAwAS2 --- CHANGELOG.md | 15 +++++++++++++++ README.md | 4 +++- RELEASE_NOTES.md | 16 ++++++++++------ SECURITY.md | 8 ++++++++ app/build.gradle.kts | 4 ++-- 5 files changed, 38 insertions(+), 9 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 10d9f1e..97296fc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,18 @@ +## 0.8.0 + +### Security +- Package names are validated before `am force-stop`, so a rule can no longer inject shell commands +- The Plugin API switch in Settings is now honored by the receiver +- HTTP GET action accepts only http(s), logs host only, always closes the connection + +### Reliability +- Shell and `su` calls have real timeouts (a hung process no longer blocks the rule thread) +- `su` availability is cached for 30 s + +### Build +- CI: Gradle cache, timeout, concurrency, APK signature check; PRs build stable only +- Unit tests for package-name and URL validation + ## 0.7.0 - Accessibility for APP_OPENED; UsageStats fallback; stronger sticky monitor notes diff --git a/README.md b/README.md index 169e201..e4d7e9f 100644 --- a/README.md +++ b/README.md @@ -59,7 +59,7 @@ Optional **Shizuku** (preferred) or root `su` for shell / `svc` style actions. E ## Privacy -No `INTERNET` permission. No analytics. Rules stay on device unless you export them. +No analytics, no accounts, no telemetry. Rules stay on device unless you export them. The `INTERNET` permission is used only by the optional **HTTP GET** action, which accepts `http://` and `https://` URLs and logs the host only (never the query string). ## Plugin API @@ -68,6 +68,8 @@ com.endroid.latch.api.FIRE_TRIGGER extra trigger= com.endroid.latch.api.RUN_RULE extra rule_id= ``` +Any installed app can send these broadcasts, so they can be switched off in Settings (**Plugin API**). When off, Latch ignores them. Turn it off if you have rules with shell actions and do not use plugins. + ## Stable vs beta | Channel | Branch | Application id | diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md index 9b3105f..f3729ce 100644 --- a/RELEASE_NOTES.md +++ b/RELEASE_NOTES.md @@ -1,9 +1,13 @@ -# Latch 0.6.3 +# Latch 0.8.0 -## UI -- Home: search rules by name / trigger; enabled rules sort first -- Settings: seed colors as wrapping FilterChips (no overflow on small phones) +## Security +- Shell-injection fix for the force-stop action (package names are validated) +- Plugin API switch is now enforced +- HTTP GET action: http(s) only, host-only logging + +## Reliability +- Shell / su timeouts that actually fire +- Cached su probe ## Docs -- README badges + website/download links -- Issue template + funding metadata +- README privacy section now matches the manifest (INTERNET is used only by HTTP GET) diff --git a/SECURITY.md b/SECURITY.md index a12fb67..966b4cd 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -8,3 +8,11 @@ Security fixes target the latest release on `main`. Email **acartoon766@gmail.com** or use GitHub private vulnerability reporting. Do not open public issues for exploitable vulnerabilities. + +## Threat model + +- Latch runs entirely on the device. There are no accounts and no analytics. +- Shell actions (Shizuku or root) run only what the user typed into a rule. Package names used in force-stop are validated against a strict pattern. +- Other apps can send `FIRE_TRIGGER` / `RUN_RULE` broadcasts. The **Plugin API** switch in Settings makes Latch ignore them. +- The `INTERNET` permission exists only for the optional HTTP GET action (http/https, host-only logs). +- Release APKs are signed in CI; the signature is verified before publishing. diff --git a/app/build.gradle.kts b/app/build.gradle.kts index 30b6915..4c347e6 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -12,8 +12,8 @@ android { applicationId = "com.endroid.latch" minSdk = 26 targetSdk = 35 - versionCode = 12 - versionName = "0.7.0" + versionCode = 13 + versionName = "0.8.0" resourceConfigurations += listOf("en", "es", "de") buildConfigField("String", "VERSION_NAME", "\"${defaultConfig.versionName}\"") }