From 1240c2e35ca3f232d7a125238a33e634e9ab3231 Mon Sep 17 00:00:00 2001 From: topjohnwu Date: Thu, 22 Oct 2026 05:28:13 +0000 Subject: [PATCH] app: Remove app repackaging and signing Remove app hiding repackaging, key generation, AXML patching, and in-app APK signing components along with BouncyCastle (bcpkix). - Delete AppMigration, Keygen, AXML, and signing package classes. - Remove bcpkix dependency and build-logic packaging exclude. - Remove suManager, keyStoreRaw, StringDao, and strings DB table. - Simplify DownloadProcessor app update and SplashScreen init. - Remove AppMigrationTest, setupAppHide/Restore, and test scripts references to repackaged test packages. - Remove unused hide_app_title string across all locales. Assisted-by: Gemini 4 Argon --- app/build-logic/src/main/java/Setup.kt | 1 - app/core/build.gradle.kts | 1 - .../java/com/topjohnwu/magisk/core/Config.kt | 42 +- .../java/com/topjohnwu/magisk/core/Const.kt | 1 - .../magisk/core/base/BaseActivity.kt | 9 - .../magisk/core/base/SplashScreen.kt | 67 +- .../magisk/core/data/magiskdb/MagiskDB.kt | 1 - .../magisk/core/data/magiskdb/StringDao.kt | 20 - .../magisk/core/di/ServiceLocator.kt | 2 - .../magisk/core/download/DownloadProcessor.kt | 43 +- .../magisk/core/repository/DBConfig.kt | 54 -- .../magisk/core/signing/ApkSignerV2.java | 772 ------------------ .../magisk/core/signing/ByteArrayStream.java | 35 - .../topjohnwu/magisk/core/signing/JarMap.java | 166 ---- .../magisk/core/signing/SignApk.java | 566 ------------- .../magisk/core/signing/ZipUtils.java | 136 --- .../magisk/core/tasks/AppMigration.kt | 296 ------- .../com/topjohnwu/magisk/core/utils/AXML.kt | 124 --- .../com/topjohnwu/magisk/core/utils/Keygen.kt | 80 -- .../com/topjohnwu/magisk/test/Environment.kt | 26 - app/core/src/main/res/values-ar/strings.xml | 1 - app/core/src/main/res/values-ast/strings.xml | 1 - app/core/src/main/res/values-az/strings.xml | 1 - .../src/main/res/values-b+sr+Latn/strings.xml | 1 - app/core/src/main/res/values-be/strings.xml | 1 - app/core/src/main/res/values-bg/strings.xml | 1 - app/core/src/main/res/values-bn/strings.xml | 1 - app/core/src/main/res/values-ca/strings.xml | 1 - app/core/src/main/res/values-cs/strings.xml | 1 - app/core/src/main/res/values-de/strings.xml | 1 - app/core/src/main/res/values-el/strings.xml | 1 - app/core/src/main/res/values-es/strings.xml | 1 - app/core/src/main/res/values-et/strings.xml | 1 - app/core/src/main/res/values-fa/strings.xml | 1 - app/core/src/main/res/values-fr/strings.xml | 1 - app/core/src/main/res/values-hi/strings.xml | 1 - app/core/src/main/res/values-hn/strings.xml | 1 - app/core/src/main/res/values-hu/strings.xml | 1 - app/core/src/main/res/values-in/strings.xml | 1 - app/core/src/main/res/values-it/strings.xml | 1 - app/core/src/main/res/values-iw/strings.xml | 1 - app/core/src/main/res/values-ja/strings.xml | 1 - app/core/src/main/res/values-ka/strings.xml | 1 - app/core/src/main/res/values-kk/strings.xml | 1 - app/core/src/main/res/values-ko/strings.xml | 1 - app/core/src/main/res/values-ku/strings.xml | 1 - app/core/src/main/res/values-lt/strings.xml | 1 - app/core/src/main/res/values-ml/strings.xml | 1 - app/core/src/main/res/values-nb/strings.xml | 1 - app/core/src/main/res/values-pl/strings.xml | 1 - .../src/main/res/values-pt-rBR/strings.xml | 1 - .../src/main/res/values-pt-rPT/strings.xml | 1 - app/core/src/main/res/values-ro/strings.xml | 1 - app/core/src/main/res/values-ru/strings.xml | 1 - app/core/src/main/res/values-sk/strings.xml | 1 - app/core/src/main/res/values-sq/strings.xml | 1 - app/core/src/main/res/values-sr/strings.xml | 1 - app/core/src/main/res/values-sv/strings.xml | 1 - app/core/src/main/res/values-sw/strings.xml | 1 - app/core/src/main/res/values-ta/strings.xml | 1 - app/core/src/main/res/values-tr/strings.xml | 1 - app/core/src/main/res/values-uk/strings.xml | 1 - app/core/src/main/res/values-ur/strings.xml | 1 - app/core/src/main/res/values-vi/strings.xml | 1 - .../src/main/res/values-zh-rCN/strings.xml | 1 - .../src/main/res/values-zh-rTW/strings.xml | 1 - app/core/src/main/res/values/strings.xml | 1 - app/gradle/libs.versions.toml | 1 - app/test/src/main/AndroidManifest.xml | 4 - .../topjohnwu/magisk/test/AppMigrationTest.kt | 89 -- scripts/avd.sh | 1 - scripts/test_common.sh | 14 - 72 files changed, 5 insertions(+), 2593 deletions(-) delete mode 100644 app/core/src/main/java/com/topjohnwu/magisk/core/data/magiskdb/StringDao.kt delete mode 100644 app/core/src/main/java/com/topjohnwu/magisk/core/signing/ApkSignerV2.java delete mode 100644 app/core/src/main/java/com/topjohnwu/magisk/core/signing/ByteArrayStream.java delete mode 100644 app/core/src/main/java/com/topjohnwu/magisk/core/signing/JarMap.java delete mode 100644 app/core/src/main/java/com/topjohnwu/magisk/core/signing/SignApk.java delete mode 100644 app/core/src/main/java/com/topjohnwu/magisk/core/signing/ZipUtils.java delete mode 100644 app/core/src/main/java/com/topjohnwu/magisk/core/tasks/AppMigration.kt delete mode 100644 app/core/src/main/java/com/topjohnwu/magisk/core/utils/AXML.kt delete mode 100644 app/core/src/main/java/com/topjohnwu/magisk/core/utils/Keygen.kt delete mode 100644 app/test/src/main/java/com/topjohnwu/magisk/test/AppMigrationTest.kt diff --git a/app/build-logic/src/main/java/Setup.kt b/app/build-logic/src/main/java/Setup.kt index 6a8127789..dfd217ef6 100644 --- a/app/build-logic/src/main/java/Setup.kt +++ b/app/build-logic/src/main/java/Setup.kt @@ -67,7 +67,6 @@ fun Project.setupCommon() { "/META-INF/androidx/**", "/META-INF/versions/**", "/META-INF/native-image/**", - "/org/bouncycastle/**", "/org/apache/commons/**", "/kotlin/**", "/*.txt", diff --git a/app/core/build.gradle.kts b/app/core/build.gradle.kts index 7d2c3efff..9364c89a4 100644 --- a/app/core/build.gradle.kts +++ b/app/core/build.gradle.kts @@ -43,7 +43,6 @@ dependencies { api(libs.timber) api(libs.markwon.core) - implementation(libs.bcpkix) implementation(libs.commons.compress) implementation(libs.xz) implementation(libs.wire.runtime) diff --git a/app/core/src/main/java/com/topjohnwu/magisk/core/Config.kt b/app/core/src/main/java/com/topjohnwu/magisk/core/Config.kt index 03f29bc2c..cde22fd93 100644 --- a/app/core/src/main/java/com/topjohnwu/magisk/core/Config.kt +++ b/app/core/src/main/java/com/topjohnwu/magisk/core/Config.kt @@ -1,6 +1,5 @@ package com.topjohnwu.magisk.core -import android.os.Bundle import androidx.core.content.edit import com.topjohnwu.magisk.core.di.ServiceLocator import com.topjohnwu.magisk.core.model.ColorMode @@ -11,7 +10,6 @@ import kotlinx.coroutines.GlobalScope object Config : PreferenceConfig, DBConfig { - override val stringDB get() = ServiceLocator.stringDB override val settingsDB get() = ServiceLocator.settingsDB override val context get() = ServiceLocator.deContext @OptIn(kotlinx.coroutines.DelicateCoroutinesApi::class) @@ -24,8 +22,6 @@ object Config : PreferenceConfig, DBConfig { const val SU_BIOMETRIC = "su_biometric" const val ZYGISK = "zygisk" const val BOOTLOOP = "bootloop" - const val SU_MANAGER = "requester" - const val KEYSTORE = "keystore" // prefs const val SU_NOTIFICATION = "su_notification" @@ -41,8 +37,6 @@ object Config : PreferenceConfig, DBConfig { const val THEME_ORDINAL = "theme_ordinal" const val DOH = "doh" const val RAND_NAME = "rand_name" - - val NO_MIGRATION = emptySet() } object OldValue { @@ -119,8 +113,6 @@ object Config : PreferenceConfig, DBConfig { } var zygisk by dbSettings(Key.ZYGISK, Info.isEmulator) - var suManager by dbStrings(Key.SU_MANAGER, "", true) - var keyStoreRaw by dbStrings(Key.KEYSTORE, "", true) var suNotification by preferenceStrInt(Key.SU_NOTIFICATION, Value.NOTIFICATION_TOAST) var suMntNamespaceMode by dbSettings(Key.SU_MNT_NS, Value.NAMESPACE_MODE_REQUESTER) var suMultiuserMode by dbSettings(Key.SU_MULTIUSER_MODE, Value.MULTIUSER_MODE_OWNER_ONLY) @@ -135,39 +127,7 @@ object Config : PreferenceConfig, DBConfig { private const val SU_FINGERPRINT = "su_fingerprint" private const val UPDATE_CHANNEL = "update_channel" - fun toBundle(): Bundle { - val map = prefs.all - Key.NO_MIGRATION - return Bundle().apply { - for ((key, value) in map) { - when (value) { - is String -> putString(key, value) - is Int -> putInt(key, value) - is Boolean -> putBoolean(key, value) - } - } - } - } - - @Suppress("DEPRECATION") - private fun fromBundle(bundle: Bundle) { - val keys = bundle.keySet().apply { removeAll(Key.NO_MIGRATION) } - prefs.edit { - for (key in keys) { - when (val value = bundle.get(key)) { - is String -> putString(key, value) - is Int -> putInt(key, value) - is Boolean -> putBoolean(key, value) - } - } - } - } - - fun init(bundle: Bundle?) { - // Only try to load prefs when fresh install - if (bundle != null && prefs.all.isEmpty()) { - fromBundle(bundle) - } - + fun init() { prefs.edit { // Migrate su_fingerprint if (prefs.getBoolean(SU_FINGERPRINT, false)) diff --git a/app/core/src/main/java/com/topjohnwu/magisk/core/Const.kt b/app/core/src/main/java/com/topjohnwu/magisk/core/Const.kt index 2f0c85b13..74604585e 100644 --- a/app/core/src/main/java/com/topjohnwu/magisk/core/Const.kt +++ b/app/core/src/main/java/com/topjohnwu/magisk/core/Const.kt @@ -53,7 +53,6 @@ object Const { object Key { // intents const val OPEN_SECTION = "section" - const val PREV_CONFIG = "prev_config" } object Value { diff --git a/app/core/src/main/java/com/topjohnwu/magisk/core/base/BaseActivity.kt b/app/core/src/main/java/com/topjohnwu/magisk/core/base/BaseActivity.kt index 74c1b5e2a..00854a545 100644 --- a/app/core/src/main/java/com/topjohnwu/magisk/core/base/BaseActivity.kt +++ b/app/core/src/main/java/com/topjohnwu/magisk/core/base/BaseActivity.kt @@ -16,7 +16,6 @@ import androidx.activity.result.ActivityResultCallback import androidx.activity.result.contract.ActivityResultContracts.GetContent import androidx.activity.result.contract.ActivityResultContracts.RequestPermission import com.topjohnwu.magisk.core.R -import com.topjohnwu.magisk.core.ktx.reflectField import com.topjohnwu.magisk.core.ktx.toast import com.topjohnwu.magisk.core.utils.RequestAuthentication import com.topjohnwu.magisk.core.utils.RequestInstall @@ -127,14 +126,6 @@ class ActivityExtension(private val activity: ComponentActivity) { } } -val Activity.launchPackage: String? get() { - return if (Build.VERSION.SDK_INT >= 34) { - launchedFromPackage - } else { - Activity::class.java.reflectField("mReferrer").get(this) as String? - } -} - fun Activity.relaunch() { startActivity(Intent(intent).setFlags(0)) finish() diff --git a/app/core/src/main/java/com/topjohnwu/magisk/core/base/SplashScreen.kt b/app/core/src/main/java/com/topjohnwu/magisk/core/base/SplashScreen.kt index 2d96eb357..7838be153 100644 --- a/app/core/src/main/java/com/topjohnwu/magisk/core/base/SplashScreen.kt +++ b/app/core/src/main/java/com/topjohnwu/magisk/core/base/SplashScreen.kt @@ -1,31 +1,18 @@ package com.topjohnwu.magisk.core.base -import android.Manifest.permission.REQUEST_INSTALL_PACKAGES import android.os.Bundle import androidx.activity.ComponentActivity import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen import androidx.lifecycle.Lifecycle -import androidx.lifecycle.lifecycleScope -import com.topjohnwu.magisk.StubApk -import com.topjohnwu.magisk.core.BuildConfig -import com.topjohnwu.magisk.core.BuildConfig.APP_PACKAGE_NAME import com.topjohnwu.magisk.core.Config -import com.topjohnwu.magisk.core.Const -import com.topjohnwu.magisk.core.Info import com.topjohnwu.magisk.core.JobService import com.topjohnwu.magisk.core.R import com.topjohnwu.magisk.core.di.ServiceLocator import com.topjohnwu.magisk.core.isRunningAsStub -import com.topjohnwu.magisk.core.ktx.writeTo -import com.topjohnwu.magisk.core.tasks.AppMigration import com.topjohnwu.magisk.core.utils.RootUtils import com.topjohnwu.magisk.view.Notifications import com.topjohnwu.magisk.view.Shortcuts import com.topjohnwu.superuser.Shell -import kotlinx.coroutines.launch -import timber.log.Timber -import java.io.File -import java.io.IOException interface SplashScreenHost : IActivityExtension { val splashController: SplashController<*> @@ -94,59 +81,7 @@ class SplashController(private val activity: T) } private fun T.initializeApp() { - val prevPkg = launchPackage - val prevConfig = intent.getBundleExtra(Const.Key.PREV_CONFIG) - val isPackageMigration = prevPkg != null && prevConfig != null - - Config.init(prevConfig) - - if (packageName != APP_PACKAGE_NAME) { - runCatching { - // Hidden, remove com.topjohnwu.magisk if exist as it could be malware - packageManager.getApplicationInfo(APP_PACKAGE_NAME, 0) - Shell.cmd("(pm uninstall $APP_PACKAGE_NAME)& >/dev/null 2>&1").exec() - } - } else { - if (Config.suManager.isNotEmpty()) { - Config.suManager = "" - } - if (isPackageMigration) { - Shell.cmd("(pm uninstall $prevPkg)& >/dev/null 2>&1").exec() - } - } - - if (isPackageMigration) { - runOnUiThread { - // Relaunch the process after package migration - StubApk.restartProcess(this) - } - return - } - - // Validate stub APK - if (isRunningAsStub && ( - // Version mismatch - Info.stub!!.version != BuildConfig.STUB_VERSION || - // Not properly patched - intent.component!!.className.contains(AppMigration.PLACEHOLDER)) - ) { - withPermission(REQUEST_INSTALL_PACKAGES) { granted -> - if (granted) { - lifecycleScope.launch { - val apk = File(cacheDir, "stub.apk") - try { - assets.open("stub.apk").writeTo(apk) - AppMigration.upgradeStub(activity, apk)?.let { - startActivity(it) - } - } catch (e: IOException) { - Timber.e(e) - } - } - } - } - return - } + Config.init() Notifications.setup() JobService.schedule(this) diff --git a/app/core/src/main/java/com/topjohnwu/magisk/core/data/magiskdb/MagiskDB.kt b/app/core/src/main/java/com/topjohnwu/magisk/core/data/magiskdb/MagiskDB.kt index ff44ed1f0..a8badaf61 100644 --- a/app/core/src/main/java/com/topjohnwu/magisk/core/data/magiskdb/MagiskDB.kt +++ b/app/core/src/main/java/com/topjohnwu/magisk/core/data/magiskdb/MagiskDB.kt @@ -49,6 +49,5 @@ open class MagiskDB { object Table { const val POLICY = "policies" const val SETTINGS = "settings" - const val STRINGS = "strings" } } diff --git a/app/core/src/main/java/com/topjohnwu/magisk/core/data/magiskdb/StringDao.kt b/app/core/src/main/java/com/topjohnwu/magisk/core/data/magiskdb/StringDao.kt deleted file mode 100644 index 2ea488a59..000000000 --- a/app/core/src/main/java/com/topjohnwu/magisk/core/data/magiskdb/StringDao.kt +++ /dev/null @@ -1,20 +0,0 @@ -package com.topjohnwu.magisk.core.data.magiskdb - -class StringDao : MagiskDB() { - - suspend fun delete(key: String) { - val query = "DELETE FROM ${Table.STRINGS} WHERE key=\"$key\"" - exec(query) - } - - suspend fun put(key: String, value: String) { - val kv = mapOf("key" to key, "value" to value) - val query = "REPLACE INTO ${Table.STRINGS} ${kv.toQuery()}" - exec(query) - } - - suspend fun fetch(key: String, default: String = ""): String { - val query = "SELECT value FROM ${Table.STRINGS} WHERE key=\"$key\" LIMIT 1" - return exec(query) { it["value"] }.firstOrNull() ?: default - } -} diff --git a/app/core/src/main/java/com/topjohnwu/magisk/core/di/ServiceLocator.kt b/app/core/src/main/java/com/topjohnwu/magisk/core/di/ServiceLocator.kt index bc9207f11..26a4a8840 100644 --- a/app/core/src/main/java/com/topjohnwu/magisk/core/di/ServiceLocator.kt +++ b/app/core/src/main/java/com/topjohnwu/magisk/core/di/ServiceLocator.kt @@ -9,7 +9,6 @@ import com.topjohnwu.magisk.core.Const import com.topjohnwu.magisk.core.data.SuLogDatabase import com.topjohnwu.magisk.core.data.magiskdb.PolicyDao import com.topjohnwu.magisk.core.data.magiskdb.SettingsDao -import com.topjohnwu.magisk.core.data.magiskdb.StringDao import com.topjohnwu.magisk.core.repository.FirmwareCrawler import com.topjohnwu.magisk.core.repository.LogRepository import com.topjohnwu.magisk.core.repository.NetworkService @@ -24,7 +23,6 @@ object ServiceLocator { // Database val policyDB = PolicyDao() val settingsDB = SettingsDao() - val stringDB = StringDao() val sulogDB by lazy { createSuLogDatabase(deContext).suLogDao() } val logRepo by lazy { LogRepository(sulogDB) } diff --git a/app/core/src/main/java/com/topjohnwu/magisk/core/download/DownloadProcessor.kt b/app/core/src/main/java/com/topjohnwu/magisk/core/download/DownloadProcessor.kt index 97a6f25ac..f672073ac 100644 --- a/app/core/src/main/java/com/topjohnwu/magisk/core/download/DownloadProcessor.kt +++ b/app/core/src/main/java/com/topjohnwu/magisk/core/download/DownloadProcessor.kt @@ -1,21 +1,16 @@ package com.topjohnwu.magisk.core.download import android.net.Uri -import com.topjohnwu.magisk.StubApk -import com.topjohnwu.magisk.core.R -import com.topjohnwu.magisk.core.isRunningAsStub import com.topjohnwu.magisk.core.ktx.cachedFile import com.topjohnwu.magisk.core.ktx.copyAll import com.topjohnwu.magisk.core.ktx.copyAndClose import com.topjohnwu.magisk.core.ktx.withInOut import com.topjohnwu.magisk.core.ktx.writeTo -import com.topjohnwu.magisk.core.tasks.AppMigration import com.topjohnwu.magisk.core.utils.MediaStoreUtils.outputStream import com.topjohnwu.magisk.utils.APKInstall import org.apache.commons.compress.archivers.zip.ZipArchiveEntry import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream import org.apache.commons.compress.archivers.zip.ZipFile -import java.io.IOException import java.io.InputStream import java.io.OutputStream @@ -31,41 +26,9 @@ class DownloadProcessor(notifier: DownloadNotifier) : DownloadNotifier by notifi suspend fun handleApp(stream: InputStream, subject: Subject.App) { val external = subject.file.outputStream() - - if (isRunningAsStub) { - val updateApk = StubApk.update(context) - try { - // Download full APK to stub update path - stream.copyAndClose(TeeOutputStream(external, updateApk.outputStream())) - - // Also upgrade stub - notifyUpdate(subject.notifyId) { - it.setProgress(0, 0, true) - .setContentTitle(context.getString(R.string.hide_app_title)) - .setContentText("") - } - - // Extract stub - val apk = context.cachedFile("stub.apk") - ZipFile.Builder().setFile(updateApk).get().use { zf -> - apk.delete() - zf.getInputStream(zf.getEntry("assets/stub.apk")).writeTo(apk) - } - - // Patch and install - subject.intent = AppMigration.upgradeStub(context, apk) - ?: throw IOException("HideAPK patch error") - apk.delete() - } catch (e: Exception) { - // If any error occurred, do not let stub load the new APK - updateApk.delete() - throw e - } - } else { - val session = APKInstall.startSession(context) - stream.copyAndClose(TeeOutputStream(external, session.openStream(context))) - subject.intent = session.waitIntent() - } + val session = APKInstall.startSession(context) + stream.copyAndClose(TeeOutputStream(external, session.openStream(context))) + subject.intent = session.waitIntent() } suspend fun handleModule(src: InputStream, file: Uri) { diff --git a/app/core/src/main/java/com/topjohnwu/magisk/core/repository/DBConfig.kt b/app/core/src/main/java/com/topjohnwu/magisk/core/repository/DBConfig.kt index 1e56bb948..2039bf11e 100644 --- a/app/core/src/main/java/com/topjohnwu/magisk/core/repository/DBConfig.kt +++ b/app/core/src/main/java/com/topjohnwu/magisk/core/repository/DBConfig.kt @@ -1,7 +1,6 @@ package com.topjohnwu.magisk.core.repository import com.topjohnwu.magisk.core.data.magiskdb.SettingsDao -import com.topjohnwu.magisk.core.data.magiskdb.StringDao import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking @@ -10,7 +9,6 @@ import kotlin.reflect.KProperty interface DBConfig { val settingsDB: SettingsDao - val stringDB: StringDao val coroutineScope: CoroutineScope fun dbSettings( @@ -22,13 +20,6 @@ interface DBConfig { name: String, default: Boolean ) = BoolDBProperty(name, default) - - fun dbStrings( - name: String, - default: String, - sync: Boolean = false - ) = StringDBProperty(name, default, sync) - } class IntDBProperty( @@ -68,48 +59,3 @@ open class BoolDBProperty( override fun setValue(thisRef: DBConfig, property: KProperty<*>, value: Boolean) = base.setValue(thisRef, property, if (value) 1 else 0) } - -class StringDBProperty( - private val name: String, - private val default: String, - private val sync: Boolean -) : ReadWriteProperty { - - private var value: String? = null - - @Synchronized - override fun getValue(thisRef: DBConfig, property: KProperty<*>): String { - if (value == null) - value = runBlocking { - thisRef.stringDB.fetch(name, default) - } - return value!! - } - - override fun setValue(thisRef: DBConfig, property: KProperty<*>, value: String) { - synchronized(this) { - this.value = value - } - if (value.isEmpty()) { - if (sync) { - runBlocking { - thisRef.stringDB.delete(name) - } - } else { - thisRef.coroutineScope.launch { - thisRef.stringDB.delete(name) - } - } - } else { - if (sync) { - runBlocking { - thisRef.stringDB.put(name, value) - } - } else { - thisRef.coroutineScope.launch { - thisRef.stringDB.put(name, value) - } - } - } - } -} diff --git a/app/core/src/main/java/com/topjohnwu/magisk/core/signing/ApkSignerV2.java b/app/core/src/main/java/com/topjohnwu/magisk/core/signing/ApkSignerV2.java deleted file mode 100644 index 789ba1a05..000000000 --- a/app/core/src/main/java/com/topjohnwu/magisk/core/signing/ApkSignerV2.java +++ /dev/null @@ -1,772 +0,0 @@ -package com.topjohnwu.magisk.core.signing; - -import java.nio.BufferUnderflowException; -import java.nio.ByteBuffer; -import java.nio.ByteOrder; -import java.security.DigestException; -import java.security.InvalidAlgorithmParameterException; -import java.security.InvalidKeyException; -import java.security.KeyFactory; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.security.PrivateKey; -import java.security.PublicKey; -import java.security.Signature; -import java.security.SignatureException; -import java.security.cert.CertificateEncodingException; -import java.security.cert.X509Certificate; -import java.security.spec.AlgorithmParameterSpec; -import java.security.spec.InvalidKeySpecException; -import java.security.spec.MGF1ParameterSpec; -import java.security.spec.PSSParameterSpec; -import java.security.spec.X509EncodedKeySpec; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -/** - * APK Signature Scheme v2 signer. - * - *

APK Signature Scheme v2 is a whole-file signature scheme which aims to protect every single - * bit of the APK, as opposed to the JAR Signature Scheme which protects only the names and - * uncompressed contents of ZIP entries. - */ -public abstract class ApkSignerV2 { - /* - * The two main goals of APK Signature Scheme v2 are: - * 1. Detect any unauthorized modifications to the APK. This is achieved by making the signature - * cover every byte of the APK being signed. - * 2. Enable much faster signature and integrity verification. This is achieved by requiring - * only a minimal amount of APK parsing before the signature is verified, thus completely - * bypassing ZIP entry decompression and by making integrity verification parallelizable by - * employing a hash tree. - * - * The generated signature block is wrapped into an APK Signing Block and inserted into the - * original APK immediately before the start of ZIP Central Directory. This is to ensure that - * JAR and ZIP parsers continue to work on the signed APK. The APK Signing Block is designed for - * extensibility. For example, a future signature scheme could insert its signatures there as - * well. The contract of the APK Signing Block is that all contents outside of the block must be - * protected by signatures inside the block. - */ - - public static final int SIGNATURE_RSA_PSS_WITH_SHA256 = 0x0101; - public static final int SIGNATURE_RSA_PSS_WITH_SHA512 = 0x0102; - public static final int SIGNATURE_RSA_PKCS1_V1_5_WITH_SHA256 = 0x0103; - public static final int SIGNATURE_RSA_PKCS1_V1_5_WITH_SHA512 = 0x0104; - public static final int SIGNATURE_ECDSA_WITH_SHA256 = 0x0201; - public static final int SIGNATURE_ECDSA_WITH_SHA512 = 0x0202; - public static final int SIGNATURE_DSA_WITH_SHA256 = 0x0301; - public static final int SIGNATURE_DSA_WITH_SHA512 = 0x0302; - - /** - * {@code .SF} file header section attribute indicating that the APK is signed not just with - * JAR signature scheme but also with APK Signature Scheme v2 or newer. This attribute - * facilitates v2 signature stripping detection. - * - *

The attribute contains a comma-separated set of signature scheme IDs. - */ - public static final String SF_ATTRIBUTE_ANDROID_APK_SIGNED_NAME = "X-Android-APK-Signed"; - public static final String SF_ATTRIBUTE_ANDROID_APK_SIGNED_VALUE = "2"; - - private static final int CONTENT_DIGEST_CHUNKED_SHA256 = 0; - private static final int CONTENT_DIGEST_CHUNKED_SHA512 = 1; - - private static final int CONTENT_DIGESTED_CHUNK_MAX_SIZE_BYTES = 1024 * 1024; - - private static final byte[] APK_SIGNING_BLOCK_MAGIC = - new byte[] { - 0x41, 0x50, 0x4b, 0x20, 0x53, 0x69, 0x67, 0x20, - 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x20, 0x34, 0x32, - }; - private static final int APK_SIGNATURE_SCHEME_V2_BLOCK_ID = 0x7109871a; - - private ApkSignerV2() {} - - /** - * Signer configuration. - */ - public static final class SignerConfig { - /** Private key. */ - public PrivateKey privateKey; - - /** - * Certificates, with the first certificate containing the public key corresponding to - * {@link #privateKey}. - */ - public List certificates; - - /** - * List of signature algorithms with which to sign (see {@code SIGNATURE_...} constants). - */ - public List signatureAlgorithms; - } - - /** - * Signs the provided APK using APK Signature Scheme v2 and returns the signed APK as a list of - * consecutive chunks. - * - *

NOTE: To enable APK signature verifier to detect v2 signature stripping, header sections - * of META-INF/*.SF files of APK being signed must contain the - * {@code X-Android-APK-Signed: true} attribute. - * - * @param inputApk contents of the APK to be signed. The APK starts at the current position - * of the buffer and ends at the limit of the buffer. - * @param signerConfigs signer configurations, one for each signer. - * - * @throws ApkParseException if the APK cannot be parsed. - * @throws InvalidKeyException if a signing key is not suitable for this signature scheme or - * cannot be used in general. - * @throws SignatureException if an error occurs when computing digests of generating - * signatures. - */ - public static ByteBuffer[] sign( - ByteBuffer inputApk, - List signerConfigs) - throws ApkParseException, InvalidKeyException, SignatureException { - // Slice/create a view in the inputApk to make sure that: - // 1. inputApk is what's between position and limit of the original inputApk, and - // 2. changes to position, limit, and byte order are not reflected in the original. - ByteBuffer originalInputApk = inputApk; - inputApk = originalInputApk.slice(); - inputApk.order(ByteOrder.LITTLE_ENDIAN); - - // Locate ZIP End of Central Directory (EoCD), Central Directory, and check that Central - // Directory is immediately followed by the ZIP End of Central Directory. - int eocdOffset = ZipUtils.findZipEndOfCentralDirectoryRecord(inputApk); - if (eocdOffset == -1) { - throw new ApkParseException("Failed to locate ZIP End of Central Directory"); - } - if (ZipUtils.isZip64EndOfCentralDirectoryLocatorPresent(inputApk, eocdOffset)) { - throw new ApkParseException("ZIP64 format not supported"); - } - inputApk.position(eocdOffset); - long centralDirSizeLong = ZipUtils.getZipEocdCentralDirectorySizeBytes(inputApk); - if (centralDirSizeLong > Integer.MAX_VALUE) { - throw new ApkParseException( - "ZIP Central Directory size out of range: " + centralDirSizeLong); - } - int centralDirSize = (int) centralDirSizeLong; - long centralDirOffsetLong = ZipUtils.getZipEocdCentralDirectoryOffset(inputApk); - if (centralDirOffsetLong > Integer.MAX_VALUE) { - throw new ApkParseException( - "ZIP Central Directory offset in file out of range: " + centralDirOffsetLong); - } - int centralDirOffset = (int) centralDirOffsetLong; - int expectedEocdOffset = centralDirOffset + centralDirSize; - if (expectedEocdOffset < centralDirOffset) { - throw new ApkParseException( - "ZIP Central Directory extent too large. Offset: " + centralDirOffset - + ", size: " + centralDirSize); - } - if (eocdOffset != expectedEocdOffset) { - throw new ApkParseException( - "ZIP Central Directory not immeiately followed by ZIP End of" - + " Central Directory. CD end: " + expectedEocdOffset - + ", EoCD start: " + eocdOffset); - } - - // Create ByteBuffers holding the contents of everything before ZIP Central Directory, - // ZIP Central Directory, and ZIP End of Central Directory. - inputApk.clear(); - ByteBuffer beforeCentralDir = getByteBuffer(inputApk, centralDirOffset); - ByteBuffer centralDir = getByteBuffer(inputApk, eocdOffset - centralDirOffset); - // Create a copy of End of Central Directory because we'll need modify its contents later. - byte[] eocdBytes = new byte[inputApk.remaining()]; - inputApk.get(eocdBytes); - ByteBuffer eocd = ByteBuffer.wrap(eocdBytes); - eocd.order(inputApk.order()); - - // Figure which which digests to use for APK contents. - Set contentDigestAlgorithms = new HashSet<>(); - for (SignerConfig signerConfig : signerConfigs) { - for (int signatureAlgorithm : signerConfig.signatureAlgorithms) { - contentDigestAlgorithms.add( - getSignatureAlgorithmContentDigestAlgorithm(signatureAlgorithm)); - } - } - - // Compute digests of APK contents. - Map contentDigests; // digest algorithm ID -> digest - try { - contentDigests = - computeContentDigests( - contentDigestAlgorithms, - new ByteBuffer[] {beforeCentralDir, centralDir, eocd}); - } catch (DigestException e) { - throw new SignatureException("Failed to compute digests of APK", e); - } - - // Sign the digests and wrap the signatures and signer info into an APK Signing Block. - ByteBuffer apkSigningBlock = - ByteBuffer.wrap(generateApkSigningBlock(signerConfigs, contentDigests)); - - // Update Central Directory Offset in End of Central Directory Record. Central Directory - // follows the APK Signing Block and thus is shifted by the size of the APK Signing Block. - centralDirOffset += apkSigningBlock.remaining(); - eocd.clear(); - ZipUtils.setZipEocdCentralDirectoryOffset(eocd, centralDirOffset); - - // Follow the Java NIO pattern for ByteBuffer whose contents have been consumed. - originalInputApk.position(originalInputApk.limit()); - - // Reset positions (to 0) and limits (to capacity) in the ByteBuffers below to follow the - // Java NIO pattern for ByteBuffers which are ready for their contents to be read by caller. - // Contrary to the name, this does not clear the contents of these ByteBuffer. - beforeCentralDir.clear(); - centralDir.clear(); - eocd.clear(); - - // Insert APK Signing Block immediately before the ZIP Central Directory. - return new ByteBuffer[] { - beforeCentralDir, - apkSigningBlock, - centralDir, - eocd, - }; - } - - private static Map computeContentDigests( - Set digestAlgorithms, - ByteBuffer[] contents) throws DigestException { - // For each digest algorithm the result is computed as follows: - // 1. Each segment of contents is split into consecutive chunks of 1 MB in size. - // The final chunk will be shorter iff the length of segment is not a multiple of 1 MB. - // No chunks are produced for empty (zero length) segments. - // 2. The digest of each chunk is computed over the concatenation of byte 0xa5, the chunk's - // length in bytes (uint32 little-endian) and the chunk's contents. - // 3. The output digest is computed over the concatenation of the byte 0x5a, the number of - // chunks (uint32 little-endian) and the concatenation of digests of chunks of all - // segments in-order. - - int chunkCount = 0; - for (ByteBuffer input : contents) { - chunkCount += getChunkCount(input.remaining(), CONTENT_DIGESTED_CHUNK_MAX_SIZE_BYTES); - } - - final Map digestsOfChunks = new HashMap<>(digestAlgorithms.size()); - for (int digestAlgorithm : digestAlgorithms) { - int digestOutputSizeBytes = getContentDigestAlgorithmOutputSizeBytes(digestAlgorithm); - byte[] concatenationOfChunkCountAndChunkDigests = - new byte[5 + chunkCount * digestOutputSizeBytes]; - concatenationOfChunkCountAndChunkDigests[0] = 0x5a; - setUnsignedInt32LittleEngian( - chunkCount, concatenationOfChunkCountAndChunkDigests, 1); - digestsOfChunks.put(digestAlgorithm, concatenationOfChunkCountAndChunkDigests); - } - - int chunkIndex = 0; - byte[] chunkContentPrefix = new byte[5]; - chunkContentPrefix[0] = (byte) 0xa5; - // Optimization opportunity: digests of chunks can be computed in parallel. - for (ByteBuffer input : contents) { - while (input.hasRemaining()) { - int chunkSize = - Math.min(input.remaining(), CONTENT_DIGESTED_CHUNK_MAX_SIZE_BYTES); - final ByteBuffer chunk = getByteBuffer(input, chunkSize); - for (int digestAlgorithm : digestAlgorithms) { - String jcaAlgorithmName = - getContentDigestAlgorithmJcaDigestAlgorithm(digestAlgorithm); - MessageDigest md; - try { - md = MessageDigest.getInstance(jcaAlgorithmName); - } catch (NoSuchAlgorithmException e) { - throw new DigestException( - jcaAlgorithmName + " MessageDigest not supported", e); - } - // Reset position to 0 and limit to capacity. Position would've been modified - // by the preceding iteration of this loop. NOTE: Contrary to the method name, - // this does not modify the contents of the chunk. - chunk.clear(); - setUnsignedInt32LittleEngian(chunk.remaining(), chunkContentPrefix, 1); - md.update(chunkContentPrefix); - md.update(chunk); - byte[] concatenationOfChunkCountAndChunkDigests = - digestsOfChunks.get(digestAlgorithm); - int expectedDigestSizeBytes = - getContentDigestAlgorithmOutputSizeBytes(digestAlgorithm); - int actualDigestSizeBytes = - md.digest( - concatenationOfChunkCountAndChunkDigests, - 5 + chunkIndex * expectedDigestSizeBytes, - expectedDigestSizeBytes); - if (actualDigestSizeBytes != expectedDigestSizeBytes) { - throw new DigestException( - "Unexpected output size of " + md.getAlgorithm() - + " digest: " + actualDigestSizeBytes); - } - } - chunkIndex++; - } - } - - Map result = new HashMap<>(digestAlgorithms.size()); - for (Map.Entry entry : digestsOfChunks.entrySet()) { - int digestAlgorithm = entry.getKey(); - byte[] concatenationOfChunkCountAndChunkDigests = entry.getValue(); - String jcaAlgorithmName = getContentDigestAlgorithmJcaDigestAlgorithm(digestAlgorithm); - MessageDigest md; - try { - md = MessageDigest.getInstance(jcaAlgorithmName); - } catch (NoSuchAlgorithmException e) { - throw new DigestException(jcaAlgorithmName + " MessageDigest not supported", e); - } - result.put(digestAlgorithm, md.digest(concatenationOfChunkCountAndChunkDigests)); - } - return result; - } - - private static int getChunkCount(int inputSize, int chunkSize) { - return (inputSize + chunkSize - 1) / chunkSize; - } - - private static void setUnsignedInt32LittleEngian(int value, byte[] result, int offset) { - result[offset] = (byte) (value & 0xff); - result[offset + 1] = (byte) ((value >> 8) & 0xff); - result[offset + 2] = (byte) ((value >> 16) & 0xff); - result[offset + 3] = (byte) ((value >> 24) & 0xff); - } - - private static byte[] generateApkSigningBlock( - List signerConfigs, - Map contentDigests) throws InvalidKeyException, SignatureException { - byte[] apkSignatureSchemeV2Block = - generateApkSignatureSchemeV2Block(signerConfigs, contentDigests); - return generateApkSigningBlock(apkSignatureSchemeV2Block); - } - - private static byte[] generateApkSigningBlock(byte[] apkSignatureSchemeV2Block) { - // FORMAT: - // uint64: size (excluding this field) - // repeated ID-value pairs: - // uint64: size (excluding this field) - // uint32: ID - // (size - 4) bytes: value - // uint64: size (same as the one above) - // uint128: magic - - int resultSize = - 8 // size - + 8 + 4 + apkSignatureSchemeV2Block.length // v2Block as ID-value pair - + 8 // size - + 16 // magic - ; - ByteBuffer result = ByteBuffer.allocate(resultSize); - result.order(ByteOrder.LITTLE_ENDIAN); - long blockSizeFieldValue = resultSize - 8; - result.putLong(blockSizeFieldValue); - - long pairSizeFieldValue = 4 + apkSignatureSchemeV2Block.length; - result.putLong(pairSizeFieldValue); - result.putInt(APK_SIGNATURE_SCHEME_V2_BLOCK_ID); - result.put(apkSignatureSchemeV2Block); - - result.putLong(blockSizeFieldValue); - result.put(APK_SIGNING_BLOCK_MAGIC); - - return result.array(); - } - - private static byte[] generateApkSignatureSchemeV2Block( - List signerConfigs, - Map contentDigests) throws InvalidKeyException, SignatureException { - // FORMAT: - // * length-prefixed sequence of length-prefixed signer blocks. - - List signerBlocks = new ArrayList<>(signerConfigs.size()); - int signerNumber = 0; - for (SignerConfig signerConfig : signerConfigs) { - signerNumber++; - byte[] signerBlock; - try { - signerBlock = generateSignerBlock(signerConfig, contentDigests); - } catch (InvalidKeyException e) { - throw new InvalidKeyException("Signer #" + signerNumber + " failed", e); - } catch (SignatureException e) { - throw new SignatureException("Signer #" + signerNumber + " failed", e); - } - signerBlocks.add(signerBlock); - } - - return encodeAsSequenceOfLengthPrefixedElements( - new byte[][] { - encodeAsSequenceOfLengthPrefixedElements(signerBlocks), - }); - } - - private static byte[] generateSignerBlock( - SignerConfig signerConfig, - Map contentDigests) throws InvalidKeyException, SignatureException { - if (signerConfig.certificates.isEmpty()) { - throw new SignatureException("No certificates configured for signer"); - } - PublicKey publicKey = signerConfig.certificates.get(0).getPublicKey(); - - byte[] encodedPublicKey = encodePublicKey(publicKey); - - V2SignatureSchemeBlock.SignedData signedData = new V2SignatureSchemeBlock.SignedData(); - try { - signedData.certificates = encodeCertificates(signerConfig.certificates); - } catch (CertificateEncodingException e) { - throw new SignatureException("Failed to encode certificates", e); - } - - List> digests = - new ArrayList<>(signerConfig.signatureAlgorithms.size()); - for (int signatureAlgorithm : signerConfig.signatureAlgorithms) { - int contentDigestAlgorithm = - getSignatureAlgorithmContentDigestAlgorithm(signatureAlgorithm); - byte[] contentDigest = contentDigests.get(contentDigestAlgorithm); - if (contentDigest == null) { - throw new RuntimeException( - getContentDigestAlgorithmJcaDigestAlgorithm(contentDigestAlgorithm) - + " content digest for " - + getSignatureAlgorithmJcaSignatureAlgorithm(signatureAlgorithm) - + " not computed"); - } - digests.add(Pair.create(signatureAlgorithm, contentDigest)); - } - signedData.digests = digests; - - V2SignatureSchemeBlock.Signer signer = new V2SignatureSchemeBlock.Signer(); - // FORMAT: - // * length-prefixed sequence of length-prefixed digests: - // * uint32: signature algorithm ID - // * length-prefixed bytes: digest of contents - // * length-prefixed sequence of certificates: - // * length-prefixed bytes: X.509 certificate (ASN.1 DER encoded). - // * length-prefixed sequence of length-prefixed additional attributes: - // * uint32: ID - // * (length - 4) bytes: value - signer.signedData = encodeAsSequenceOfLengthPrefixedElements(new byte[][] { - encodeAsSequenceOfLengthPrefixedPairsOfIntAndLengthPrefixedBytes(signedData.digests), - encodeAsSequenceOfLengthPrefixedElements(signedData.certificates), - // additional attributes - new byte[0], - }); - signer.publicKey = encodedPublicKey; - signer.signatures = new ArrayList<>(); - for (int signatureAlgorithm : signerConfig.signatureAlgorithms) { - Pair signatureParams = - getSignatureAlgorithmJcaSignatureAlgorithm(signatureAlgorithm); - String jcaSignatureAlgorithm = signatureParams.getFirst(); - AlgorithmParameterSpec jcaSignatureAlgorithmParams = signatureParams.getSecond(); - byte[] signatureBytes; - try { - Signature signature = Signature.getInstance(jcaSignatureAlgorithm); - signature.initSign(signerConfig.privateKey); - if (jcaSignatureAlgorithmParams != null) { - signature.setParameter(jcaSignatureAlgorithmParams); - } - signature.update(signer.signedData); - signatureBytes = signature.sign(); - } catch (InvalidKeyException e) { - throw new InvalidKeyException("Failed sign using " + jcaSignatureAlgorithm, e); - } catch (NoSuchAlgorithmException | InvalidAlgorithmParameterException - | SignatureException e) { - throw new SignatureException("Failed sign using " + jcaSignatureAlgorithm, e); - } - - try { - Signature signature = Signature.getInstance(jcaSignatureAlgorithm); - signature.initVerify(publicKey); - if (jcaSignatureAlgorithmParams != null) { - signature.setParameter(jcaSignatureAlgorithmParams); - } - signature.update(signer.signedData); - if (!signature.verify(signatureBytes)) { - throw new SignatureException("Signature did not verify"); - } - } catch (InvalidKeyException e) { - throw new InvalidKeyException("Failed to verify generated " + jcaSignatureAlgorithm - + " signature using public key from certificate", e); - } catch (NoSuchAlgorithmException | InvalidAlgorithmParameterException - | SignatureException e) { - throw new SignatureException("Failed to verify generated " + jcaSignatureAlgorithm - + " signature using public key from certificate", e); - } - - signer.signatures.add(Pair.create(signatureAlgorithm, signatureBytes)); - } - - // FORMAT: - // * length-prefixed signed data - // * length-prefixed sequence of length-prefixed signatures: - // * uint32: signature algorithm ID - // * length-prefixed bytes: signature of signed data - // * length-prefixed bytes: public key (X.509 SubjectPublicKeyInfo, ASN.1 DER encoded) - return encodeAsSequenceOfLengthPrefixedElements( - new byte[][] { - signer.signedData, - encodeAsSequenceOfLengthPrefixedPairsOfIntAndLengthPrefixedBytes( - signer.signatures), - signer.publicKey, - }); - } - - private static final class V2SignatureSchemeBlock { - private static final class Signer { - public byte[] signedData; - public List> signatures; - public byte[] publicKey; - } - - private static final class SignedData { - public List> digests; - public List certificates; - } - } - - private static byte[] encodePublicKey(PublicKey publicKey) throws InvalidKeyException { - byte[] encodedPublicKey = null; - if ("X.509".equals(publicKey.getFormat())) { - encodedPublicKey = publicKey.getEncoded(); - } - if (encodedPublicKey == null) { - try { - encodedPublicKey = - KeyFactory.getInstance(publicKey.getAlgorithm()) - .getKeySpec(publicKey, X509EncodedKeySpec.class) - .getEncoded(); - } catch (NoSuchAlgorithmException | InvalidKeySpecException e) { - throw new InvalidKeyException( - "Failed to obtain X.509 encoded form of public key " + publicKey - + " of class " + publicKey.getClass().getName(), - e); - } - } - if ((encodedPublicKey == null) || (encodedPublicKey.length == 0)) { - throw new InvalidKeyException( - "Failed to obtain X.509 encoded form of public key " + publicKey - + " of class " + publicKey.getClass().getName()); - } - return encodedPublicKey; - } - - public static List encodeCertificates(List certificates) - throws CertificateEncodingException { - List result = new ArrayList<>(); - for (X509Certificate certificate : certificates) { - result.add(certificate.getEncoded()); - } - return result; - } - - private static byte[] encodeAsSequenceOfLengthPrefixedElements(List sequence) { - return encodeAsSequenceOfLengthPrefixedElements( - sequence.toArray(new byte[sequence.size()][])); - } - - private static byte[] encodeAsSequenceOfLengthPrefixedElements(byte[][] sequence) { - int payloadSize = 0; - for (byte[] element : sequence) { - payloadSize += 4 + element.length; - } - ByteBuffer result = ByteBuffer.allocate(payloadSize); - result.order(ByteOrder.LITTLE_ENDIAN); - for (byte[] element : sequence) { - result.putInt(element.length); - result.put(element); - } - return result.array(); - } - - private static byte[] encodeAsSequenceOfLengthPrefixedPairsOfIntAndLengthPrefixedBytes( - List> sequence) { - int resultSize = 0; - for (Pair element : sequence) { - resultSize += 12 + element.getSecond().length; - } - ByteBuffer result = ByteBuffer.allocate(resultSize); - result.order(ByteOrder.LITTLE_ENDIAN); - for (Pair element : sequence) { - byte[] second = element.getSecond(); - result.putInt(8 + second.length); - result.putInt(element.getFirst()); - result.putInt(second.length); - result.put(second); - } - return result.array(); - } - - /** - * Relative get method for reading {@code size} number of bytes from the current - * position of this buffer. - * - *

This method reads the next {@code size} bytes at this buffer's current position, - * returning them as a {@code ByteBuffer} with start set to 0, limit and capacity set to - * {@code size}, byte order set to this buffer's byte order; and then increments the position by - * {@code size}. - */ - private static ByteBuffer getByteBuffer(ByteBuffer source, int size) { - if (size < 0) { - throw new IllegalArgumentException("size: " + size); - } - int originalLimit = source.limit(); - int position = source.position(); - int limit = position + size; - if ((limit < position) || (limit > originalLimit)) { - throw new BufferUnderflowException(); - } - source.limit(limit); - try { - ByteBuffer result = source.slice(); - result.order(source.order()); - source.position(limit); - return result; - } finally { - source.limit(originalLimit); - } - } - - private static Pair - getSignatureAlgorithmJcaSignatureAlgorithm(int sigAlgorithm) { - switch (sigAlgorithm) { - case SIGNATURE_RSA_PSS_WITH_SHA256: - return Pair.create( - "SHA256withRSA/PSS", - new PSSParameterSpec( - "SHA-256", "MGF1", MGF1ParameterSpec.SHA256, 256 / 8, 1)); - case SIGNATURE_RSA_PSS_WITH_SHA512: - return Pair.create( - "SHA512withRSA/PSS", - new PSSParameterSpec( - "SHA-512", "MGF1", MGF1ParameterSpec.SHA512, 512 / 8, 1)); - case SIGNATURE_RSA_PKCS1_V1_5_WITH_SHA256: - return Pair.create("SHA256withRSA", null); - case SIGNATURE_RSA_PKCS1_V1_5_WITH_SHA512: - return Pair.create("SHA512withRSA", null); - case SIGNATURE_ECDSA_WITH_SHA256: - return Pair.create("SHA256withECDSA", null); - case SIGNATURE_ECDSA_WITH_SHA512: - return Pair.create("SHA512withECDSA", null); - case SIGNATURE_DSA_WITH_SHA256: - return Pair.create("SHA256withDSA", null); - case SIGNATURE_DSA_WITH_SHA512: - return Pair.create("SHA512withDSA", null); - default: - throw new IllegalArgumentException( - "Unknown signature algorithm: 0x" - + Long.toHexString(sigAlgorithm & 0xffffffff)); - } - } - - private static int getSignatureAlgorithmContentDigestAlgorithm(int sigAlgorithm) { - switch (sigAlgorithm) { - case SIGNATURE_RSA_PSS_WITH_SHA256: - case SIGNATURE_RSA_PKCS1_V1_5_WITH_SHA256: - case SIGNATURE_ECDSA_WITH_SHA256: - case SIGNATURE_DSA_WITH_SHA256: - return CONTENT_DIGEST_CHUNKED_SHA256; - case SIGNATURE_RSA_PSS_WITH_SHA512: - case SIGNATURE_RSA_PKCS1_V1_5_WITH_SHA512: - case SIGNATURE_ECDSA_WITH_SHA512: - case SIGNATURE_DSA_WITH_SHA512: - return CONTENT_DIGEST_CHUNKED_SHA512; - default: - throw new IllegalArgumentException( - "Unknown signature algorithm: 0x" - + Long.toHexString(sigAlgorithm & 0xffffffff)); - } - } - - private static String getContentDigestAlgorithmJcaDigestAlgorithm(int digestAlgorithm) { - switch (digestAlgorithm) { - case CONTENT_DIGEST_CHUNKED_SHA256: - return "SHA-256"; - case CONTENT_DIGEST_CHUNKED_SHA512: - return "SHA-512"; - default: - throw new IllegalArgumentException( - "Unknown content digest algorithm: " + digestAlgorithm); - } - } - - private static int getContentDigestAlgorithmOutputSizeBytes(int digestAlgorithm) { - switch (digestAlgorithm) { - case CONTENT_DIGEST_CHUNKED_SHA256: - return 256 / 8; - case CONTENT_DIGEST_CHUNKED_SHA512: - return 512 / 8; - default: - throw new IllegalArgumentException( - "Unknown content digest algorithm: " + digestAlgorithm); - } - } - - /** - * Indicates that APK file could not be parsed. - */ - public static class ApkParseException extends Exception { - private static final long serialVersionUID = 1L; - - public ApkParseException(String message) { - super(message); - } - - public ApkParseException(String message, Throwable cause) { - super(message, cause); - } - } - - /** - * Pair of two elements. - */ - private static class Pair { - private final A mFirst; - private final B mSecond; - - private Pair(A first, B second) { - mFirst = first; - mSecond = second; - } - - public static Pair create(A first, B second) { - return new Pair<>(first, second); - } - - public A getFirst() { - return mFirst; - } - - public B getSecond() { - return mSecond; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((mFirst == null) ? 0 : mFirst.hashCode()); - result = prime * result + ((mSecond == null) ? 0 : mSecond.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - @SuppressWarnings("rawtypes") - Pair other = (Pair) obj; - if (mFirst == null) { - if (other.mFirst != null) { - return false; - } - } else if (!mFirst.equals(other.mFirst)) { - return false; - } - if (mSecond == null) { - return other.mSecond == null; - } else return mSecond.equals(other.mSecond); - } - } -} diff --git a/app/core/src/main/java/com/topjohnwu/magisk/core/signing/ByteArrayStream.java b/app/core/src/main/java/com/topjohnwu/magisk/core/signing/ByteArrayStream.java deleted file mode 100644 index 0454a5fef..000000000 --- a/app/core/src/main/java/com/topjohnwu/magisk/core/signing/ByteArrayStream.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.topjohnwu.magisk.core.signing; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.nio.ByteBuffer; - -public class ByteArrayStream extends ByteArrayOutputStream { - - public synchronized void readFrom(InputStream is) { - readFrom(is, Integer.MAX_VALUE); - } - - public synchronized void readFrom(InputStream is, int len) { - int read; - byte buffer[] = new byte[4096]; - try { - while ((read = is.read(buffer, 0, Math.min(len, buffer.length))) > 0) { - write(buffer, 0, read); - len -= read; - } - } catch (IOException e) { - e.printStackTrace(); - } - } - - public ByteArrayInputStream getInputStream() { - return new ByteArrayInputStream(buf, 0, count); - } - - public ByteBuffer toByteBuffer() { - return ByteBuffer.wrap(buf, 0, count); - } -} diff --git a/app/core/src/main/java/com/topjohnwu/magisk/core/signing/JarMap.java b/app/core/src/main/java/com/topjohnwu/magisk/core/signing/JarMap.java deleted file mode 100644 index a1f528a4f..000000000 --- a/app/core/src/main/java/com/topjohnwu/magisk/core/signing/JarMap.java +++ /dev/null @@ -1,166 +0,0 @@ -package com.topjohnwu.magisk.core.signing; - -import java.io.Closeable; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.Collections; -import java.util.Enumeration; -import java.util.LinkedHashMap; -import java.util.jar.JarEntry; -import java.util.jar.JarFile; -import java.util.jar.JarInputStream; -import java.util.jar.Manifest; -import java.util.zip.ZipEntry; -import java.util.zip.ZipFile; - -public abstract class JarMap implements Closeable { - - LinkedHashMap entryMap; - - public static JarMap open(File file, boolean verify) throws IOException { - return new FileMap(file, verify, ZipFile.OPEN_READ); - } - - public static JarMap open(InputStream is, boolean verify) throws IOException { - return new StreamMap(is, verify); - } - - public File getFile() { - return null; - } - - public abstract Manifest getManifest() throws IOException; - - public InputStream getInputStream(ZipEntry ze) throws IOException { - JarMapEntry e = getMapEntry(ze.getName()); - return e != null ? e.data.getInputStream() : null; - } - - public OutputStream getOutputStream(ZipEntry ze) { - if (entryMap == null) - entryMap = new LinkedHashMap<>(); - JarMapEntry e = new JarMapEntry(ze.getName()); - entryMap.put(ze.getName(), e); - return e.data; - } - - public byte[] getRawData(ZipEntry ze) throws IOException { - JarMapEntry e = getMapEntry(ze.getName()); - return e != null ? e.data.toByteArray() : null; - } - - public abstract Enumeration entries(); - - public final ZipEntry getEntry(String name) { - return getJarEntry(name); - } - - public JarEntry getJarEntry(String name) { - return getMapEntry(name); - } - - JarMapEntry getMapEntry(String name) { - JarMapEntry e = null; - if (entryMap != null) - e = (JarMapEntry) entryMap.get(name); - return e; - } - - private static class FileMap extends JarMap { - - private JarFile jarFile; - - FileMap(File file, boolean verify, int mode) throws IOException { - jarFile = new JarFile(file, verify, mode); - } - - @Override - public File getFile() { - return new File(jarFile.getName()); - } - - @Override - public Manifest getManifest() throws IOException { - return jarFile.getManifest(); - } - - @Override - public InputStream getInputStream(ZipEntry ze) throws IOException { - InputStream is = super.getInputStream(ze); - return is != null ? is : jarFile.getInputStream(ze); - } - - @Override - public byte[] getRawData(ZipEntry ze) throws IOException { - byte[] b = super.getRawData(ze); - if (b != null) - return b; - ByteArrayStream bytes = new ByteArrayStream(); - bytes.readFrom(jarFile.getInputStream(ze)); - return bytes.toByteArray(); - } - - @Override - public Enumeration entries() { - return jarFile.entries(); - } - - @Override - public JarEntry getJarEntry(String name) { - JarEntry e = getMapEntry(name); - return e != null ? e : jarFile.getJarEntry(name); - } - - @Override - public void close() throws IOException { - jarFile.close(); - } - } - - private static class StreamMap extends JarMap { - - private JarInputStream jis; - - StreamMap(InputStream is, boolean verify) throws IOException { - jis = new JarInputStream(is, verify); - entryMap = new LinkedHashMap<>(); - JarEntry entry; - while ((entry = jis.getNextJarEntry()) != null) { - entryMap.put(entry.getName(), new JarMapEntry(entry, jis)); - } - } - - @Override - public Manifest getManifest() { - return jis.getManifest(); - } - - @Override - public Enumeration entries() { - return Collections.enumeration(entryMap.values()); - } - - @Override - public void close() throws IOException { - jis.close(); - } - } - - private static class JarMapEntry extends JarEntry { - - ByteArrayStream data; - - JarMapEntry(JarEntry je, InputStream is) { - super(je); - data = new ByteArrayStream(); - data.readFrom(is); - } - - JarMapEntry(String s) { - super(s); - data = new ByteArrayStream(); - } - } -} diff --git a/app/core/src/main/java/com/topjohnwu/magisk/core/signing/SignApk.java b/app/core/src/main/java/com/topjohnwu/magisk/core/signing/SignApk.java deleted file mode 100644 index bbe8cb64c..000000000 --- a/app/core/src/main/java/com/topjohnwu/magisk/core/signing/SignApk.java +++ /dev/null @@ -1,566 +0,0 @@ -package com.topjohnwu.magisk.core.signing; - -import org.bouncycastle.asn1.ASN1Encoding; -import org.bouncycastle.asn1.ASN1InputStream; -import org.bouncycastle.asn1.ASN1OutputStream; -import org.bouncycastle.cert.jcajce.JcaCertStore; -import org.bouncycastle.cms.CMSException; -import org.bouncycastle.cms.CMSProcessableByteArray; -import org.bouncycastle.cms.CMSSignedData; -import org.bouncycastle.cms.CMSSignedDataGenerator; -import org.bouncycastle.cms.CMSTypedData; -import org.bouncycastle.cms.jcajce.JcaSignerInfoGeneratorBuilder; -import org.bouncycastle.operator.ContentSigner; -import org.bouncycastle.operator.OperatorCreationException; -import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder; -import org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder; -import org.bouncycastle.util.encoders.Base64; - -import java.io.ByteArrayOutputStream; -import java.io.FilterOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.PrintStream; -import java.nio.ByteBuffer; -import java.security.DigestOutputStream; -import java.security.GeneralSecurityException; -import java.security.InvalidKeyException; -import java.security.MessageDigest; -import java.security.PrivateKey; -import java.security.PublicKey; -import java.security.cert.CertificateEncodingException; -import java.security.cert.X509Certificate; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Enumeration; -import java.util.Iterator; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.TimeZone; -import java.util.TreeMap; -import java.util.jar.Attributes; -import java.util.jar.JarEntry; -import java.util.jar.JarFile; -import java.util.jar.JarOutputStream; -import java.util.jar.Manifest; -import java.util.regex.Pattern; - -/* - * Modified from AOSP - * https://android.googlesource.com/platform/build/+/refs/tags/android-7.1.2_r39/tools/signapk/src/com/android/signapk/SignApk.java - * */ - -public class SignApk { - private static final String CERT_SF_NAME = "META-INF/CERT.SF"; - private static final String CERT_SIG_NAME = "META-INF/CERT.%s"; - private static final String CERT_SF_MULTI_NAME = "META-INF/CERT%d.SF"; - private static final String CERT_SIG_MULTI_NAME = "META-INF/CERT%d.%s"; - - // bitmasks for which hash algorithms we need the manifest to include. - private static final int USE_SHA1 = 1; - private static final int USE_SHA256 = 2; - - /** - * Digest algorithm used when signing the APK using APK Signature Scheme v2. - */ - private static final String APK_SIG_SCHEME_V2_DIGEST_ALGORITHM = "SHA-256"; - // Files matching this pattern are not copied to the output. - private static final Pattern stripPattern = - Pattern.compile("^(META-INF/((.*)[.](SF|RSA|DSA|EC)|com/android/otacert))|(" + - Pattern.quote(JarFile.MANIFEST_NAME) + ")$"); - - /** - * Return one of USE_SHA1 or USE_SHA256 according to the signature - * algorithm specified in the cert. - */ - private static int getDigestAlgorithm(X509Certificate cert) { - String sigAlg = cert.getSigAlgName().toUpperCase(Locale.US); - if ("SHA1WITHRSA".equals(sigAlg) || "MD5WITHRSA".equals(sigAlg)) { - return USE_SHA1; - } else if (sigAlg.startsWith("SHA256WITH")) { - return USE_SHA256; - } else { - throw new IllegalArgumentException("unsupported signature algorithm \"" + sigAlg + - "\" in cert [" + cert.getSubjectDN()); - } - } - - /** - * Returns the expected signature algorithm for this key type. - */ - private static String getSignatureAlgorithm(X509Certificate cert) { - String keyType = cert.getPublicKey().getAlgorithm().toUpperCase(Locale.US); - if ("RSA".equalsIgnoreCase(keyType)) { - if (getDigestAlgorithm(cert) == USE_SHA256) { - return "SHA256withRSA"; - } else { - return "SHA1withRSA"; - } - } else if ("EC".equalsIgnoreCase(keyType)) { - return "SHA256withECDSA"; - } else { - throw new IllegalArgumentException("unsupported key type: " + keyType); - } - } - - /** - * Add the hash(es) of every file to the manifest, creating it if - * necessary. - */ - private static Manifest addDigestsToManifest(JarMap jar, int hashes) - throws IOException, GeneralSecurityException { - Manifest input = jar.getManifest(); - Manifest output = new Manifest(); - Attributes main = output.getMainAttributes(); - if (input != null) { - main.putAll(input.getMainAttributes()); - } else { - main.putValue("Manifest-Version", "1.0"); - main.putValue("Created-By", "1.0 (Android SignApk)"); - } - - MessageDigest md_sha1 = null; - MessageDigest md_sha256 = null; - if ((hashes & USE_SHA1) != 0) { - md_sha1 = MessageDigest.getInstance("SHA1"); - } - if ((hashes & USE_SHA256) != 0) { - md_sha256 = MessageDigest.getInstance("SHA256"); - } - - byte[] buffer = new byte[4096]; - int num; - - // We sort the input entries by name, and add them to the - // output manifest in sorted order. We expect that the output - // map will be deterministic. - - TreeMap byName = new TreeMap<>(); - - for (Enumeration e = jar.entries(); e.hasMoreElements(); ) { - JarEntry entry = e.nextElement(); - byName.put(entry.getName(), entry); - } - - for (JarEntry entry : byName.values()) { - String name = entry.getName(); - if (!entry.isDirectory() && !stripPattern.matcher(name).matches()) { - InputStream data = jar.getInputStream(entry); - while ((num = data.read(buffer)) > 0) { - if (md_sha1 != null) md_sha1.update(buffer, 0, num); - if (md_sha256 != null) md_sha256.update(buffer, 0, num); - } - - Attributes attr = null; - if (input != null) attr = input.getAttributes(name); - attr = attr != null ? new Attributes(attr) : new Attributes(); - // Remove any previously computed digests from this entry's attributes. - for (Iterator i = attr.keySet().iterator(); i.hasNext(); ) { - Object key = i.next(); - if (!(key instanceof Attributes.Name)) { - continue; - } - String attributeNameLowerCase = - key.toString().toLowerCase(Locale.US); - if (attributeNameLowerCase.endsWith("-digest")) { - i.remove(); - } - } - // Add SHA-1 digest if requested - if (md_sha1 != null) { - attr.putValue("SHA1-Digest", - new String(Base64.encode(md_sha1.digest()), "ASCII")); - } - // Add SHA-256 digest if requested - if (md_sha256 != null) { - attr.putValue("SHA-256-Digest", - new String(Base64.encode(md_sha256.digest()), "ASCII")); - } - output.getEntries().put(name, attr); - } - } - - return output; - } - - /** - * Write a .SF file with a digest of the specified manifest. - */ - private static void writeSignatureFile(Manifest manifest, OutputStream out, - int hash) - throws IOException, GeneralSecurityException { - Manifest sf = new Manifest(); - Attributes main = sf.getMainAttributes(); - main.putValue("Signature-Version", "1.0"); - main.putValue("Created-By", "1.0 (Android SignApk)"); - // Add APK Signature Scheme v2 signature stripping protection. - // This attribute indicates that this APK is supposed to have been signed using one or - // more APK-specific signature schemes in addition to the standard JAR signature scheme - // used by this code. APK signature verifier should reject the APK if it does not - // contain a signature for the signature scheme the verifier prefers out of this set. - main.putValue( - ApkSignerV2.SF_ATTRIBUTE_ANDROID_APK_SIGNED_NAME, - ApkSignerV2.SF_ATTRIBUTE_ANDROID_APK_SIGNED_VALUE); - - MessageDigest md = MessageDigest.getInstance(hash == USE_SHA256 ? "SHA256" : "SHA1"); - PrintStream print = new PrintStream(new DigestOutputStream(new ByteArrayOutputStream(), md), - true, "UTF-8"); - - // Digest of the entire manifest - manifest.write(print); - print.flush(); - main.putValue(hash == USE_SHA256 ? "SHA-256-Digest-Manifest" : "SHA1-Digest-Manifest", - new String(Base64.encode(md.digest()), "ASCII")); - - Map entries = manifest.getEntries(); - for (Map.Entry entry : entries.entrySet()) { - // Digest of the manifest stanza for this entry. - print.print("Name: " + entry.getKey() + "\r\n"); - for (Map.Entry att : entry.getValue().entrySet()) { - print.print(att.getKey() + ": " + att.getValue() + "\r\n"); - } - print.print("\r\n"); - print.flush(); - - Attributes sfAttr = new Attributes(); - sfAttr.putValue(hash == USE_SHA256 ? "SHA-256-Digest" : "SHA1-Digest", - new String(Base64.encode(md.digest()), "ASCII")); - sf.getEntries().put(entry.getKey(), sfAttr); - } - - CountOutputStream cout = new CountOutputStream(out); - sf.write(cout); - - // A bug in the java.util.jar implementation of Android platforms - // up to version 1.6 will cause a spurious IOException to be thrown - // if the length of the signature file is a multiple of 1024 bytes. - // As a workaround, add an extra CRLF in this case. - if ((cout.size() % 1024) == 0) { - cout.write('\r'); - cout.write('\n'); - } - } - - /** - * Sign data and write the digital signature to 'out'. - */ - private static void writeSignatureBlock( - CMSTypedData data, X509Certificate publicKey, PrivateKey privateKey, OutputStream out) - throws IOException, - CertificateEncodingException, - OperatorCreationException, - CMSException { - ArrayList certList = new ArrayList<>(1); - certList.add(publicKey); - JcaCertStore certs = new JcaCertStore(certList); - - CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); - ContentSigner signer = new JcaContentSignerBuilder(getSignatureAlgorithm(publicKey)) - .build(privateKey); - gen.addSignerInfoGenerator( - new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().build()) - .setDirectSignature(true) - .build(signer, publicKey) - ); - gen.addCertificates(certs); - CMSSignedData sigData = gen.generate(data, false); - - try (ASN1InputStream asn1 = new ASN1InputStream(sigData.getEncoded())) { - ASN1OutputStream dos = ASN1OutputStream.create(out, ASN1Encoding.DER); - dos.writeObject(asn1.readObject()); - } - } - - /** - * Copy all the files in a manifest from input to output. We set - * the modification times in the output to a fixed time, so as to - * reduce variation in the output file and make incremental OTAs - * more efficient. - */ - private static void copyFiles(Manifest manifest, JarMap in, JarOutputStream out, - long timestamp, int defaultAlignment) throws IOException { - byte[] buffer = new byte[4096]; - int num; - - Map entries = manifest.getEntries(); - ArrayList names = new ArrayList<>(entries.keySet()); - Collections.sort(names); - - boolean firstEntry = true; - long offset = 0L; - - // We do the copy in two passes -- first copying all the - // entries that are STORED, then copying all the entries that - // have any other compression flag (which in practice means - // DEFLATED). This groups all the stored entries together at - // the start of the file and makes it easier to do alignment - // on them (since only stored entries are aligned). - - for (String name : names) { - JarEntry inEntry = in.getJarEntry(name); - JarEntry outEntry; - if (inEntry.getMethod() != JarEntry.STORED) continue; - // Preserve the STORED method of the input entry. - outEntry = new JarEntry(inEntry); - outEntry.setTime(timestamp); - // Discard comment and extra fields of this entry to - // simplify alignment logic below and for consistency with - // how compressed entries are handled later. - outEntry.setComment(null); - outEntry.setExtra(null); - - // 'offset' is the offset into the file at which we expect - // the file data to begin. This is the value we need to - // make a multiple of 'alignement'. - offset += JarFile.LOCHDR + outEntry.getName().length(); - if (firstEntry) { - // The first entry in a jar file has an extra field of - // four bytes that you can't get rid of; any extra - // data you specify in the JarEntry is appended to - // these forced four bytes. This is JAR_MAGIC in - // JarOutputStream; the bytes are 0xfeca0000. - offset += 4; - firstEntry = false; - } - int alignment = getStoredEntryDataAlignment(name, defaultAlignment); - if (alignment > 0 && (offset % alignment != 0)) { - // Set the "extra data" of the entry to between 1 and - // alignment-1 bytes, to make the file data begin at - // an aligned offset. - int needed = alignment - (int) (offset % alignment); - outEntry.setExtra(new byte[needed]); - offset += needed; - } - - out.putNextEntry(outEntry); - - InputStream data = in.getInputStream(inEntry); - while ((num = data.read(buffer)) > 0) { - out.write(buffer, 0, num); - offset += num; - } - out.flush(); - } - - // Copy all the non-STORED entries. We don't attempt to - // maintain the 'offset' variable past this point; we don't do - // alignment on these entries. - - for (String name : names) { - JarEntry inEntry = in.getJarEntry(name); - JarEntry outEntry; - if (inEntry.getMethod() == JarEntry.STORED) continue; - // Create a new entry so that the compressed len is recomputed. - outEntry = new JarEntry(name); - outEntry.setTime(timestamp); - out.putNextEntry(outEntry); - - InputStream data = in.getInputStream(inEntry); - while ((num = data.read(buffer)) > 0) { - out.write(buffer, 0, num); - } - out.flush(); - } - } - - /** - * Returns the multiple (in bytes) at which the provided {@code STORED} entry's data must start - * relative to start of file or {@code 0} if alignment of this entry's data is not important. - */ - private static int getStoredEntryDataAlignment(String entryName, int defaultAlignment) { - if (defaultAlignment <= 0) { - return 0; - } - - if (entryName.endsWith(".so")) { - // Align .so contents to memory page boundary to enable memory-mapped - // execution. - return 4096; - } else { - return defaultAlignment; - } - } - - private static void signFile(Manifest manifest, - X509Certificate[] publicKey, PrivateKey[] privateKey, - long timestamp, JarOutputStream outputJar) throws Exception { - // MANIFEST.MF - JarEntry je = new JarEntry(JarFile.MANIFEST_NAME); - je.setTime(timestamp); - outputJar.putNextEntry(je); - manifest.write(outputJar); - - int numKeys = publicKey.length; - for (int k = 0; k < numKeys; ++k) { - // CERT.SF / CERT#.SF - je = new JarEntry(numKeys == 1 ? CERT_SF_NAME : - (String.format(Locale.US, CERT_SF_MULTI_NAME, k))); - je.setTime(timestamp); - outputJar.putNextEntry(je); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - writeSignatureFile(manifest, baos, getDigestAlgorithm(publicKey[k])); - byte[] signedData = baos.toByteArray(); - outputJar.write(signedData); - - // CERT.{EC,RSA} / CERT#.{EC,RSA} - final String keyType = publicKey[k].getPublicKey().getAlgorithm(); - je = new JarEntry(numKeys == 1 ? (String.format(CERT_SIG_NAME, keyType)) : - (String.format(Locale.US, CERT_SIG_MULTI_NAME, k, keyType))); - je.setTime(timestamp); - outputJar.putNextEntry(je); - writeSignatureBlock(new CMSProcessableByteArray(signedData), - publicKey[k], privateKey[k], outputJar); - } - } - - /** - * Converts the provided lists of private keys, their X.509 certificates, and digest algorithms - * into a list of APK Signature Scheme v2 {@code SignerConfig} instances. - */ - private static List createV2SignerConfigs( - PrivateKey[] privateKeys, X509Certificate[] certificates, String[] digestAlgorithms) - throws InvalidKeyException { - if (privateKeys.length != certificates.length) { - throw new IllegalArgumentException( - "The number of private keys must match the number of certificates: " - + privateKeys.length + " vs" + certificates.length); - } - List result = new ArrayList<>(privateKeys.length); - for (int i = 0; i < privateKeys.length; i++) { - PrivateKey privateKey = privateKeys[i]; - X509Certificate certificate = certificates[i]; - PublicKey publicKey = certificate.getPublicKey(); - String keyAlgorithm = privateKey.getAlgorithm(); - if (!keyAlgorithm.equalsIgnoreCase(publicKey.getAlgorithm())) { - throw new InvalidKeyException( - "Key algorithm of private key #" + (i + 1) + " does not match key" - + " algorithm of public key #" + (i + 1) + ": " + keyAlgorithm - + " vs " + publicKey.getAlgorithm()); - } - ApkSignerV2.SignerConfig signerConfig = new ApkSignerV2.SignerConfig(); - signerConfig.privateKey = privateKey; - signerConfig.certificates = Collections.singletonList(certificate); - List signatureAlgorithms = new ArrayList<>(digestAlgorithms.length); - for (String digestAlgorithm : digestAlgorithms) { - try { - signatureAlgorithms.add(getV2SignatureAlgorithm(keyAlgorithm, digestAlgorithm)); - } catch (IllegalArgumentException e) { - throw new InvalidKeyException( - "Unsupported key and digest algorithm combination for signer #" - + (i + 1), e); - } - } - signerConfig.signatureAlgorithms = signatureAlgorithms; - result.add(signerConfig); - } - return result; - } - - private static int getV2SignatureAlgorithm(String keyAlgorithm, String digestAlgorithm) { - if ("SHA-256".equalsIgnoreCase(digestAlgorithm)) { - if ("RSA".equalsIgnoreCase(keyAlgorithm)) { - // Use RSASSA-PKCS1-v1_5 signature scheme instead of RSASSA-PSS to guarantee - // deterministic signatures which make life easier for OTA updates (fewer files - // changed when deterministic signature schemes are used). - return ApkSignerV2.SIGNATURE_RSA_PKCS1_V1_5_WITH_SHA256; - } else if ("EC".equalsIgnoreCase(keyAlgorithm)) { - return ApkSignerV2.SIGNATURE_ECDSA_WITH_SHA256; - } else if ("DSA".equalsIgnoreCase(keyAlgorithm)) { - return ApkSignerV2.SIGNATURE_DSA_WITH_SHA256; - } else { - throw new IllegalArgumentException("Unsupported key algorithm: " + keyAlgorithm); - } - } else if ("SHA-512".equalsIgnoreCase(digestAlgorithm)) { - if ("RSA".equalsIgnoreCase(keyAlgorithm)) { - // Use RSASSA-PKCS1-v1_5 signature scheme instead of RSASSA-PSS to guarantee - // deterministic signatures which make life easier for OTA updates (fewer files - // changed when deterministic signature schemes are used). - return ApkSignerV2.SIGNATURE_RSA_PKCS1_V1_5_WITH_SHA512; - } else if ("EC".equalsIgnoreCase(keyAlgorithm)) { - return ApkSignerV2.SIGNATURE_ECDSA_WITH_SHA512; - } else if ("DSA".equalsIgnoreCase(keyAlgorithm)) { - return ApkSignerV2.SIGNATURE_DSA_WITH_SHA512; - } else { - throw new IllegalArgumentException("Unsupported key algorithm: " + keyAlgorithm); - } - } else { - throw new IllegalArgumentException("Unsupported digest algorithm: " + digestAlgorithm); - } - } - - public static void sign(X509Certificate cert, PrivateKey key, - JarMap inputJar, OutputStream outputStream) throws Exception { - int alignment = 4; - int hashes = 0; - - X509Certificate[] publicKey = new X509Certificate[1]; - publicKey[0] = cert; - hashes |= getDigestAlgorithm(publicKey[0]); - - // Set all ZIP file timestamps to Jan 1 2009 00:00:00. - long timestamp = 1230768000000L; - // The Java ZipEntry API we're using converts milliseconds since epoch into MS-DOS - // timestamp using the current timezone. We thus adjust the milliseconds since epoch - // value to end up with MS-DOS timestamp of Jan 1 2009 00:00:00. - timestamp -= TimeZone.getDefault().getOffset(timestamp); - - PrivateKey[] privateKey = new PrivateKey[1]; - privateKey[0] = key; - - // Generate, in memory, an APK signed using standard JAR Signature Scheme. - ByteArrayStream v1SignedApkBuf = new ByteArrayStream(); - JarOutputStream outputJar = new JarOutputStream(v1SignedApkBuf); - // Use maximum compression for compressed entries because the APK lives forever on - // the system partition. - outputJar.setLevel(9); - Manifest manifest = addDigestsToManifest(inputJar, hashes); - copyFiles(manifest, inputJar, outputJar, timestamp, alignment); - signFile(manifest, publicKey, privateKey, timestamp, outputJar); - outputJar.close(); - ByteBuffer v1SignedApk = v1SignedApkBuf.toByteBuffer(); - - ByteBuffer[] outputChunks; - List signerConfigs = createV2SignerConfigs(privateKey, publicKey, - new String[]{APK_SIG_SCHEME_V2_DIGEST_ALGORITHM}); - outputChunks = ApkSignerV2.sign(v1SignedApk, signerConfigs); - - // This assumes outputChunks are array-backed. To avoid this assumption, the - // code could be rewritten to use FileChannel. - for (ByteBuffer outputChunk : outputChunks) { - outputStream.write(outputChunk.array(), - outputChunk.arrayOffset() + outputChunk.position(), outputChunk.remaining()); - outputChunk.position(outputChunk.limit()); - } - } - - /** - * Write to another stream and track how many bytes have been - * written. - */ - private static class CountOutputStream extends FilterOutputStream { - private int mCount; - - public CountOutputStream(OutputStream out) { - super(out); - mCount = 0; - } - - @Override - public void write(int b) throws IOException { - super.write(b); - mCount++; - } - - @Override - public void write(byte[] b, int off, int len) throws IOException { - super.write(b, off, len); - mCount += len; - } - - public int size() { - return mCount; - } - } -} diff --git a/app/core/src/main/java/com/topjohnwu/magisk/core/signing/ZipUtils.java b/app/core/src/main/java/com/topjohnwu/magisk/core/signing/ZipUtils.java deleted file mode 100644 index 2e92b7a6c..000000000 --- a/app/core/src/main/java/com/topjohnwu/magisk/core/signing/ZipUtils.java +++ /dev/null @@ -1,136 +0,0 @@ -package com.topjohnwu.magisk.core.signing; - -import java.nio.ByteBuffer; -import java.nio.ByteOrder; - -/** - * Assorted ZIP format helpers. - * - *

NOTE: Most helper methods operating on {@code ByteBuffer} instances expect that the byte - * order of these buffers is little-endian. - */ -public abstract class ZipUtils { - - private static final int ZIP_EOCD_REC_MIN_SIZE = 22; - private static final int ZIP_EOCD_REC_SIG = 0x06054b50; - private static final int ZIP_EOCD_CENTRAL_DIR_SIZE_FIELD_OFFSET = 12; - private static final int ZIP_EOCD_CENTRAL_DIR_OFFSET_FIELD_OFFSET = 16; - private static final int ZIP_EOCD_COMMENT_LENGTH_FIELD_OFFSET = 20; - - private static final int ZIP64_EOCD_LOCATOR_SIZE = 20; - private static final int ZIP64_EOCD_LOCATOR_SIG = 0x07064b50; - - private static final int UINT16_MAX_VALUE = 0xffff; - - private ZipUtils() { - } - - /** - * Returns the position at which ZIP End of Central Directory record starts in the provided - * buffer or {@code -1} if the record is not present. - * - *

NOTE: Byte order of {@code zipContents} must be little-endian. - */ - public static int findZipEndOfCentralDirectoryRecord(ByteBuffer zipContents) { - assertByteOrderLittleEndian(zipContents); - - // ZIP End of Central Directory (EOCD) record is located at the very end of the ZIP archive. - // The record can be identified by its 4-byte signature/magic which is located at the very - // beginning of the record. A complication is that the record is variable-length because of - // the comment field. - // The algorithm for locating the ZIP EOCD record is as follows. We search backwards from - // end of the buffer for the EOCD record signature. Whenever we find a signature, we check - // the candidate record's comment length is such that the remainder of the record takes up - // exactly the remaining bytes in the buffer. The search is bounded because the maximum - // size of the comment field is 65535 bytes because the field is an unsigned 16-bit number. - - int archiveSize = zipContents.capacity(); - if (archiveSize < ZIP_EOCD_REC_MIN_SIZE) { - return -1; - } - int maxCommentLength = Math.min(archiveSize - ZIP_EOCD_REC_MIN_SIZE, UINT16_MAX_VALUE); - int eocdWithEmptyCommentStartPosition = archiveSize - ZIP_EOCD_REC_MIN_SIZE; - for (int expectedCommentLength = 0; expectedCommentLength < maxCommentLength; expectedCommentLength++) { - int eocdStartPos = eocdWithEmptyCommentStartPosition - expectedCommentLength; - if (zipContents.getInt(eocdStartPos) == ZIP_EOCD_REC_SIG) { - int actualCommentLength = getUnsignedInt16(zipContents, eocdStartPos + ZIP_EOCD_COMMENT_LENGTH_FIELD_OFFSET); - if (actualCommentLength == expectedCommentLength) { - return eocdStartPos; - } - } - } - - return -1; - } - - /** - * Returns {@code true} if the provided buffer contains a ZIP64 End of Central Directory - * Locator. - * - *

NOTE: Byte order of {@code zipContents} must be little-endian. - */ - public static boolean isZip64EndOfCentralDirectoryLocatorPresent(ByteBuffer zipContents, int zipEndOfCentralDirectoryPosition) { - assertByteOrderLittleEndian(zipContents); - - // ZIP64 End of Central Directory Locator immediately precedes the ZIP End of Central - // Directory Record. - - int locatorPosition = zipEndOfCentralDirectoryPosition - ZIP64_EOCD_LOCATOR_SIZE; - if (locatorPosition < 0) { - return false; - } - - return zipContents.getInt(locatorPosition) == ZIP64_EOCD_LOCATOR_SIG; - } - - /** - * Returns the offset of the start of the ZIP Central Directory in the archive. - * - *

NOTE: Byte order of {@code zipEndOfCentralDirectory} must be little-endian. - */ - public static long getZipEocdCentralDirectoryOffset(ByteBuffer zipEndOfCentralDirectory) { - assertByteOrderLittleEndian(zipEndOfCentralDirectory); - return getUnsignedInt32(zipEndOfCentralDirectory, zipEndOfCentralDirectory.position() + ZIP_EOCD_CENTRAL_DIR_OFFSET_FIELD_OFFSET); - } - - /** - * Sets the offset of the start of the ZIP Central Directory in the archive. - * - *

NOTE: Byte order of {@code zipEndOfCentralDirectory} must be little-endian. - */ - public static void setZipEocdCentralDirectoryOffset(ByteBuffer zipEndOfCentralDirectory, long offset) { - assertByteOrderLittleEndian(zipEndOfCentralDirectory); - setUnsignedInt32(zipEndOfCentralDirectory, zipEndOfCentralDirectory.position() + ZIP_EOCD_CENTRAL_DIR_OFFSET_FIELD_OFFSET, offset); - } - - /** - * Returns the size (in bytes) of the ZIP Central Directory. - * - *

NOTE: Byte order of {@code zipEndOfCentralDirectory} must be little-endian. - */ - public static long getZipEocdCentralDirectorySizeBytes(ByteBuffer zipEndOfCentralDirectory) { - assertByteOrderLittleEndian(zipEndOfCentralDirectory); - return getUnsignedInt32(zipEndOfCentralDirectory, zipEndOfCentralDirectory.position() + ZIP_EOCD_CENTRAL_DIR_SIZE_FIELD_OFFSET); - } - - private static void assertByteOrderLittleEndian(ByteBuffer buffer) { - if (buffer.order() != ByteOrder.LITTLE_ENDIAN) { - throw new IllegalArgumentException("ByteBuffer byte order must be little endian"); - } - } - - private static int getUnsignedInt16(ByteBuffer buffer, int offset) { - return buffer.getShort(offset) & 0xffff; - } - - private static long getUnsignedInt32(ByteBuffer buffer, int offset) { - return buffer.getInt(offset) & 0xffffffffL; - } - - private static void setUnsignedInt32(ByteBuffer buffer, int offset, long value) { - if ((value < 0) || (value > 0xffffffffL)) { - throw new IllegalArgumentException("uint32 value of out range: " + value); - } - buffer.putInt(buffer.position() + offset, (int) value); - } -} diff --git a/app/core/src/main/java/com/topjohnwu/magisk/core/tasks/AppMigration.kt b/app/core/src/main/java/com/topjohnwu/magisk/core/tasks/AppMigration.kt deleted file mode 100644 index 8c78f5b12..000000000 --- a/app/core/src/main/java/com/topjohnwu/magisk/core/tasks/AppMigration.kt +++ /dev/null @@ -1,296 +0,0 @@ -package com.topjohnwu.magisk.core.tasks - -import android.app.Activity -import android.app.ActivityOptions -import android.content.Context -import android.content.Intent -import android.content.pm.PackageManager -import android.os.Build -import android.widget.Toast -import com.topjohnwu.magisk.StubApk -import com.topjohnwu.magisk.core.AppApkPath -import com.topjohnwu.magisk.core.BuildConfig.APP_PACKAGE_NAME -import com.topjohnwu.magisk.core.Config -import com.topjohnwu.magisk.core.Const -import com.topjohnwu.magisk.core.R -import com.topjohnwu.magisk.core.ktx.await -import com.topjohnwu.magisk.core.ktx.toast -import com.topjohnwu.magisk.core.ktx.writeTo -import com.topjohnwu.magisk.core.signing.JarMap -import com.topjohnwu.magisk.core.signing.SignApk -import com.topjohnwu.magisk.core.utils.AXML -import com.topjohnwu.magisk.core.utils.Keygen -import com.topjohnwu.magisk.utils.APKInstall -import com.topjohnwu.superuser.Shell -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.withContext -import timber.log.Timber -import java.io.File -import java.io.IOException -import java.io.OutputStream -import java.security.SecureRandom -import kotlin.random.asKotlinRandom - -object AppMigration { - - private const val ALPHA = "abcdefghijklmnopqrstuvwxyz" - private const val ALPHADOTS = "$ALPHA....." - private const val ANDROID_MANIFEST = "AndroidManifest.xml" - private const val TEST_PKG_NAME = "$APP_PACKAGE_NAME.test" - - // Some arbitrary limit - const val MAX_LABEL_LENGTH = 32 - const val PLACEHOLDER = "COMPONENT_PLACEHOLDER" - - private fun genPackageName(): String { - val random = SecureRandom() - val len = 5 + random.nextInt(15) - val builder = StringBuilder(len) - var next: Char - var prev = 0.toChar() - for (i in 0 until len) { - next = if (prev == '.' || i == 0 || i == len - 1) { - ALPHA[random.nextInt(ALPHA.length)] - } else { - ALPHADOTS[random.nextInt(ALPHADOTS.length)] - } - builder.append(next) - prev = next - } - if (!builder.contains('.')) { - // Pick a random index and set it as dot - val idx = random.nextInt(len - 2) - builder[idx + 1] = '.' - } - return builder.toString() - } - - private fun classNameGenerator() = sequence { - val c1 = mutableListOf() - val c2 = mutableListOf() - val c3 = mutableListOf() - val random = SecureRandom() - val kRandom = random.asKotlinRandom() - - fun chain(vararg iters: Iterable) = sequence { - iters.forEach { it.forEach { v -> yield(v) } } - } - - for (a in chain('a'..'z', 'A'..'Z')) { - if (a != 'a' && a != 'A') { - c1.add("$a") - } - for (b in chain('a'..'z', 'A'..'Z', '0'..'9')) { - c2.add("$a$b") - for (c in chain('a'..'z', 'A'..'Z', '0'..'9')) { - c3.add("$a$b$c") - } - } - } - - c1.shuffle(random) - c2.shuffle(random) - c3.shuffle(random) - - fun notJavaKeyword(name: String) = when (name) { - "do", "if", "for", "int", "new", "try" -> false - else -> true - } - - fun List.process() = asSequence().filter(::notJavaKeyword) - - val names = mutableListOf() - names.addAll(c1) - names.addAll(c2.process().take(30)) - names.addAll(c3.process().take(30)) - - while (true) { - val seg = 2 + random.nextInt(4) - val cls = StringBuilder() - for (i in 0 until seg) { - cls.append(names.random(kRandom)) - if (i != seg - 1) - cls.append('.') - } - // Old Android does not support capitalized package names - // Check Android 7.0.0 PackageParser#buildClassName - cls[0] = cls[0].lowercaseChar() - yield(cls.toString()) - } - }.distinct().iterator() - - private fun patch( - context: Context, - apk: File, out: OutputStream, - pkg: String, label: CharSequence - ): Boolean { - val pm = context.packageManager - val info = pm.getPackageArchiveInfo(apk.path, 0)?.applicationInfo ?: return false - val origLabel = info.nonLocalizedLabel.toString() - try { - JarMap.open(apk, true).use { jar -> - val je = jar.getJarEntry(ANDROID_MANIFEST) - val xml = AXML(jar.getRawData(je)) - val generator = classNameGenerator() - val p = xml.patchStrings { - when { - it.contains(APP_PACKAGE_NAME) -> it.replace(APP_PACKAGE_NAME, pkg) - it.contains(PLACEHOLDER) -> generator.next() - it == origLabel -> label.toString() - else -> it - } - } - if (!p) return false - - // Write apk changes - jar.getOutputStream(je).use { it.write(xml.bytes) } - val keys = Keygen() - SignApk.sign(keys.cert, keys.key, jar, out) - return true - } - } catch (e: Exception) { - Timber.e(e) - return false - } - } - - private fun patchTest(apk: File, out: File, pkg: String): Boolean { - try { - JarMap.open(apk, true).use { jar -> - val je = jar.getJarEntry(ANDROID_MANIFEST) - val xml = AXML(jar.getRawData(je)) - val p = xml.patchStrings { - when (it) { - APP_PACKAGE_NAME -> pkg - TEST_PKG_NAME -> "$pkg.test" - else -> it - } - } - if (!p) return false - - // Write apk changes - jar.getOutputStream(je).use { it.write(xml.bytes) } - val keys = Keygen() - out.outputStream().use { SignApk.sign(keys.cert, keys.key, jar, it) } - return true - } - } catch (e: Exception) { - Timber.e(e) - return false - } - } - - private fun launchApp(context: Context, pkg: String) { - val intent = context.packageManager.getLaunchIntentForPackage(pkg) ?: return - intent.putExtra(Const.Key.PREV_CONFIG, Config.toBundle()) - val options = ActivityOptions.makeBasic() - if (Build.VERSION.SDK_INT >= 34) { - options.setShareIdentityEnabled(true) - } - context.startActivity(intent, options.toBundle()) - if (context is Activity) { - context.finish() - } - } - - suspend fun patchAndHide(context: Context, label: String, pkg: String? = null): Boolean { - val stub = File(context.cacheDir, "stub.apk") - try { - context.assets.open("stub.apk").writeTo(stub) - } catch (e: IOException) { - Timber.e(e) - return false - } - - // Generate a new random signature and package name if needed - val pkg = pkg ?: genPackageName() - Config.keyStoreRaw = "" - - // Check and patch the test APK - try { - val info = context.packageManager.getApplicationInfo(TEST_PKG_NAME, 0) - val testApk = File(info.sourceDir) - val testRepack = File(context.cacheDir, "test.apk") - if (!patchTest(testApk, testRepack, pkg)) - return false - val cmd = "adb_pm_install $testRepack $pkg.test" - if (!Shell.cmd(cmd).exec().isSuccess) - return false - } catch (e: PackageManager.NameNotFoundException) { - } - - val repack = File(context.cacheDir, "patched.apk") - repack.outputStream().use { - if (!patch(context, stub, it, pkg, label)) - return false - } - - // Install and auto launch app - val cmd = "adb_pm_install $repack $pkg" - if (Shell.cmd(cmd).exec().isSuccess) { - Config.suManager = pkg - Shell.cmd("touch $AppApkPath").exec() - launchApp(context, pkg) - return true - } else { - return false - } - } - - @Suppress("DEPRECATION") - suspend fun hide(activity: Activity, label: String) { - val dialog = android.app.ProgressDialog(activity).apply { - setTitle(activity.getString(R.string.hide_app_title)) - isIndeterminate = true - setCancelable(false) - show() - } - val success = withContext(Dispatchers.IO) { - patchAndHide(activity, label) - } - if (!success) { - dialog.dismiss() - activity.toast(R.string.failure, Toast.LENGTH_LONG) - } - } - - suspend fun restoreApp(context: Context): Boolean { - val apk = StubApk.current(context) - val cmd = "adb_pm_install $apk $APP_PACKAGE_NAME" - if (Shell.cmd(cmd).await().isSuccess) { - Config.suManager = "" - Shell.cmd("touch $AppApkPath").exec() - launchApp(context, APP_PACKAGE_NAME) - return true - } - return false - } - - @Suppress("DEPRECATION") - suspend fun restore(activity: Activity) { - val dialog = android.app.ProgressDialog(activity).apply { - setTitle(activity.getString(R.string.restore_img_msg)) - isIndeterminate = true - setCancelable(false) - show() - } - if (!restoreApp(activity)) { - activity.toast(R.string.failure, Toast.LENGTH_LONG) - } - dialog.dismiss() - } - - suspend fun upgradeStub(context: Context, apk: File): Intent? { - val label = context.applicationInfo.nonLocalizedLabel - val pkg = context.packageName - val session = APKInstall.startSession(context) - return withContext(Dispatchers.IO) { - session.openStream(context).use { - if (!patch(context, apk, it, pkg, label)) { - return@withContext null - } - } - session.waitIntent() - } - } -} diff --git a/app/core/src/main/java/com/topjohnwu/magisk/core/utils/AXML.kt b/app/core/src/main/java/com/topjohnwu/magisk/core/utils/AXML.kt deleted file mode 100644 index f45a8f9fc..000000000 --- a/app/core/src/main/java/com/topjohnwu/magisk/core/utils/AXML.kt +++ /dev/null @@ -1,124 +0,0 @@ -package com.topjohnwu.magisk.core.utils - -import java.io.ByteArrayOutputStream -import java.nio.ByteBuffer -import java.nio.ByteOrder.LITTLE_ENDIAN -import java.nio.charset.Charset - -class AXML(b: ByteArray) { - - var bytes = b - private set - - companion object { - private const val CHUNK_SIZE_OFF = 4 - private const val STRING_INDICES_OFF = 7 * 4 - private val UTF_16LE = Charset.forName("UTF-16LE") - } - - /** - * String pool header: - * 0: 0x1C0001 - * 1: chunk size - * 2: number of strings - * 3: number of styles (assert as 0) - * 4: flags - * 5: offset to string data - * 6: offset to style data (assert as 0) - * - * Followed by an array of uint32_t with size = number of strings - * Each entry points to an offset into the string data - */ - fun patchStrings(mapFn: (String) -> String): Boolean { - val buffer = ByteBuffer.wrap(bytes).order(LITTLE_ENDIAN) - - fun findStringPool(): Int { - var offset = 8 - while (offset < bytes.size) { - if (buffer.getInt(offset) == 0x1C0001) - return offset - offset += buffer.getInt(offset + CHUNK_SIZE_OFF) - } - return -1 - } - - val start = findStringPool() - if (start < 0) - return false - - // Read header - buffer.position(start + 4) - val intBuf = buffer.asIntBuffer() - val size = intBuf.get() - val count = intBuf.get() - intBuf.get() - intBuf.get() - val dataOff = start + intBuf.get() - intBuf.get() - - val strList = ArrayList(count) - // Collect all strings in the pool - for (i in 0 until count) { - val off = dataOff + intBuf.get() - val len = buffer.getShort(off) - strList.add(String(bytes, off + 2, len * 2, UTF_16LE)) - } - - val strArr = strList.toTypedArray() - for (i in strArr.indices) { - strArr[i] = mapFn(strArr[i]) - } - - // Write everything before string data, will patch values later - val baos = RawByteStream() - baos.write(bytes, 0, dataOff) - - // Write string data - val offList = IntArray(count) - for (i in 0 until count) { - offList[i] = baos.size() - dataOff - val str = strArr[i] - baos.write(str.length.toShortBytes()) - baos.write(str.toByteArray(UTF_16LE)) - // Null terminate - baos.write(0) - baos.write(0) - } - baos.align() - - val sizeDiff = baos.size() - start - size - val newBuffer = ByteBuffer.wrap(baos.buffer).order(LITTLE_ENDIAN) - - // Patch XML size - newBuffer.putInt(CHUNK_SIZE_OFF, buffer.getInt(CHUNK_SIZE_OFF) + sizeDiff) - // Patch string pool size - newBuffer.putInt(start + CHUNK_SIZE_OFF, size + sizeDiff) - // Patch index table - newBuffer.position(start + STRING_INDICES_OFF) - val newIntBuf = newBuffer.asIntBuffer() - offList.forEach { newIntBuf.put(it) } - - // Write the rest of the chunks - val nextOff = start + size - baos.write(bytes, nextOff, bytes.size - nextOff) - - bytes = baos.toByteArray() - return true - } - - private fun Int.toShortBytes(): ByteArray { - val b = ByteBuffer.allocate(2).order(LITTLE_ENDIAN) - b.putShort(this.toShort()) - return b.array() - } - - private class RawByteStream : ByteArrayOutputStream() { - val buffer: ByteArray get() = buf - - fun align(alignment: Int = 4) { - val newCount = (count + alignment - 1) / alignment * alignment - for (i in 0 until (newCount - count)) - write(0) - } - } -} diff --git a/app/core/src/main/java/com/topjohnwu/magisk/core/utils/Keygen.kt b/app/core/src/main/java/com/topjohnwu/magisk/core/utils/Keygen.kt deleted file mode 100644 index 283a5c5a8..000000000 --- a/app/core/src/main/java/com/topjohnwu/magisk/core/utils/Keygen.kt +++ /dev/null @@ -1,80 +0,0 @@ -package com.topjohnwu.magisk.core.utils - -import android.util.Base64 -import android.util.Base64OutputStream -import com.topjohnwu.magisk.core.Config -import org.bouncycastle.asn1.x500.X500Name -import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo -import org.bouncycastle.cert.X509v3CertificateBuilder -import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter -import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder -import java.io.ByteArrayOutputStream -import java.math.BigInteger -import java.security.KeyPairGenerator -import java.security.KeyStore -import java.security.PrivateKey -import java.security.cert.X509Certificate -import java.util.Calendar -import java.util.Locale -import java.util.Random -import java.util.zip.GZIPInputStream -import java.util.zip.GZIPOutputStream - -private interface CertKeyProvider { - val cert: X509Certificate - val key: PrivateKey -} - -class Keygen : CertKeyProvider { - - companion object { - private const val ALIAS = "magisk" - private val PASSWORD get() = "magisk".toCharArray() - private const val DNAME = "C=US,ST=California,L=Mountain View,O=Google Inc.,OU=Android,CN=Android" - private const val BASE64_FLAG = Base64.NO_PADDING or Base64.NO_WRAP - } - - private val start = Calendar.getInstance().apply { add(Calendar.MONTH, -3) } - private val end = (start.clone() as Calendar).apply { add(Calendar.YEAR, 30) } - - private val ks = init() - override val cert = ks.getCertificate(ALIAS) as X509Certificate - override val key = ks.getKey(ALIAS, PASSWORD) as PrivateKey - - private fun init(): KeyStore { - val raw = Config.keyStoreRaw - val ks = KeyStore.getInstance("PKCS12") - if (raw.isEmpty()) { - ks.load(null) - } else { - GZIPInputStream(Base64.decode(raw, BASE64_FLAG).inputStream()).use { - ks.load(it, PASSWORD) - } - } - - // Keys already exist - if (ks.containsAlias(ALIAS)) - return ks - - // Generate new private key and certificate - val kp = KeyPairGenerator.getInstance("RSA").apply { initialize(4096) }.genKeyPair() - val dname = X500Name(DNAME) - val builder = X509v3CertificateBuilder( - dname, BigInteger(160, Random()), - start.time, end.time, Locale.ROOT, dname, - SubjectPublicKeyInfo.getInstance(kp.public.encoded) - ) - val signer = JcaContentSignerBuilder("SHA1WithRSA").build(kp.private) - val cert = JcaX509CertificateConverter().getCertificate(builder.build(signer)) - - // Store them into keystore - ks.setKeyEntry(ALIAS, kp.private, PASSWORD, arrayOf(cert)) - val bytes = ByteArrayOutputStream() - GZIPOutputStream(Base64OutputStream(bytes, BASE64_FLAG)).use { - ks.store(it, PASSWORD) - } - Config.keyStoreRaw = bytes.toString("UTF-8") - - return ks - } -} diff --git a/app/core/src/main/java/com/topjohnwu/magisk/test/Environment.kt b/app/core/src/main/java/com/topjohnwu/magisk/test/Environment.kt index 28476b9ab..84d32cc70 100644 --- a/app/core/src/main/java/com/topjohnwu/magisk/test/Environment.kt +++ b/app/core/src/main/java/com/topjohnwu/magisk/test/Environment.kt @@ -5,13 +5,11 @@ import android.os.Build import androidx.annotation.Keep import androidx.core.net.toUri import androidx.test.ext.junit.runners.AndroidJUnit4 -import com.topjohnwu.magisk.core.BuildConfig.APP_PACKAGE_NAME import com.topjohnwu.magisk.core.Const import com.topjohnwu.magisk.core.download.DownloadNotifier import com.topjohnwu.magisk.core.download.DownloadProcessor import com.topjohnwu.magisk.core.ktx.cachedFile import com.topjohnwu.magisk.core.model.module.LocalModule -import com.topjohnwu.magisk.core.tasks.AppMigration import com.topjohnwu.magisk.core.tasks.FlashZip import com.topjohnwu.magisk.core.tasks.MagiskInstaller import com.topjohnwu.magisk.core.utils.RootUtils @@ -269,28 +267,4 @@ class Environment : TestCommon { setupRemoveModule(root) setupUpgradeModule(root, update) } - - @Test - fun setupAppHide() { - runBlocking { - assertTrue( - "App hiding failed", - AppMigration.patchAndHide( - context = appContext, - label = "Settings", - pkg = "repackaged.$APP_PACKAGE_NAME" - ) - ) - } - } - - @Test - fun setupAppRestore() { - runBlocking { - assertTrue( - "App restoration failed", - AppMigration.restoreApp(appContext) - ) - } - } } diff --git a/app/core/src/main/res/values-ar/strings.xml b/app/core/src/main/res/values-ar/strings.xml index 5647c44b6..6c1ef089c 100644 --- a/app/core/src/main/res/values-ar/strings.xml +++ b/app/core/src/main/res/values-ar/strings.xml @@ -207,7 +207,6 @@ جارٍ التثبيت… تم! اكتمل تنفيذ إجراء %1$s فشل! - جارٍ إخفاء تطبيق Magisk… لا يوجد تطبيق لفتح الرابط إلغاء تثبيت كامل استعادة الملف diff --git a/app/core/src/main/res/values-ast/strings.xml b/app/core/src/main/res/values-ast/strings.xml index 6f51a8bd5..2b9ca69b0 100644 --- a/app/core/src/main/res/values-ast/strings.xml +++ b/app/core/src/main/res/values-ast/strings.xml @@ -178,7 +178,6 @@ Flaxando… ¡Fecho! Completóse l\'aición de: %1$s ¡Falló! - Escondiendo l\'aplicación Magisk… Nun s\'atopó nenguna aplicación p\'abrir l\'enllaz Desinstalar dafechu Restaurar les imáxenes diff --git a/app/core/src/main/res/values-az/strings.xml b/app/core/src/main/res/values-az/strings.xml index 92739a17a..a252959a4 100644 --- a/app/core/src/main/res/values-az/strings.xml +++ b/app/core/src/main/res/values-az/strings.xml @@ -183,7 +183,6 @@ Flashlanır... Bitdi! Alınmadı! - Magisk tətbiqi gizlədilir… Keçidi açaçaq tətbiq yoxdur Tamamilə sil Nüsxələri Bərpa et diff --git a/app/core/src/main/res/values-b+sr+Latn/strings.xml b/app/core/src/main/res/values-b+sr+Latn/strings.xml index 37f33e6ea..073b2e52c 100644 --- a/app/core/src/main/res/values-b+sr+Latn/strings.xml +++ b/app/core/src/main/res/values-b+sr+Latn/strings.xml @@ -208,7 +208,6 @@ Flešovanje… Završeno! Pokretanje akcije %1$s završeno Neuspešno! - Skrivanje Magisk aplikacije… Nije pronađena aplikacija za otvaranje linka Kompletna deinstalacija Povrati slike diff --git a/app/core/src/main/res/values-be/strings.xml b/app/core/src/main/res/values-be/strings.xml index c1bef80bd..5d387b7d4 100644 --- a/app/core/src/main/res/values-be/strings.xml +++ b/app/core/src/main/res/values-be/strings.xml @@ -151,7 +151,6 @@ Усталёўка… Завершана! Не атрымалася - Хаванне праграмы Magisk… Праграмы для адкрыцця спасылкі не знойдзена Поўнае выдаленне Аднавіць раздзелы diff --git a/app/core/src/main/res/values-bg/strings.xml b/app/core/src/main/res/values-bg/strings.xml index f4c5c75e0..2d3170939 100644 --- a/app/core/src/main/res/values-bg/strings.xml +++ b/app/core/src/main/res/values-bg/strings.xml @@ -181,7 +181,6 @@ Инсталиране… Готово! Грешка! - Скриване на приложението на Magisk… Не е намерено приложение, с което препратката да бъде отворена Премахване Възстановяване на образи diff --git a/app/core/src/main/res/values-bn/strings.xml b/app/core/src/main/res/values-bn/strings.xml index 9ca806bc4..464ca2890 100644 --- a/app/core/src/main/res/values-bn/strings.xml +++ b/app/core/src/main/res/values-bn/strings.xml @@ -178,7 +178,6 @@ ঝলকানি… সম্পন্ন! ব্যর্থ হয়েছে! - ম্যাজিস্ক অ্যাপটি লুকিয়ে রাখছে… লিঙ্ক খোলার জন্য কোনো অ্যাপ পাওয়া যায়নি সম্পূর্ণ আনইনস্টল করুন ছবি পুনরুদ্ধার করুন diff --git a/app/core/src/main/res/values-ca/strings.xml b/app/core/src/main/res/values-ca/strings.xml index 6cf163799..ac3199a3e 100644 --- a/app/core/src/main/res/values-ca/strings.xml +++ b/app/core/src/main/res/values-ca/strings.xml @@ -165,7 +165,6 @@ Arranjament… Fet! Fallit - Amagant Magisk Manager… No s\'ha trobat una aplicació per obrir l\'enllaç Desinstal·lació completa Restaura imatges diff --git a/app/core/src/main/res/values-cs/strings.xml b/app/core/src/main/res/values-cs/strings.xml index 5b4a5825f..a56a087b0 100644 --- a/app/core/src/main/res/values-cs/strings.xml +++ b/app/core/src/main/res/values-cs/strings.xml @@ -203,7 +203,6 @@ Flashuji… Dokončeno! Akce %1$s byla dokončena Nepodařilo se! - Skrývám aplikaci Magisk… Nebyla nalezena žádná aplikace pro otevření odkazu Kompletní odinstalace Obnovit obrazy diff --git a/app/core/src/main/res/values-de/strings.xml b/app/core/src/main/res/values-de/strings.xml index b44cd42b0..5c459378d 100644 --- a/app/core/src/main/res/values-de/strings.xml +++ b/app/core/src/main/res/values-de/strings.xml @@ -187,7 +187,6 @@ Flashen … Fertig! Fehlgeschlagen - Magisk-App verstecken … Keine App zum öffnen des Links gefunden Vollständig deinstallieren Image wiederherstellen diff --git a/app/core/src/main/res/values-el/strings.xml b/app/core/src/main/res/values-el/strings.xml index 08ce7b02b..0071f3aa6 100644 --- a/app/core/src/main/res/values-el/strings.xml +++ b/app/core/src/main/res/values-el/strings.xml @@ -179,7 +179,6 @@ Προγραμματισμός σε εξέλιξη Ολοκληρώθηκε Αποτυχία - Απόκρυψη της εφαρμογής Magisk… Δεν βρέθηκε εφαρμογή για άνοιγμα του συνδέσμου Πλήρης απεγκατάσταση Επαναφορά Images diff --git a/app/core/src/main/res/values-es/strings.xml b/app/core/src/main/res/values-es/strings.xml index a575e1dd1..9eda30451 100644 --- a/app/core/src/main/res/values-es/strings.xml +++ b/app/core/src/main/res/values-es/strings.xml @@ -183,7 +183,6 @@ Flasheando… ¡Listo! ¡Ocurrió un error! - Ocultando la app de Magisk… No se encontró ninguna app que pueda abrir este enlace Desinstalación completa Solo restaurar las imágenes diff --git a/app/core/src/main/res/values-et/strings.xml b/app/core/src/main/res/values-et/strings.xml index 2b2f72057..519891e93 100644 --- a/app/core/src/main/res/values-et/strings.xml +++ b/app/core/src/main/res/values-et/strings.xml @@ -174,7 +174,6 @@ Välgutamine… Valmis! Ebaõnnestus - Magiski rakenduse peitmine… Lingi avamiseks sobivat rakendust ei leitud. Täielik eemaldus Taasta tõmmised diff --git a/app/core/src/main/res/values-fa/strings.xml b/app/core/src/main/res/values-fa/strings.xml index 9ddcd6ab4..5f96c12b7 100644 --- a/app/core/src/main/res/values-fa/strings.xml +++ b/app/core/src/main/res/values-fa/strings.xml @@ -190,7 +190,6 @@ ر حال فلش کردن… تمام! انجام عملیات %1$s به پایان رسید ناموفق - در حال مخفی کردن برنامه Magisk… هیچ برنامه ای برای باز کردن لینک یافت نشد کامل کردن حذف بازیابی تصاویر diff --git a/app/core/src/main/res/values-fr/strings.xml b/app/core/src/main/res/values-fr/strings.xml index 5e39f0747..57d08310c 100644 --- a/app/core/src/main/res/values-fr/strings.xml +++ b/app/core/src/main/res/values-fr/strings.xml @@ -190,7 +190,6 @@ Écriture en mémoire Flash… Terminé ! Erreur - Masquage de l’application Magisk… Aucune application permettant d’ouvrir le lien n’a été trouvée Désinstallation complète Restauration des images diff --git a/app/core/src/main/res/values-hi/strings.xml b/app/core/src/main/res/values-hi/strings.xml index 9d6e081aa..dd1b6d5ff 100644 --- a/app/core/src/main/res/values-hi/strings.xml +++ b/app/core/src/main/res/values-hi/strings.xml @@ -179,7 +179,6 @@ फ़्लैश हो रहा है... सफल हुआ! असफल हुआ ! - मैजिस्क ऐप अब छिप रहा है… लिंक खोलने के लिए कोई एप्लिकेशन नहीं मिला पूर्ण रूप से अनइंस्टॉल करें इमेज रिस्टोर करें diff --git a/app/core/src/main/res/values-hn/strings.xml b/app/core/src/main/res/values-hn/strings.xml index bc96d9a4d..cf5a9c79d 100644 --- a/app/core/src/main/res/values-hn/strings.xml +++ b/app/core/src/main/res/values-hn/strings.xml @@ -190,7 +190,6 @@ Flash ho raha hai… Ho gaya! %1$s ka action complete ho gaya Fail ho gaya! - Magisk app ko chhupa rahe hain… Link kholne ke liye koi app nahi mila Sab kuch uninstall karo Images restore karo diff --git a/app/core/src/main/res/values-hu/strings.xml b/app/core/src/main/res/values-hu/strings.xml index 9af9b7e2d..900a8b60e 100644 --- a/app/core/src/main/res/values-hu/strings.xml +++ b/app/core/src/main/res/values-hu/strings.xml @@ -179,7 +179,6 @@ Flashing… Kész! Nem sikerült! - A Magisk app elrejtése… Nem található alkalmazás a link megnyitásához Teljes eltávolítás Image-ek visszaállítása diff --git a/app/core/src/main/res/values-in/strings.xml b/app/core/src/main/res/values-in/strings.xml index 922f5328a..2b7db39d5 100644 --- a/app/core/src/main/res/values-in/strings.xml +++ b/app/core/src/main/res/values-in/strings.xml @@ -206,7 +206,6 @@ Selesai! Aksi %1$s selesai Gagal! - Menyembunyikan aplikasi Magisk… Tidak ditemukan aplikasi untuk membuka tautan Pencopotan penuh Pulihkan image diff --git a/app/core/src/main/res/values-it/strings.xml b/app/core/src/main/res/values-it/strings.xml index 132c194d8..4110cd020 100644 --- a/app/core/src/main/res/values-it/strings.xml +++ b/app/core/src/main/res/values-it/strings.xml @@ -209,7 +209,6 @@ Flash in corso… Completato! Azione di %1$s completata Fallito - Sto nascondendo l\'app di Magisk… Nessuna app disponibile per aprire il link Disinstalla completamente Ripristina immagini diff --git a/app/core/src/main/res/values-iw/strings.xml b/app/core/src/main/res/values-iw/strings.xml index 8ca35ed91..c4b3b46e3 100644 --- a/app/core/src/main/res/values-iw/strings.xml +++ b/app/core/src/main/res/values-iw/strings.xml @@ -188,7 +188,6 @@ צורב… בוצע! בוצעה ריצת פעולה של %1$s נכשל! - מסתיר את יישום Magisk… לא נמצאו יישומים לפתיחת קישור זה הסרה מלאה שיחזור תמונות diff --git a/app/core/src/main/res/values-ja/strings.xml b/app/core/src/main/res/values-ja/strings.xml index 606256f25..19d42cd02 100644 --- a/app/core/src/main/res/values-ja/strings.xml +++ b/app/core/src/main/res/values-ja/strings.xml @@ -182,7 +182,6 @@ 書込中… 完了! 失敗! - Magisk アプリを隠しています… このリンクを開けるアプリがありません 完全にアンインストール イメージのリストア diff --git a/app/core/src/main/res/values-ka/strings.xml b/app/core/src/main/res/values-ka/strings.xml index 84075f6f9..364bc2a1c 100644 --- a/app/core/src/main/res/values-ka/strings.xml +++ b/app/core/src/main/res/values-ka/strings.xml @@ -164,7 +164,6 @@ მიმდინარეობს ჩაშენება… დასრულდა! ჩაიშალა - ვმალავთ Magisk-ის აპს… ლინკის გამხსნელი აპლიკაცია ვერ მოიძებნა დეინსტალაციის დასრულება სურათის აღდგენა diff --git a/app/core/src/main/res/values-kk/strings.xml b/app/core/src/main/res/values-kk/strings.xml index 21bb213cf..60cfa4833 100644 --- a/app/core/src/main/res/values-kk/strings.xml +++ b/app/core/src/main/res/values-kk/strings.xml @@ -188,7 +188,6 @@ Орнатуда… Дайын! Қате! - Magisk қолданбасын жасыруда… Сілтемені аша алатын қолданба табылмады Толығымен жою Жад бөлімдерін қалпына келтіру diff --git a/app/core/src/main/res/values-ko/strings.xml b/app/core/src/main/res/values-ko/strings.xml index 461de880b..cab73cf69 100644 --- a/app/core/src/main/res/values-ko/strings.xml +++ b/app/core/src/main/res/values-ko/strings.xml @@ -177,7 +177,6 @@ 설치 중… 완료! 실패! - Magisk 앱 숨기는 중… 링크를 열 수 있는 앱이 없습니다. 완전히 제거 이미지 복구 diff --git a/app/core/src/main/res/values-ku/strings.xml b/app/core/src/main/res/values-ku/strings.xml index 9f0646f7d..3a392d5f1 100644 --- a/app/core/src/main/res/values-ku/strings.xml +++ b/app/core/src/main/res/values-ku/strings.xml @@ -192,7 +192,6 @@ فلاش کردن تەواو! کارکردنی %1$s تەواو بوو Failed! - شاردنەوەی ئەپی ماجیسک… هیچ ئەپێک تییە تا لینکەکەی پێ بکرێتەوە سڕینەوەی تەواوی هێنانەوەی img diff --git a/app/core/src/main/res/values-lt/strings.xml b/app/core/src/main/res/values-lt/strings.xml index 428c13d8e..92e9458de 100644 --- a/app/core/src/main/res/values-lt/strings.xml +++ b/app/core/src/main/res/values-lt/strings.xml @@ -181,7 +181,6 @@ Diegiama… Baigta! Nepavyko! - Slepiama Magisk programėlė… Nerasta programėlių nuorodos atidarymui Visiškas pašalinimas Atkurti vaizdą diff --git a/app/core/src/main/res/values-ml/strings.xml b/app/core/src/main/res/values-ml/strings.xml index b1f954921..a3d2179ee 100644 --- a/app/core/src/main/res/values-ml/strings.xml +++ b/app/core/src/main/res/values-ml/strings.xml @@ -179,7 +179,6 @@ ഫ്ലാഷ് ചെയ്യുന്നു... ചെയ്തു! പരാജയപ്പെട്ടു! - മജിസ്‌ക് ആപ്പ് മറയ്ക്കുന്നു... ലിങ്ക് തുറക്കാൻ ആപ്പൊന്നും കണ്ടെത്തിയില്ല പൂർണ്ണമായും അൺഇൻസ്റ്റാൾ ചെയ്യുക ഇമേജുകൾ റിസ്റ്റോർ ചെയ്യുക diff --git a/app/core/src/main/res/values-nb/strings.xml b/app/core/src/main/res/values-nb/strings.xml index bda8e7b47..519dff27f 100644 --- a/app/core/src/main/res/values-nb/strings.xml +++ b/app/core/src/main/res/values-nb/strings.xml @@ -165,7 +165,6 @@ Innbrenner … Ferdig! Mislykket! - Skjuler Magisk-programmet … Ingen programmer kunne åpne lenken Fullfør avinstallasjon Gjenopprett avtrykk diff --git a/app/core/src/main/res/values-pl/strings.xml b/app/core/src/main/res/values-pl/strings.xml index c18e521d1..e790f070a 100644 --- a/app/core/src/main/res/values-pl/strings.xml +++ b/app/core/src/main/res/values-pl/strings.xml @@ -187,7 +187,6 @@ Flashowanie… Gotowe! Błąd - Ukrywanie aplikacji Magisk… Nie znaleziono aplikacji do otwarcia linku Odinstaluj całkowicie Przywróć obrazy diff --git a/app/core/src/main/res/values-pt-rBR/strings.xml b/app/core/src/main/res/values-pt-rBR/strings.xml index e9a63d435..c5fb179e0 100644 --- a/app/core/src/main/res/values-pt-rBR/strings.xml +++ b/app/core/src/main/res/values-pt-rBR/strings.xml @@ -190,7 +190,6 @@ Flashando… Concluído! Ação de execução de %1$s concluída Falhou! - Ocultando o app do Magisk… Nenhum app encontrado para abrir o link Desinstalação completa Restaurar imagens diff --git a/app/core/src/main/res/values-pt-rPT/strings.xml b/app/core/src/main/res/values-pt-rPT/strings.xml index 8d61e2231..c211affd6 100644 --- a/app/core/src/main/res/values-pt-rPT/strings.xml +++ b/app/core/src/main/res/values-pt-rPT/strings.xml @@ -190,7 +190,6 @@ Flashando… Concluído! Ação de execução de %1$s concluída Falhou! - A ocultar o app do Magisk… Nenhum app encontrado para abrir o link Desinstalação completa Restaurar imagens diff --git a/app/core/src/main/res/values-ro/strings.xml b/app/core/src/main/res/values-ro/strings.xml index af54cf5f5..956183d5e 100644 --- a/app/core/src/main/res/values-ro/strings.xml +++ b/app/core/src/main/res/values-ro/strings.xml @@ -190,7 +190,6 @@ Se scrie în memoria flash… Terminat! Eșec! - Se ascunde aplicația Magisk… Nu a fost găsită nicio aplicație pentru a deschide linkul Finalizează dezinstalarea Restaurează imagini diff --git a/app/core/src/main/res/values-ru/strings.xml b/app/core/src/main/res/values-ru/strings.xml index 341c2e9b7..bf2c352bb 100644 --- a/app/core/src/main/res/values-ru/strings.xml +++ b/app/core/src/main/res/values-ru/strings.xml @@ -189,7 +189,6 @@ Установка… Завершено! Ошибка! - Скрытие приложения Magisk… Приложения для открытия ссылки не найдены Полное удаление Восстановить разделы diff --git a/app/core/src/main/res/values-sk/strings.xml b/app/core/src/main/res/values-sk/strings.xml index d57db3265..2f721b9ec 100644 --- a/app/core/src/main/res/values-sk/strings.xml +++ b/app/core/src/main/res/values-sk/strings.xml @@ -190,7 +190,6 @@ Flashovanie... Hotovo! Zlyhalo! - Skrýva sa aplikácia Magisk… Nepodarilo sa nájsť vhodnú aplikáciu na otvorenie odkazu Úplne odinštalovať Obnoviť obrazy diff --git a/app/core/src/main/res/values-sq/strings.xml b/app/core/src/main/res/values-sq/strings.xml index 52c02c813..68194f1b9 100644 --- a/app/core/src/main/res/values-sq/strings.xml +++ b/app/core/src/main/res/values-sq/strings.xml @@ -203,7 +203,6 @@ Duke u flash-uar… U krye! U krye veprimi i %1$s Dështoi! - Duke fshehur aplikacionin Magisk… Nuk u gjet asnjë aplikacion për të hapur lidhjen Çinstalim i plotë Rikthe imazhet diff --git a/app/core/src/main/res/values-sr/strings.xml b/app/core/src/main/res/values-sr/strings.xml index 26474c234..40cde9972 100644 --- a/app/core/src/main/res/values-sr/strings.xml +++ b/app/core/src/main/res/values-sr/strings.xml @@ -208,7 +208,6 @@ Флешовање… Завршено! Покретање акције %1$s завршено Неуспешно! - Скривање Magisk апликације… Није пронађена апликација за отварање линка Комплетна деинсталација Поврати слике diff --git a/app/core/src/main/res/values-sv/strings.xml b/app/core/src/main/res/values-sv/strings.xml index f52afbc23..566d74c7a 100644 --- a/app/core/src/main/res/values-sv/strings.xml +++ b/app/core/src/main/res/values-sv/strings.xml @@ -165,7 +165,6 @@ Flashar… Färdig! Misslyckades! - Gömmer Magisk-appen… Ingen app hittades som kan öppna länken link Komplett avinstallation Återställ avbilder diff --git a/app/core/src/main/res/values-sw/strings.xml b/app/core/src/main/res/values-sw/strings.xml index 159ce2c9b..1b40ef4cd 100644 --- a/app/core/src/main/res/values-sw/strings.xml +++ b/app/core/src/main/res/values-sw/strings.xml @@ -177,7 +177,6 @@ Flashing… Done! Failed! - Hiding the Magisk app… No app found to open the link Complete Uninstall Restore Images diff --git a/app/core/src/main/res/values-ta/strings.xml b/app/core/src/main/res/values-ta/strings.xml index 79ccc74a5..ea7b9e263 100644 --- a/app/core/src/main/res/values-ta/strings.xml +++ b/app/core/src/main/res/values-ta/strings.xml @@ -165,7 +165,6 @@ ஏற்றுகிறது… முடிந்தது! தோல்வி! - மேஜிஸ்க் பயன்பாட்டை மறைக்கிறது… இணைப்பைத் திறக்க எந்த பயன்பாடும் கிடைக்கவில்லை நிறுவல் நீக்குதல் படங்களை மீட்டமை diff --git a/app/core/src/main/res/values-tr/strings.xml b/app/core/src/main/res/values-tr/strings.xml index 5e27830a0..406858898 100644 --- a/app/core/src/main/res/values-tr/strings.xml +++ b/app/core/src/main/res/values-tr/strings.xml @@ -203,7 +203,6 @@ Yazılıyor… Tamamlandı! %1$s işlemi tamamlandı Başarısız! - Magisk uygulaması gizleniyor… Bağlantıyı açacak uygulama bulunamadı Tamamen kaldır İmajları geri yükle diff --git a/app/core/src/main/res/values-uk/strings.xml b/app/core/src/main/res/values-uk/strings.xml index 202eec804..3da76392f 100644 --- a/app/core/src/main/res/values-uk/strings.xml +++ b/app/core/src/main/res/values-uk/strings.xml @@ -207,7 +207,6 @@ Прошивання… Готово! Дію %1$s виконано Не вдалося! - Ховання застосунку Magisk… Не знайдено застосунку для відкриття посилання Повне видалення Відновити розділи diff --git a/app/core/src/main/res/values-ur/strings.xml b/app/core/src/main/res/values-ur/strings.xml index 4d7e25f4a..f2eaf5552 100644 --- a/app/core/src/main/res/values-ur/strings.xml +++ b/app/core/src/main/res/values-ur/strings.xml @@ -175,7 +175,6 @@ فلیش ہو رہا ہے… ہو گیا! ناکام! - Magisk ایپ کو چھپایا جا رہا ہے… لنک کھولنے کے لیے کوئی ایپ نہیں ملی مکمل ان انسٹال تصاویر بحال کریں diff --git a/app/core/src/main/res/values-vi/strings.xml b/app/core/src/main/res/values-vi/strings.xml index b2dec9515..c718a70e8 100644 --- a/app/core/src/main/res/values-vi/strings.xml +++ b/app/core/src/main/res/values-vi/strings.xml @@ -179,7 +179,6 @@ Đang cài… Xong! Thất bại! - Đang ẩn ứng dụng Magisk… Không tìm thấy ứng dụng nào để mở liên kết Hoàn thành Gỡ cài đặt Khôi phục đĩa ảnh boot (boot image) diff --git a/app/core/src/main/res/values-zh-rCN/strings.xml b/app/core/src/main/res/values-zh-rCN/strings.xml index 2f2ff9bf3..a0c055ddb 100644 --- a/app/core/src/main/res/values-zh-rCN/strings.xml +++ b/app/core/src/main/res/values-zh-rCN/strings.xml @@ -218,7 +218,6 @@ 正在刷入 完成! %1$s 操作运行完成 失败 - 正在隐藏 Magisk 应用 找不到能打开此链接的应用 完全卸载 还原原厂映像 diff --git a/app/core/src/main/res/values-zh-rTW/strings.xml b/app/core/src/main/res/values-zh-rTW/strings.xml index 5726c6632..9ca4bb7e2 100644 --- a/app/core/src/main/res/values-zh-rTW/strings.xml +++ b/app/core/src/main/res/values-zh-rTW/strings.xml @@ -225,7 +225,6 @@ %1$s 的動作執行完成 完成! 失敗! - 正在隱藏 Magisk…… 沒有可以開啟此連結的應用程式 完全解除安裝 還原原始映像檔 diff --git a/app/core/src/main/res/values/strings.xml b/app/core/src/main/res/values/strings.xml index 4fa1d488b..dca95e4d2 100644 --- a/app/core/src/main/res/values/strings.xml +++ b/app/core/src/main/res/values/strings.xml @@ -215,7 +215,6 @@ Flashing… Done! Done running action of %1$s Failed! - Hiding the Magisk app… No app found to open the link Complete uninstall Restore images diff --git a/app/gradle/libs.versions.toml b/app/gradle/libs.versions.toml index 276c58e31..bc577e048 100644 --- a/app/gradle/libs.versions.toml +++ b/app/gradle/libs.versions.toml @@ -15,7 +15,6 @@ navigationevent = "1.1.2" wire = "7.0.3" [libraries] -bcpkix = { module = "org.bouncycastle:bcpkix-jdk18on", version = "1.86" } commons-compress = { module = "org.apache.commons:commons-compress", version = "1.28.0" } retrofit = { module = "com.squareup.retrofit2:retrofit", version.ref = "retrofit" } retrofit-moshi = { module = "com.squareup.retrofit2:converter-moshi", version.ref = "retrofit" } diff --git a/app/test/src/main/AndroidManifest.xml b/app/test/src/main/AndroidManifest.xml index f6db92673..2b4b21ab7 100644 --- a/app/test/src/main/AndroidManifest.xml +++ b/app/test/src/main/AndroidManifest.xml @@ -16,8 +16,4 @@ android:name="com.topjohnwu.magisk.test.AppTestRunner" android:targetPackage="com.topjohnwu.magisk" /> - - diff --git a/app/test/src/main/java/com/topjohnwu/magisk/test/AppMigrationTest.kt b/app/test/src/main/java/com/topjohnwu/magisk/test/AppMigrationTest.kt deleted file mode 100644 index 56faf300a..000000000 --- a/app/test/src/main/java/com/topjohnwu/magisk/test/AppMigrationTest.kt +++ /dev/null @@ -1,89 +0,0 @@ -package com.topjohnwu.magisk.test - -import android.content.BroadcastReceiver -import android.content.Context -import android.content.Intent -import android.content.IntentFilter -import android.os.ParcelFileDescriptor.AutoCloseInputStream -import androidx.annotation.Keep -import androidx.test.ext.junit.runners.AndroidJUnit4 -import androidx.test.platform.app.InstrumentationRegistry -import org.junit.After -import org.junit.Assert.assertTrue -import org.junit.Test -import org.junit.runner.RunWith -import java.util.concurrent.CountDownLatch -import java.util.concurrent.TimeUnit - -@Keep -@RunWith(AndroidJUnit4::class) -class AppMigrationTest { - - companion object { - private const val APP_PKG = "com.topjohnwu.magisk" - private const val STUB_PKG = "repackaged.$APP_PKG" - // First launch may compile the hidden app's dynamic APK before uninstalling. - private const val RECEIVER_TIMEOUT = 30L - } - - private val instrumentation get() = InstrumentationRegistry.getInstrumentation() - private val context get() = instrumentation.context - private val uiAutomation get() = instrumentation.uiAutomation - private val registeredReceivers = mutableListOf() - - class PackageRemoveMonitor( - context: Context, - private val packageName: String - ) : BroadcastReceiver() { - - val latch = CountDownLatch(1) - - init { - val filter = IntentFilter(Intent.ACTION_PACKAGE_REMOVED) - filter.addDataScheme("package") - context.registerReceiver(this, filter) - } - - override fun onReceive(context: Context, intent: Intent) { - if (intent.action != Intent.ACTION_PACKAGE_REMOVED) - return - val data = intent.data ?: return - val pkg = data.schemeSpecificPart - if (pkg == packageName) latch.countDown() - } - } - - @After - fun tearDown() { - registeredReceivers.forEach(context::unregisterReceiver) - } - - private fun testAppMigration(pkg: String, method: String) { - val receiver = PackageRemoveMonitor(context, pkg) - registeredReceivers.add(receiver) - - // Trigger the test to run migration - val pfd = uiAutomation.executeShellCommand( - "am instrument -w --user current -e class .Environment#$method " + - "$pkg.test/${AppTestRunner::class.java.name}" - ) - val output = AutoCloseInputStream(pfd).reader().use { it.readText() } - assertTrue("$method failed, inst out: $output", output.contains("OK (")) - - // Wait for migration to complete - assertTrue( - "$pkg uninstallation failed", - receiver.latch.await(RECEIVER_TIMEOUT, TimeUnit.SECONDS) - ) - } - - @Test - fun testAppHide() { - testAppMigration(APP_PKG, "setupAppHide") - } - - @Test - fun testAppRestore() { - testAppMigration(STUB_PKG, "setupAppRestore") - } -} diff --git a/scripts/avd.sh b/scripts/avd.sh index 41ae46266..4cebdff01 100755 --- a/scripts/avd.sh +++ b/scripts/avd.sh @@ -298,7 +298,6 @@ live_test_main() { for apk in "${apks[@]}"; do # Cleanup adb shell pm uninstall com.topjohnwu.magisk || true - adb shell pm uninstall repackaged.com.topjohnwu.magisk.test || true adb shell /system/xbin/su 0 rm -rf /data/adb/modules # "Install" Magisk diff --git a/scripts/test_common.sh b/scripts/test_common.sh index 62cf30957..4463e1414 100644 --- a/scripts/test_common.sh +++ b/scripts/test_common.sh @@ -81,22 +81,8 @@ print_apks() { run_tests() { local pkg='com.topjohnwu.magisk.test' - local self="$pkg/$pkg.TestRunner" local app="$pkg/$pkg.AppTestRunner" - local stub="repackaged.$pkg/$pkg.AppTestRunner" # Run app tests am_instrument '.SmokeTest,.IntegrationTest' $app - - # Test app hiding - am_instrument '.AppMigrationTest#testAppHide' $self - - # Make sure it still works - am_instrument '.SmokeTest' $stub - - # Test app restore - am_instrument '.AppMigrationTest#testAppRestore' $self - - # Make sure it still works - am_instrument '.SmokeTest' $app }