From ffb83e7a94044d9983b37b18c5829b14bc6d315b Mon Sep 17 00:00:00 2001 From: 4di-hello <4di-hello@users.noreply.github.com> Date: Mon, 30 Nov 2026 20:14:23 +0100 Subject: [PATCH 1/2] Plugins: load only official LeanBitLab plugins, checked before anything is extracted Plugins run inside the keyboard and see everything that is typed, but any APK a user picks was loaded. Now the AI, translation, OCR, handwriting and CJK plugins are checked before extraction: signed with a known LeanBitLab key (or the keyboard's own key), or one of the known unsigned handwriting releases 1.0.0-1.0.6. The voice plugin app is only bound when it has a known key. File names from the plugin archive are used without their path, so an entry like "../x.so" can't leave the plugin folder. Co-Authored-By: Claude Opus 5.5 --- .../keyboard/latin/ai/OfflineAiLoader.kt | 2 + .../keyboard/latin/cjk/CjkPluginLoader.kt | 2 + .../latin/handwriting/HandwritingLoader.kt | 6 +- .../keyboard/latin/ocr/OcrPluginLoader.kt | 4 +- .../latin/translation/TranslationLoader.kt | 6 +- .../keyboard/latin/utils/PluginTrust.kt | 193 ++++++++++++++++++ .../latin/voice/VoicePluginManager.kt | 2 + .../keyboard/latin/utils/PluginTrustTest.kt | 25 +++ 8 files changed, 237 insertions(+), 3 deletions(-) create mode 100644 app/src/main/java/helium314/keyboard/latin/utils/PluginTrust.kt create mode 100644 app/src/test/java/helium314/keyboard/latin/utils/PluginTrustTest.kt diff --git a/app/src/main/java/helium314/keyboard/latin/ai/OfflineAiLoader.kt b/app/src/main/java/helium314/keyboard/latin/ai/OfflineAiLoader.kt index a71b73b81d..26dc6f03dd 100644 --- a/app/src/main/java/helium314/keyboard/latin/ai/OfflineAiLoader.kt +++ b/app/src/main/java/helium314/keyboard/latin/ai/OfflineAiLoader.kt @@ -125,6 +125,8 @@ object OfflineAiLoader { return try { apkFile.setReadOnly() val nativeLibDir = getNativeLibDir(context, apkFile) + // check before anything of the plugin is extracted or loaded + helium314.keyboard.latin.utils.PluginTrust.requireTrusted(context, apkFile) extractNativeLibs(apkFile, nativeLibDir) val classLoader = PluginClassLoader( apkFile.absolutePath, diff --git a/app/src/main/java/helium314/keyboard/latin/cjk/CjkPluginLoader.kt b/app/src/main/java/helium314/keyboard/latin/cjk/CjkPluginLoader.kt index d2be2b549f..e2e3466844 100644 --- a/app/src/main/java/helium314/keyboard/latin/cjk/CjkPluginLoader.kt +++ b/app/src/main/java/helium314/keyboard/latin/cjk/CjkPluginLoader.kt @@ -207,6 +207,8 @@ object CjkPluginLoader { val userDir = File(context.filesDir, "cjk/user").apply { mkdirs() } val nativeLibDir = getNativeLibDir(context, apkFile) + // check before anything of the plugin is extracted or loaded + helium314.keyboard.latin.utils.PluginTrust.requireTrusted(context, apkFile) extractPluginAssetsAndLibs(apkFile, nativeLibDir, sharedDir) val libDirPath = nativeLibDir.absolutePath diff --git a/app/src/main/java/helium314/keyboard/latin/handwriting/HandwritingLoader.kt b/app/src/main/java/helium314/keyboard/latin/handwriting/HandwritingLoader.kt index ca2514d22f..7014bb9d43 100644 --- a/app/src/main/java/helium314/keyboard/latin/handwriting/HandwritingLoader.kt +++ b/app/src/main/java/helium314/keyboard/latin/handwriting/HandwritingLoader.kt @@ -276,6 +276,10 @@ object HandwritingLoader { try { ensureWorkManagerInitialized(context) + // check before anything of the plugin is extracted or loaded + helium314.keyboard.latin.utils.PluginTrust.requireTrusted(context, apkFile) + // check before anything of the plugin is extracted or loaded + helium314.keyboard.latin.utils.PluginTrust.requireTrusted(context, apkFile) val classLoader = getOrCreateClassLoader(context, apkFile) val clazz = classLoader.loadClass(PLUGIN_CLASS_NAME) val recognizer = clazz.getDeclaredConstructor().newInstance() as HandwritingRecognizer @@ -307,7 +311,7 @@ object HandwritingLoader { val prefix = "lib/$targetAbi/" for (entry in zip.entries().asSequence()) { if (entry.name.startsWith(prefix) && entry.name.endsWith(".so")) { - val fileName = entry.name.substring(prefix.length) + val fileName = entry.name.substringAfterLast('/') // no path from the zip, e.g. "../" val outFile = File(outputDir, fileName) if (!outFile.exists() || outFile.length() != entry.size) { zip.getInputStream(entry).use { input -> diff --git a/app/src/main/java/helium314/keyboard/latin/ocr/OcrPluginLoader.kt b/app/src/main/java/helium314/keyboard/latin/ocr/OcrPluginLoader.kt index 02673d07a8..027070739a 100644 --- a/app/src/main/java/helium314/keyboard/latin/ocr/OcrPluginLoader.kt +++ b/app/src/main/java/helium314/keyboard/latin/ocr/OcrPluginLoader.kt @@ -148,7 +148,7 @@ object OcrPluginLoader { val prefix = "lib/$targetAbi/" for (entry in zip.entries().asSequence()) { if (entry.name.startsWith(prefix) && entry.name.endsWith(".so")) { - val fileName = entry.name.substring(prefix.length) + val fileName = entry.name.substringAfterLast('/') // no path from the zip, e.g. "../" val outFile = File(outputDir, fileName) if (!outFile.exists() || outFile.length() != entry.size) { zip.getInputStream(entry).use { input -> @@ -207,6 +207,8 @@ object OcrPluginLoader { ensureWorkManagerInitialized(context) val apkLastModified = apkFile.lastModified() val nativeLibDir = getNativeLibDir(context, apkFile) + // check before anything of the plugin is extracted or loaded + helium314.keyboard.latin.utils.PluginTrust.requireTrusted(context, apkFile) extractNativeLibs(apkFile, nativeLibDir) val cachedLoader = cachedClassLoader diff --git a/app/src/main/java/helium314/keyboard/latin/translation/TranslationLoader.kt b/app/src/main/java/helium314/keyboard/latin/translation/TranslationLoader.kt index 01234d2632..986e470fe3 100644 --- a/app/src/main/java/helium314/keyboard/latin/translation/TranslationLoader.kt +++ b/app/src/main/java/helium314/keyboard/latin/translation/TranslationLoader.kt @@ -124,6 +124,10 @@ object TranslationLoader { TranslationModelImporter.migrateLegacyModels(context) ensureWorkManagerInitialized(context) val nativeLibDir = getNativeLibDir(context, apkFile) + // check before anything of the plugin is extracted or loaded + helium314.keyboard.latin.utils.PluginTrust.requireTrusted(context, apkFile) + // check before anything of the plugin is extracted or loaded + helium314.keyboard.latin.utils.PluginTrust.requireTrusted(context, apkFile) extractNativeLibs(apkFile, nativeLibDir) val cachedLoader = cachedClassLoader val classLoader = if (cachedLoader != null && cachedApkModified == apkFile.lastModified()) { @@ -179,7 +183,7 @@ object TranslationLoader { val prefix = "lib/$targetAbi/" for (entry in zip.entries().asSequence()) { if (entry.name.startsWith(prefix) && entry.name.endsWith(".so")) { - val fileName = entry.name.substring(prefix.length) + val fileName = entry.name.substringAfterLast('/') // no path from the zip, e.g. "../" val outFile = File(outputDir, fileName) if (!outFile.exists() || outFile.length() != entry.size) { zip.getInputStream(entry).use { input -> diff --git a/app/src/main/java/helium314/keyboard/latin/utils/PluginTrust.kt b/app/src/main/java/helium314/keyboard/latin/utils/PluginTrust.kt new file mode 100644 index 0000000000..708937ca7f --- /dev/null +++ b/app/src/main/java/helium314/keyboard/latin/utils/PluginTrust.kt @@ -0,0 +1,193 @@ +// SPDX-License-Identifier: GPL-3.0-only +package helium314.keyboard.latin.utils + +import android.content.Context +import android.content.pm.PackageManager +import android.os.Build +import android.os.Handler +import android.os.Looper +import android.widget.Toast +import java.io.File +import java.security.MessageDigest + +/** + * Plugins run inside the keyboard and see everything that is typed. Only official LeanType plugins + * are loaded: signed with a known LeanBitLab key, or (the handwriting plugin, whose releases are not + * signed) one of the known release files. The voice plugin is an app of its own that gets the audio + * and returns text: it is only used if it is signed with the known key, see [isTrustedPackage]. + * Plugins signed with the same key as the keyboard itself are trusted as well (builds that sign + * keyboard and plugins with one key, e.g. for development). + */ +object PluginTrust { + private const val TAG = "PluginTrust" + + /** SHA-256 of the signing certificates of the LeanBitLab plugin releases */ + private val TRUSTED_SIGNERS = setOf( + // CJK, GIF, translation + "01CFC72120C539EC4CC846CD70D25F83E3FC694D8BDCD2211454A8C993C4F5A3", + // OCR, offline AI + "963156A08CA5DD16325F8F49FBD906F5AE16A51B2D0D08C6D68913C392105B4D", + // voice + "C537F49420355FF10423355BB7345CAF83CA844D6416E364C53CA3DB4494F119", + ) + + /** SHA-256 of the unsigned handwriting plugin releases v1.0.0 to v1.0.6 */ + private val TRUSTED_UNSIGNED_FILES = setOf( + "7b666ed6f020561182529e30ce106b34ea977cc355bb54d66c9a4f8306f230ed", // 1.0.0 + "264d2c1242cf0e9ae43d867370d0b01cb95ade0471b4ef8ec619bca2b6568338", // 1.0.1 + "3565cb3d7e53180d25f8ad320efa43f2ce5fc29d891ee3fa3d4c2b2224a42edb", // 1.0.2 + "5f7b96a7bf2dd7beb9cb4eae120819e3c73273cf326b500123fd492efb8ef807", // 1.0.3 + "f626910eaea998788863a3462d657cfaeedd7e38e0f2672823371a01ea733792", // 1.0.4 + "00e65a445922d11d5014a91e032f13cbdae2c538575140f4883627361bfe81a6", // 1.0.5 + "75fd358279492ee82e07587ec73708c99a7f17f1402cb8a2c45a1df3c6abc1cc", // 1.0.6 arm64-v8a + "ec6bc10d102ea77c90e5fa4c60dc773877ecaaadd18711e931407b1bb50709cb", // 1.0.6 armeabi-v7a + "bb209cce3a870b14249d6bb6395136c961499127b7f64d57f8a48a5b804fac76", // 1.0.6 x86 + "0a4d7ee666c902d5bbd9a86b09eae7375b2af952c3237aa94bf7c27ecb6a111a", // 1.0.6 x86_64 + ) + + /** SHA-256 of the certificates the keyboard itself is signed with, see [trustedSigners] */ + @Volatile private var ownSigners: Set? = null + + /** The LeanBitLab keys and the key of the keyboard itself */ + private fun trustedSigners(context: Context): Set { + val own = ownSigners ?: try { + packageSigners(context.packageManager, context.packageName).toSet() + } catch (e: Exception) { + Log.w(TAG, "could not read the own signature", e) + emptySet() + }.also { ownSigners = it } + return TRUSTED_SIGNERS + own + } + + /** files already checked in this process, by path, size and modification time */ + private val checked = HashSet() + + /** Throws a [SecurityException] if [apk] is not an official plugin; call before loading any code of it */ + fun requireTrusted(context: Context, apk: File) { + val id = "${apk.absolutePath}:${apk.length()}:${apk.lastModified()}" + synchronized(checked) { if (id in checked) return } + val reason = untrustedReason(context, apk) + if (reason == null) { + synchronized(checked) { checked.add(id) } + return + } + Log.e(TAG, "not loading ${apk.name}: $reason") + val appContext = context.applicationContext ?: context + Handler(Looper.getMainLooper()).post { + Toast.makeText(appContext, "Plugin not loaded: $reason", Toast.LENGTH_LONG).show() + } + throw SecurityException("untrusted plugin ${apk.name}: $reason") + } + + /** null if [apk] is an official plugin, otherwise why not */ + fun untrustedReason(context: Context, apk: File): String? { + val signers = try { + signerDigests(context, apk) + } catch (e: Exception) { + Log.w(TAG, "could not read the signature of ${apk.name}", e) + emptySet() + } + if (signers.isNotEmpty()) { + val trusted = trustedSigners(context) + if (signers.all { it in trusted }) return null + return "unknown signing key ${signers.first().take(16)}…" + } + val fileHash = try { sha256(apk) } catch (e: Exception) { return "file can't be read" } + if (fileHash in TRUSTED_UNSIGNED_FILES) return null + return "not signed and not a known release (${fileHash.take(16)}…)" + } + + /** installed plugin apps already checked, by package and update time */ + private val checkedPackages = HashSet() + + /** + * Whether the installed app [packageName] (a plugin that runs as its own app, like the voice plugin) + * is signed with a known LeanBitLab key. Shows a message and returns false otherwise. + */ + /** + * Whether [packageName] is installed but not signed with a trusted key. A package that is not installed + * is not refused here: Android cannot bind to it anyway (and tests use such fake components). + */ + fun isInstalledButUntrusted(context: Context, packageName: String): Boolean { + if (packageName == context.packageName) return false + try { + @Suppress("DEPRECATION") + context.packageManager.getPackageInfo(packageName, 0) + } catch (e: PackageManager.NameNotFoundException) { + return false + } + return !isTrustedPackage(context, packageName) + } + + fun isTrustedPackage(context: Context, packageName: String): Boolean { + val pm = context.packageManager + val updated = try { + @Suppress("DEPRECATION") + pm.getPackageInfo(packageName, 0).lastUpdateTime + } catch (e: PackageManager.NameNotFoundException) { + return false + } + val id = "$packageName:$updated" + synchronized(checkedPackages) { if (id in checkedPackages) return true } + val signers = try { + packageSigners(pm, packageName) + } catch (e: Exception) { + emptyList() + } + val trusted = trustedSigners(context) + if (signers.isNotEmpty() && signers.all { it in trusted }) { + synchronized(checkedPackages) { checkedPackages.add(id) } + return true + } + val reason = if (signers.isEmpty()) "signature can't be read" else "unknown signing key ${signers.first().take(16)}…" + Log.e(TAG, "not using $packageName: $reason") + val appContext = context.applicationContext ?: context + Handler(Looper.getMainLooper()).post { + Toast.makeText(appContext, "Plugin not used: $reason", Toast.LENGTH_LONG).show() + } + return false + } + + /** SHA-256 (upper case) of the certificates the installed app [packageName] is signed with */ + private fun packageSigners(pm: PackageManager, packageName: String): List { + val certs = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { + val signing = pm.getPackageInfo(packageName, PackageManager.GET_SIGNING_CERTIFICATES).signingInfo + if (signing == null) emptyList() + else (if (signing.hasMultipleSigners()) signing.apkContentsSigners else signing.signingCertificateHistory)?.toList() ?: emptyList() + } else { + @Suppress("DEPRECATION") + pm.getPackageInfo(packageName, PackageManager.GET_SIGNATURES).signatures?.toList() ?: emptyList() + } + return certs.map { hex(MessageDigest.getInstance("SHA-256").digest(it.toByteArray())).uppercase() } + } + + /** SHA-256 of the certificates that signed [apk], verified by Android; empty if it is not (validly) signed */ + private fun signerDigests(context: Context, apk: File): Set { + val pm = context.packageManager + val certs = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { + @Suppress("WrongConstant") + val info = pm.getPackageArchiveInfo(apk.absolutePath, PackageManager.GET_SIGNING_CERTIFICATES) + val signing = info?.signingInfo ?: return emptySet() + if (signing.hasMultipleSigners()) signing.apkContentsSigners else signing.signingCertificateHistory + } else { + @Suppress("DEPRECATION") + pm.getPackageArchiveInfo(apk.absolutePath, PackageManager.GET_SIGNATURES)?.signatures + } ?: return emptySet() + return certs.map { hex(MessageDigest.getInstance("SHA-256").digest(it.toByteArray())).uppercase() }.toSet() + } + + private fun sha256(file: File): String { + val digest = MessageDigest.getInstance("SHA-256") + file.inputStream().use { input -> + val buffer = ByteArray(64 * 1024) + while (true) { + val read = input.read(buffer) + if (read < 0) break + digest.update(buffer, 0, read) + } + } + return hex(digest.digest()) + } + + private fun hex(bytes: ByteArray) = bytes.joinToString("") { "%02x".format(it) } +} diff --git a/app/src/main/java/helium314/keyboard/latin/voice/VoicePluginManager.kt b/app/src/main/java/helium314/keyboard/latin/voice/VoicePluginManager.kt index 17573f94a5..964572904b 100644 --- a/app/src/main/java/helium314/keyboard/latin/voice/VoicePluginManager.kt +++ b/app/src/main/java/helium314/keyboard/latin/voice/VoicePluginManager.kt @@ -140,6 +140,8 @@ class VoicePluginManager(private val context: Context) : IBinder.DeathRecipient val component = resolveServiceComponent() val intent = Intent().apply { this.component = component } + // the plugin hears everything that is dictated: only the official one is used + if (helium314.keyboard.latin.utils.PluginTrust.isInstalledButUntrusted(context, component.packageName)) return false Log.i(TAG, "Binding to voice plugin service: $component") isConnecting = true diff --git a/app/src/test/java/helium314/keyboard/latin/utils/PluginTrustTest.kt b/app/src/test/java/helium314/keyboard/latin/utils/PluginTrustTest.kt new file mode 100644 index 0000000000..4b25f72d1f --- /dev/null +++ b/app/src/test/java/helium314/keyboard/latin/utils/PluginTrustTest.kt @@ -0,0 +1,25 @@ +// SPDX-License-Identifier: GPL-3.0-only +package helium314.keyboard.latin.utils + +import org.junit.Assert.assertFalse +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment + +@RunWith(RobolectricTestRunner::class) +class PluginTrustTest { + private val context get() = RuntimeEnvironment.getApplication() + + @Test + fun packagesThatAreNotInstalledAreNotTrustedButNotRefusedEither() { + // Android cannot bind to them, so there is nothing to refuse + assertFalse(PluginTrust.isTrustedPackage(context, "not.installed.plugin")) + assertFalse(PluginTrust.isInstalledButUntrusted(context, "not.installed.plugin")) + } + + @Test + fun ownPackageIsNeverRefused() { + assertFalse(PluginTrust.isInstalledButUntrusted(context, context.packageName)) + } +} From e92fb52fadabd83c393431b9fd326e5358455c99 Mon Sep 17 00:00:00 2001 From: 4di-hello <4di-hello@users.noreply.github.com> Date: Mon, 30 Nov 2026 20:25:02 +0100 Subject: [PATCH 2/2] Plugin check: also on import of translation and handwriting, Android 9, key rotation, message once - Translation import and the handwriting class loader (every load and import) are checked as well - Signatures are read with GET_SIGNATURES and GET_SIGNING_CERTIFICATES (Android 9 fills signingInfo only with the first in some versions) - One signer: a trusted key anywhere in its history is enough (key rotation); several signers: all - A refused file or app is not checked again in this process and its message is shown once - Messages as string resources Co-Authored-By: Claude Opus 5.5 --- .../latin/handwriting/HandwritingLoader.kt | 6 +- .../latin/translation/TranslationLoader.kt | 3 +- .../keyboard/latin/utils/PluginTrust.kt | 113 ++++++++++-------- app/src/main/res/values-de/strings.xml | 2 + app/src/main/res/values/strings.xml | 2 + 5 files changed, 73 insertions(+), 53 deletions(-) diff --git a/app/src/main/java/helium314/keyboard/latin/handwriting/HandwritingLoader.kt b/app/src/main/java/helium314/keyboard/latin/handwriting/HandwritingLoader.kt index 7014bb9d43..a9ba8e2dda 100644 --- a/app/src/main/java/helium314/keyboard/latin/handwriting/HandwritingLoader.kt +++ b/app/src/main/java/helium314/keyboard/latin/handwriting/HandwritingLoader.kt @@ -241,6 +241,8 @@ object HandwritingLoader { val apkModified = apkFile.lastModified() cachedClassLoader?.let { if (cachedApkModified == apkModified) return it } val nativeLibDir = getNativeLibDir(context, apkFile) + // check before anything of the plugin is extracted or loaded (every load and import comes here) + helium314.keyboard.latin.utils.PluginTrust.requireTrusted(context, apkFile) extractNativeLibs(apkFile, nativeLibDir) val nativeLoaderDex = getNativeLoaderDex(context) val dexPaths = "${apkFile.absolutePath}${File.pathSeparator}${nativeLoaderDex.absolutePath}" @@ -276,10 +278,6 @@ object HandwritingLoader { try { ensureWorkManagerInitialized(context) - // check before anything of the plugin is extracted or loaded - helium314.keyboard.latin.utils.PluginTrust.requireTrusted(context, apkFile) - // check before anything of the plugin is extracted or loaded - helium314.keyboard.latin.utils.PluginTrust.requireTrusted(context, apkFile) val classLoader = getOrCreateClassLoader(context, apkFile) val clazz = classLoader.loadClass(PLUGIN_CLASS_NAME) val recognizer = clazz.getDeclaredConstructor().newInstance() as HandwritingRecognizer diff --git a/app/src/main/java/helium314/keyboard/latin/translation/TranslationLoader.kt b/app/src/main/java/helium314/keyboard/latin/translation/TranslationLoader.kt index 986e470fe3..8237af2460 100644 --- a/app/src/main/java/helium314/keyboard/latin/translation/TranslationLoader.kt +++ b/app/src/main/java/helium314/keyboard/latin/translation/TranslationLoader.kt @@ -126,8 +126,6 @@ object TranslationLoader { val nativeLibDir = getNativeLibDir(context, apkFile) // check before anything of the plugin is extracted or loaded helium314.keyboard.latin.utils.PluginTrust.requireTrusted(context, apkFile) - // check before anything of the plugin is extracted or loaded - helium314.keyboard.latin.utils.PluginTrust.requireTrusted(context, apkFile) extractNativeLibs(apkFile, nativeLibDir) val cachedLoader = cachedClassLoader val classLoader = if (cachedLoader != null && cachedApkModified == apkFile.lastModified()) { @@ -239,6 +237,7 @@ object TranslationLoader { // Verify the plugin loads successfully ensureWorkManagerInitialized(context) val nativeLibDir = getNativeLibDir(context, apkFile) + helium314.keyboard.latin.utils.PluginTrust.requireTrusted(context, apkFile) extractNativeLibs(apkFile, nativeLibDir) val classLoader = PluginClassLoader( apkFile.absolutePath, diff --git a/app/src/main/java/helium314/keyboard/latin/utils/PluginTrust.kt b/app/src/main/java/helium314/keyboard/latin/utils/PluginTrust.kt index 708937ca7f..5ba1d97631 100644 --- a/app/src/main/java/helium314/keyboard/latin/utils/PluginTrust.kt +++ b/app/src/main/java/helium314/keyboard/latin/utils/PluginTrust.kt @@ -7,6 +7,7 @@ import android.os.Build import android.os.Handler import android.os.Looper import android.widget.Toast +import helium314.keyboard.latin.R import java.io.File import java.security.MessageDigest @@ -51,7 +52,7 @@ object PluginTrust { /** The LeanBitLab keys and the key of the keyboard itself */ private fun trustedSigners(context: Context): Set { val own = ownSigners ?: try { - packageSigners(context.packageManager, context.packageName).toSet() + packageSigners(context.packageManager, context.packageName).certs.toSet() } catch (e: Exception) { Log.w(TAG, "could not read the own signature", e) emptySet() @@ -61,36 +62,43 @@ object PluginTrust { /** files already checked in this process, by path, size and modification time */ private val checked = HashSet() + /** files refused in this process, with the reason: not checked again, the message is shown once */ + private val refused = HashMap() /** Throws a [SecurityException] if [apk] is not an official plugin; call before loading any code of it */ fun requireTrusted(context: Context, apk: File) { val id = "${apk.absolutePath}:${apk.length()}:${apk.lastModified()}" - synchronized(checked) { if (id in checked) return } + synchronized(checked) { + if (id in checked) return + refused[id]?.let { throw SecurityException("untrusted plugin ${apk.name}: $it") } + } val reason = untrustedReason(context, apk) if (reason == null) { synchronized(checked) { checked.add(id) } return } + synchronized(checked) { refused[id] = reason } Log.e(TAG, "not loading ${apk.name}: $reason") - val appContext = context.applicationContext ?: context - Handler(Looper.getMainLooper()).post { - Toast.makeText(appContext, "Plugin not loaded: $reason", Toast.LENGTH_LONG).show() - } + showMessage(context, context.getString(R.string.plugin_not_loaded, reason)) throw SecurityException("untrusted plugin ${apk.name}: $reason") } + private fun showMessage(context: Context, message: String) { + val appContext = context.applicationContext ?: context + Handler(Looper.getMainLooper()).post { Toast.makeText(appContext, message, Toast.LENGTH_LONG).show() } + } + /** null if [apk] is an official plugin, otherwise why not */ fun untrustedReason(context: Context, apk: File): String? { val signers = try { signerDigests(context, apk) } catch (e: Exception) { Log.w(TAG, "could not read the signature of ${apk.name}", e) - emptySet() + Signers(emptyList(), false) } - if (signers.isNotEmpty()) { - val trusted = trustedSigners(context) - if (signers.all { it in trusted }) return null - return "unknown signing key ${signers.first().take(16)}…" + if (signers.certs.isNotEmpty()) { + if (signers.isTrusted(trustedSigners(context))) return null + return "unknown signing key ${signers.certs.first().take(16)}…" } val fileHash = try { sha256(apk) } catch (e: Exception) { return "file can't be read" } if (fileHash in TRUSTED_UNSIGNED_FILES) return null @@ -100,10 +108,9 @@ object PluginTrust { /** installed plugin apps already checked, by package and update time */ private val checkedPackages = HashSet() - /** - * Whether the installed app [packageName] (a plugin that runs as its own app, like the voice plugin) - * is signed with a known LeanBitLab key. Shows a message and returns false otherwise. - */ + /** installed plugin apps already refused, by package and update time: the message is shown once */ + private val refusedPackages = HashSet() + /** * Whether [packageName] is installed but not signed with a trusted key. A package that is not installed * is not refused here: Android cannot bind to it anyway (and tests use such fake components). @@ -119,6 +126,10 @@ object PluginTrust { return !isTrustedPackage(context, packageName) } + /** + * Whether the installed app [packageName] (a plugin that runs as its own app, like the voice plugin) + * is signed with a known LeanBitLab key. Shows a message (once) and returns false otherwise. + */ fun isTrustedPackage(context: Context, packageName: String): Boolean { val pm = context.packageManager val updated = try { @@ -132,50 +143,58 @@ object PluginTrust { val signers = try { packageSigners(pm, packageName) } catch (e: Exception) { - emptyList() + Signers(emptyList(), false) } - val trusted = trustedSigners(context) - if (signers.isNotEmpty() && signers.all { it in trusted }) { + if (signers.certs.isNotEmpty() && signers.isTrusted(trustedSigners(context))) { synchronized(checkedPackages) { checkedPackages.add(id) } return true } - val reason = if (signers.isEmpty()) "signature can't be read" else "unknown signing key ${signers.first().take(16)}…" + val reason = if (signers.certs.isEmpty()) "signature can't be read" else "unknown signing key ${signers.certs.first().take(16)}…" Log.e(TAG, "not using $packageName: $reason") - val appContext = context.applicationContext ?: context - Handler(Looper.getMainLooper()).post { - Toast.makeText(appContext, "Plugin not used: $reason", Toast.LENGTH_LONG).show() - } + val firstTime = synchronized(checkedPackages) { refusedPackages.add(id) } + if (firstTime) showMessage(context, context.getString(R.string.plugin_not_used, reason)) return false } - /** SHA-256 (upper case) of the certificates the installed app [packageName] is signed with */ - private fun packageSigners(pm: PackageManager, packageName: String): List { - val certs = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { - val signing = pm.getPackageInfo(packageName, PackageManager.GET_SIGNING_CERTIFICATES).signingInfo - if (signing == null) emptyList() - else (if (signing.hasMultipleSigners()) signing.apkContentsSigners else signing.signingCertificateHistory)?.toList() ?: emptyList() - } else { - @Suppress("DEPRECATION") - pm.getPackageInfo(packageName, PackageManager.GET_SIGNATURES).signatures?.toList() ?: emptyList() - } - return certs.map { hex(MessageDigest.getInstance("SHA-256").digest(it.toByteArray())).uppercase() } + /** + * SHA-256 (upper case) of the signing certificates. With one signer, [certs] is its key history (key + * rotation), and a trusted key anywhere in it is enough: only the owner of that key can add a newer one. + * With several signers, all of them must be trusted. + */ + private class Signers(val certs: List, val multiple: Boolean) { + fun isTrusted(trusted: Set) = if (multiple) certs.all { it in trusted } else certs.any { it in trusted } } - /** SHA-256 of the certificates that signed [apk], verified by Android; empty if it is not (validly) signed */ - private fun signerDigests(context: Context, apk: File): Set { - val pm = context.packageManager - val certs = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { - @Suppress("WrongConstant") - val info = pm.getPackageArchiveInfo(apk.absolutePath, PackageManager.GET_SIGNING_CERTIFICATES) - val signing = info?.signingInfo ?: return emptySet() - if (signing.hasMultipleSigners()) signing.apkContentsSigners else signing.signingCertificateHistory - } else { - @Suppress("DEPRECATION") - pm.getPackageArchiveInfo(apk.absolutePath, PackageManager.GET_SIGNATURES)?.signatures - } ?: return emptySet() - return certs.map { hex(MessageDigest.getInstance("SHA-256").digest(it.toByteArray())).uppercase() }.toSet() + private fun digests(certs: Array?) = + certs.orEmpty().map { hex(MessageDigest.getInstance("SHA-256").digest(it.toByteArray())).uppercase() } + + @Suppress("DEPRECATION") + private fun signersOf(info: android.content.pm.PackageInfo?): Signers { + if (info == null) return Signers(emptyList(), false) + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { + val signing = info.signingInfo + if (signing != null) { + return if (signing.hasMultipleSigners()) Signers(digests(signing.apkContentsSigners), true) + else Signers(digests(signing.signingCertificateHistory), false) + } + } + val old = digests(info.signatures) + return Signers(old, old.size > 1) } + /** Flags for reading signatures; both, since some Android 9 versions fill signingInfo only with GET_SIGNATURES */ + @Suppress("DEPRECATION") + private val signatureFlags = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) + PackageManager.GET_SIGNATURES or PackageManager.GET_SIGNING_CERTIFICATES else PackageManager.GET_SIGNATURES + + /** Signing certificates of the installed app [packageName] */ + private fun packageSigners(pm: PackageManager, packageName: String): Signers = + signersOf(pm.getPackageInfo(packageName, signatureFlags)) + + /** Signing certificates of [apk], verified by Android; empty if it is not (validly) signed */ + private fun signerDigests(context: Context, apk: File): Signers = + signersOf(context.packageManager.getPackageArchiveInfo(apk.absolutePath, signatureFlags)) + private fun sha256(file: File): String { val digest = MessageDigest.getInstance("SHA-256") file.inputStream().use { input -> diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index 3ceb25bd6a..8163050e8f 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -1802,4 +1802,6 @@ Ermöglicht lokale GGUF / llama.cpp-Inferenz für Korrekturlesen und Umschreiben Lange auf physische Tasten drücken, um Popup-Zeichen anzuzeigen Beim Halten einer physischen Taste werden die Zeichen ihres Popups in der Vorschlagsleiste angezeigt. Wählen Sie eines aus, um den getippten Buchstaben zu ersetzen Verlaufsspeicherung + Plugin nicht geladen: %s + Plugin nicht verwendet: %s diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index afa0dfb00d..4556b1b96d 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -2523,4 +2523,6 @@ New dictionary: background_image|picture photo wallpaper navbar_color|buttons + Plugin not loaded: %s + Plugin not used: %s