Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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}"
Expand Down Expand Up @@ -307,7 +309,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 ->
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 ->
Expand Down Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,8 @@ 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)
extractNativeLibs(apkFile, nativeLibDir)
val cachedLoader = cachedClassLoader
val classLoader = if (cachedLoader != null && cachedApkModified == apkFile.lastModified()) {
Expand Down Expand Up @@ -179,7 +181,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 ->
Expand Down Expand Up @@ -235,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,
Expand Down
212 changes: 212 additions & 0 deletions app/src/main/java/helium314/keyboard/latin/utils/PluginTrust.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,212 @@
// 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 helium314.keyboard.latin.R
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<String>? = null

/** The LeanBitLab keys and the key of the keyboard itself */
private fun trustedSigners(context: Context): Set<String> {
val own = ownSigners ?: try {
packageSigners(context.packageManager, context.packageName).certs.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<String>()
/** files refused in this process, with the reason: not checked again, the message is shown once */
private val refused = HashMap<String, String>()

/** 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
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")
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)
Signers(emptyList(), false)
}
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
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<String>()

/** installed plugin apps already refused, by package and update time: the message is shown once */
private val refusedPackages = HashSet<String>()

/**
* 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)
}

/**
* 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 {
@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) {
Signers(emptyList(), false)
}
if (signers.certs.isNotEmpty() && signers.isTrusted(trustedSigners(context))) {
synchronized(checkedPackages) { checkedPackages.add(id) }
return true
}
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 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 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<String>, val multiple: Boolean) {
fun isTrusted(trusted: Set<String>) = if (multiple) certs.all { it in trusted } else certs.any { it in trusted }
}

private fun digests(certs: Array<android.content.pm.Signature>?) =
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 ->
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) }
}
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 2 additions & 0 deletions app/src/main/res/values-de/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -1802,4 +1802,6 @@ Ermöglicht lokale GGUF / llama.cpp-Inferenz für Korrekturlesen und Umschreiben
<string name="prefs_physical_key_long_press_popup">Lange auf physische Tasten drücken, um Popup-Zeichen anzuzeigen</string>
<string name="prefs_physical_key_long_press_popup_summary">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</string>
<string name="clipboard_history_retention">Verlaufsspeicherung</string>
<string name="plugin_not_loaded">Plugin nicht geladen: %s</string>
<string name="plugin_not_used">Plugin nicht verwendet: %s</string>
</resources>
2 changes: 2 additions & 0 deletions app/src/main/res/values/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -2523,4 +2523,6 @@ New dictionary:
<item>background_image|picture photo wallpaper</item>
<item>navbar_color|buttons</item>
</string-array>
<string name="plugin_not_loaded">Plugin not loaded: %s</string>
<string name="plugin_not_used">Plugin not used: %s</string>
</resources>
Original file line number Diff line number Diff line change
@@ -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))
}
}
Loading