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
This commit is contained in:
topjohnwu
2026-10-22 14:06:48 -07:00
committed by John Wu
parent 5847745840
commit 1240c2e35c
72 changed files with 5 additions and 2593 deletions
-1
View File
@@ -67,7 +67,6 @@ fun Project.setupCommon() {
"/META-INF/androidx/**",
"/META-INF/versions/**",
"/META-INF/native-image/**",
"/org/bouncycastle/**",
"/org/apache/commons/**",
"/kotlin/**",
"/*.txt",
-1
View File
@@ -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)
@@ -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<String>()
}
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))
@@ -53,7 +53,6 @@ object Const {
object Key {
// intents
const val OPEN_SECTION = "section"
const val PREV_CONFIG = "prev_config"
}
object Value {
@@ -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()
@@ -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<T>(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)
@@ -49,6 +49,5 @@ open class MagiskDB {
object Table {
const val POLICY = "policies"
const val SETTINGS = "settings"
const val STRINGS = "strings"
}
}
@@ -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
}
}
@@ -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) }
@@ -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,42 +26,10 @@ 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()
}
}
suspend fun handleModule(src: InputStream, file: Uri) {
val tmp = context.cachedFile("module.zip")
@@ -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<DBConfig, String> {
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)
}
}
}
}
}
@@ -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.
*
* <p>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.
*
* <p>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<X509Certificate> certificates;
/**
* List of signature algorithms with which to sign (see {@code SIGNATURE_...} constants).
*/
public List<Integer> signatureAlgorithms;
}
/**
* Signs the provided APK using APK Signature Scheme v2 and returns the signed APK as a list of
* consecutive chunks.
*
* <p>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<SignerConfig> 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<Integer> contentDigestAlgorithms = new HashSet<>();
for (SignerConfig signerConfig : signerConfigs) {
for (int signatureAlgorithm : signerConfig.signatureAlgorithms) {
contentDigestAlgorithms.add(
getSignatureAlgorithmContentDigestAlgorithm(signatureAlgorithm));
}
}
// Compute digests of APK contents.
Map<Integer, byte[]> 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<Integer, byte[]> computeContentDigests(
Set<Integer> 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<Integer, byte[]> 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<Integer, byte[]> result = new HashMap<>(digestAlgorithms.size());
for (Map.Entry<Integer, byte[]> 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<SignerConfig> signerConfigs,
Map<Integer, byte[]> 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<SignerConfig> signerConfigs,
Map<Integer, byte[]> contentDigests) throws InvalidKeyException, SignatureException {
// FORMAT:
// * length-prefixed sequence of length-prefixed signer blocks.
List<byte[]> 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<Integer, byte[]> 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<Pair<Integer, byte[]>> 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<String, ? extends AlgorithmParameterSpec> 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<Pair<Integer, byte[]>> signatures;
public byte[] publicKey;
}
private static final class SignedData {
public List<Pair<Integer, byte[]>> digests;
public List<byte[]> 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<byte[]> encodeCertificates(List<X509Certificate> certificates)
throws CertificateEncodingException {
List<byte[]> result = new ArrayList<>();
for (X509Certificate certificate : certificates) {
result.add(certificate.getEncoded());
}
return result;
}
private static byte[] encodeAsSequenceOfLengthPrefixedElements(List<byte[]> 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<Pair<Integer, byte[]>> sequence) {
int resultSize = 0;
for (Pair<Integer, byte[]> element : sequence) {
resultSize += 12 + element.getSecond().length;
}
ByteBuffer result = ByteBuffer.allocate(resultSize);
result.order(ByteOrder.LITTLE_ENDIAN);
for (Pair<Integer, byte[]> 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 <em>get</em> method for reading {@code size} number of bytes from the current
* position of this buffer.
*
* <p>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<String, ? extends AlgorithmParameterSpec>
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<A, B> {
private final A mFirst;
private final B mSecond;
private Pair(A first, B second) {
mFirst = first;
mSecond = second;
}
public static <A, B> Pair<A, B> 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);
}
}
}
@@ -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);
}
}
@@ -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<String, JarEntry> 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<JarEntry> 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<JarEntry> 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<JarEntry> 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();
}
}
}
@@ -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<String, JarEntry> byName = new TreeMap<>();
for (Enumeration<JarEntry> 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<Object> 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<String, Attributes> entries = manifest.getEntries();
for (Map.Entry<String, Attributes> entry : entries.entrySet()) {
// Digest of the manifest stanza for this entry.
print.print("Name: " + entry.getKey() + "\r\n");
for (Map.Entry<Object, Object> 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<X509Certificate> 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<String, Attributes> entries = manifest.getEntries();
ArrayList<String> 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<ApkSignerV2.SignerConfig> 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<ApkSignerV2.SignerConfig> 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<Integer> 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<ApkSignerV2.SignerConfig> 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;
}
}
}
@@ -1,136 +0,0 @@
package com.topjohnwu.magisk.core.signing;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
/**
* Assorted ZIP format helpers.
*
* <p>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.
*
* <p>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.
*
* <p>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.
*
* <p>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.
*
* <p>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.
*
* <p>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);
}
}
@@ -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<String>()
val c2 = mutableListOf<String>()
val c3 = mutableListOf<String>()
val random = SecureRandom()
val kRandom = random.asKotlinRandom()
fun <T> chain(vararg iters: Iterable<T>) = 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<String>.process() = asSequence().filter(::notJavaKeyword)
val names = mutableListOf<String>()
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()
}
}
}
@@ -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<String>(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)
}
}
}
@@ -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
}
}
@@ -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)
)
}
}
}
@@ -207,7 +207,6 @@
<string name="flashing">جارٍ التثبيت…</string> <string name="done">تم!</string>
<string name="done_action">اكتمل تنفيذ إجراء %1$s</string>
<string name="failure">فشل!</string>
<string name="hide_app_title">جارٍ إخفاء تطبيق Magisk…</string>
<string name="open_link_failed_toast">لا يوجد تطبيق لفتح الرابط</string>
<string name="complete_uninstall">إلغاء تثبيت كامل</string>
<string name="restore_img">استعادة الملف</string>
@@ -178,7 +178,6 @@
<string name="flashing">Flaxando…</string> <string name="done">¡Fecho!</string>
<string name="done_action">Completóse l\'aición de: %1$s</string>
<string name="failure">¡Falló!</string>
<string name="hide_app_title">Escondiendo l\'aplicación Magisk…</string>
<string name="open_link_failed_toast">Nun s\'atopó nenguna aplicación p\'abrir l\'enllaz</string>
<string name="complete_uninstall">Desinstalar dafechu</string>
<string name="restore_img">Restaurar les imáxenes</string>
@@ -183,7 +183,6 @@
<string name="flashing">Flashlanır...</string>
<string name="done">Bitdi!</string>
<string name="failure">Alınmadı!</string>
<string name="hide_app_title">Magisk tətbiqi gizlədilir…</string>
<string name="open_link_failed_toast">Keçidi açaçaq tətbiq yoxdur</string>
<string name="complete_uninstall">Tamamilə sil</string>
<string name="restore_img">Nüsxələri Bərpa et</string>
@@ -208,7 +208,6 @@
<string name="flashing">Flešovanje…</string> <string name="done">Završeno!</string>
<string name="done_action">Pokretanje akcije %1$s završeno</string>
<string name="failure">Neuspešno!</string>
<string name="hide_app_title">Skrivanje Magisk aplikacije…</string>
<string name="open_link_failed_toast">Nije pronađena aplikacija za otvaranje linka</string>
<string name="complete_uninstall">Kompletna deinstalacija</string>
<string name="restore_img">Povrati slike</string>
@@ -151,7 +151,6 @@
<string name="flashing">Усталёўка…</string>
<string name="done">Завершана!</string>
<string name="failure">Не атрымалася</string>
<string name="hide_app_title">Хаванне праграмы Magisk…</string>
<string name="open_link_failed_toast">Праграмы для адкрыцця спасылкі не знойдзена</string>
<string name="complete_uninstall">Поўнае выдаленне</string>
<string name="restore_img">Аднавіць раздзелы</string>
@@ -181,7 +181,6 @@
<string name="flashing">Инсталиране…</string>
<string name="done">Готово!</string>
<string name="failure">Грешка!</string>
<string name="hide_app_title">Скриване на приложението на Magisk…</string>
<string name="open_link_failed_toast">Не е намерено приложение, с което препратката да бъде отворена</string>
<string name="complete_uninstall">Премахване</string>
<string name="restore_img">Възстановяване на образи</string>
@@ -178,7 +178,6 @@
<string name="flashing">ঝলকানি…</string>
<string name="done">সম্পন্ন!</string>
<string name="failure">ব্যর্থ হয়েছে!</string>
<string name="hide_app_title">ম্যাজিস্ক অ্যাপটি লুকিয়ে রাখছে…</string>
<string name="open_link_failed_toast">লিঙ্ক খোলার জন্য কোনো অ্যাপ পাওয়া যায়নি</string>
<string name="complete_uninstall">সম্পূর্ণ আনইনস্টল করুন</string>
<string name="restore_img">ছবি পুনরুদ্ধার করুন</string>
@@ -165,7 +165,6 @@
<string name="flashing">Arranjament…</string>
<string name="done">Fet!</string>
<string name="failure">Fallit</string>
<string name="hide_app_title">Amagant Magisk Manager…</string>
<string name="open_link_failed_toast">No s\'ha trobat una aplicació per obrir l\'enllaç</string>
<string name="complete_uninstall">Desinstal·lació completa</string>
<string name="restore_img">Restaura imatges</string>
@@ -203,7 +203,6 @@
<string name="flashing">Flashuji…</string> <string name="done">Dokončeno!</string>
<string name="done_action">Akce %1$s byla dokončena</string>
<string name="failure">Nepodařilo se!</string>
<string name="hide_app_title">Skrývám aplikaci Magisk…</string>
<string name="open_link_failed_toast">Nebyla nalezena žádná aplikace pro otevření odkazu</string>
<string name="complete_uninstall">Kompletní odinstalace</string>
<string name="restore_img">Obnovit obrazy</string>
@@ -187,7 +187,6 @@
<string name="flashing">Flashen …</string>
<string name="done">Fertig!</string>
<string name="failure">Fehlgeschlagen</string>
<string name="hide_app_title">Magisk-App verstecken …</string>
<string name="open_link_failed_toast">Keine App zum öffnen des Links gefunden</string>
<string name="complete_uninstall">Vollständig deinstallieren</string>
<string name="restore_img">Image wiederherstellen</string>
@@ -179,7 +179,6 @@
<string name="flashing">Προγραμματισμός σε εξέλιξη</string>
<string name="done">Ολοκληρώθηκε</string>
<string name="failure">Αποτυχία</string>
<string name="hide_app_title">Απόκρυψη της εφαρμογής Magisk…</string>
<string name="open_link_failed_toast">Δεν βρέθηκε εφαρμογή για άνοιγμα του συνδέσμου</string>
<string name="complete_uninstall">Πλήρης απεγκατάσταση</string>
<string name="restore_img">Επαναφορά Images</string>
@@ -183,7 +183,6 @@
<string name="flashing">Flasheando…</string>
<string name="done">¡Listo!</string>
<string name="failure">¡Ocurrió un error!</string>
<string name="hide_app_title">Ocultando la app de Magisk…</string>
<string name="open_link_failed_toast">No se encontró ninguna app que pueda abrir este enlace</string>
<string name="complete_uninstall">Desinstalación completa</string>
<string name="restore_img">Solo restaurar las imágenes</string>
@@ -174,7 +174,6 @@
<string name="flashing">Välgutamine…</string>
<string name="done">Valmis!</string>
<string name="failure">Ebaõnnestus</string>
<string name="hide_app_title">Magiski rakenduse peitmine…</string>
<string name="open_link_failed_toast">Lingi avamiseks sobivat rakendust ei leitud.</string>
<string name="complete_uninstall">Täielik eemaldus</string>
<string name="restore_img">Taasta tõmmised</string>
@@ -190,7 +190,6 @@
<string name="flashing">ر حال فلش کردن…</string> <string name="done">تمام!</string>
<string name="done_action">انجام عملیات %1$s به پایان رسید</string>
<string name="failure">ناموفق</string>
<string name="hide_app_title">در حال مخفی کردن برنامه Magisk…</string>
<string name="open_link_failed_toast">هیچ برنامه ای برای باز کردن لینک یافت نشد</string>
<string name="complete_uninstall">کامل کردن حذف</string>
<string name="restore_img">بازیابی تصاویر</string>
@@ -190,7 +190,6 @@
<string name="flashing">Écriture en mémoire Flash…</string>
<string name="done">Terminé !</string>
<string name="failure">Erreur</string>
<string name="hide_app_title">Masquage de l’application Magisk…</string>
<string name="open_link_failed_toast">Aucune application permettant d’ouvrir le lien n’a été trouvée</string>
<string name="complete_uninstall">Désinstallation complète</string>
<string name="restore_img">Restauration des images</string>
@@ -179,7 +179,6 @@
<string name="flashing">फ़्लैश हो रहा है...</string>
<string name="done">सफल हुआ!</string>
<string name="failure">असफल हुआ !</string>
<string name="hide_app_title">मैजिस्क ऐप अब छिप रहा है…</string>
<string name="open_link_failed_toast">लिंक खोलने के लिए कोई एप्लिकेशन नहीं मिला</string>
<string name="complete_uninstall">पूर्ण रूप से अनइंस्टॉल करें</string>
<string name="restore_img">इमेज रिस्टोर करें</string>
@@ -190,7 +190,6 @@
<string name="flashing">Flash ho raha hai…</string> <string name="done">Ho gaya!</string>
<string name="done_action">%1$s ka action complete ho gaya</string>
<string name="failure">Fail ho gaya!</string>
<string name="hide_app_title">Magisk app ko chhupa rahe hain…</string>
<string name="open_link_failed_toast">Link kholne ke liye koi app nahi mila</string>
<string name="complete_uninstall">Sab kuch uninstall karo</string>
<string name="restore_img">Images restore karo</string>
@@ -179,7 +179,6 @@
<string name="flashing">Flashing…</string>
<string name="done">Kész!</string>
<string name="failure">Nem sikerült!</string>
<string name="hide_app_title">A Magisk app elrejtése…</string>
<string name="open_link_failed_toast">Nem található alkalmazás a link megnyitásához</string>
<string name="complete_uninstall">Teljes eltávolítás</string>
<string name="restore_img">Image-ek visszaállítása</string>
@@ -206,7 +206,6 @@
<string name="done">Selesai!</string>
<string name="done_action">Aksi %1$s selesai</string>
<string name="failure">Gagal!</string>
<string name="hide_app_title">Menyembunyikan aplikasi Magisk…</string>
<string name="open_link_failed_toast">Tidak ditemukan aplikasi untuk membuka tautan</string>
<string name="complete_uninstall">Pencopotan penuh</string>
<string name="restore_img">Pulihkan image</string>
@@ -209,7 +209,6 @@
<string name="flashing">Flash in corso…</string> <string name="done">Completato!</string>
<string name="done_action">Azione di %1$s completata</string>
<string name="failure">Fallito</string>
<string name="hide_app_title">Sto nascondendo l\'app di Magisk…</string>
<string name="open_link_failed_toast">Nessuna app disponibile per aprire il link</string>
<string name="complete_uninstall">Disinstalla completamente</string>
<string name="restore_img">Ripristina immagini</string>
@@ -188,7 +188,6 @@
<string name="flashing">צורב…</string> <string name="done">בוצע!</string>
<string name="done_action">בוצעה ריצת פעולה של %1$s</string>
<string name="failure">נכשל!</string>
<string name="hide_app_title">מסתיר את יישום Magisk…</string>
<string name="open_link_failed_toast">לא נמצאו יישומים לפתיחת קישור זה</string>
<string name="complete_uninstall">הסרה מלאה</string>
<string name="restore_img">שיחזור תמונות</string>
@@ -182,7 +182,6 @@
<string name="flashing">書込中…</string>
<string name="done">完了!</string>
<string name="failure">失敗!</string>
<string name="hide_app_title">Magisk アプリを隠しています…</string>
<string name="open_link_failed_toast">このリンクを開けるアプリがありません</string>
<string name="complete_uninstall">完全にアンインストール</string>
<string name="restore_img">イメージのリストア</string>
@@ -164,7 +164,6 @@
<string name="flashing">მიმდინარეობს ჩაშენება…</string>
<string name="done">დასრულდა!</string>
<string name="failure">ჩაიშალა</string>
<string name="hide_app_title">ვმალავთ Magisk-ის აპს…</string>
<string name="open_link_failed_toast">ლინკის გამხსნელი აპლიკაცია ვერ მოიძებნა</string>
<string name="complete_uninstall">დეინსტალაციის დასრულება</string>
<string name="restore_img">სურათის აღდგენა</string>
@@ -188,7 +188,6 @@
<string name="flashing">Орнатуда…</string>
<string name="done">Дайын!</string>
<string name="failure">Қате!</string>
<string name="hide_app_title">Magisk қолданбасын жасыруда…</string>
<string name="open_link_failed_toast">Сілтемені аша алатын қолданба табылмады</string>
<string name="complete_uninstall">Толығымен жою</string>
<string name="restore_img">Жад бөлімдерін қалпына келтіру</string>
@@ -177,7 +177,6 @@
<string name="flashing">설치 중…</string>
<string name="done">완료!</string>
<string name="failure">실패!</string>
<string name="hide_app_title">Magisk 앱 숨기는 중…</string>
<string name="open_link_failed_toast">링크를 열 수 있는 앱이 없습니다.</string>
<string name="complete_uninstall">완전히 제거</string>
<string name="restore_img">이미지 복구</string>
@@ -192,7 +192,6 @@
<string name="flashing">فلاش کردن</string> <string name="done">تەواو!</string>
<string name="done_action">کارکردنی %1$s تەواو بوو</string>
<string name="failure">Failed!</string>
<string name="hide_app_title">شاردنەوەی ئەپی ماجیسک…</string>
<string name="open_link_failed_toast">هیچ ئەپێک تییە تا لینکەکەی پێ بکرێتەوە</string>
<string name="complete_uninstall">سڕینەوەی تەواوی</string>
<string name="restore_img">هێنانەوەی img</string>
@@ -181,7 +181,6 @@
<string name="flashing">Diegiama…</string>
<string name="done">Baigta!</string>
<string name="failure">Nepavyko!</string>
<string name="hide_app_title">Slepiama Magisk programėlė…</string>
<string name="open_link_failed_toast">Nerasta programėlių nuorodos atidarymui</string>
<string name="complete_uninstall">Visiškas pašalinimas</string>
<string name="restore_img">Atkurti vaizdą</string>
@@ -179,7 +179,6 @@
<string name="flashing">ഫ്ലാഷ് ചെയ്യുന്നു...</string>
<string name="done">ചെയ്തു!</string>
<string name="failure">പരാജയപ്പെട്ടു!</string>
<string name="hide_app_title">മജിസ്‌ക് ആപ്പ് മറയ്ക്കുന്നു...</string>
<string name="open_link_failed_toast">ലിങ്ക് തുറക്കാൻ ആപ്പൊന്നും കണ്ടെത്തിയില്ല</string>
<string name="complete_uninstall">പൂർണ്ണമായും അൺഇൻസ്റ്റാൾ ചെയ്യുക</string>
<string name="restore_img">ഇമേജുകൾ റിസ്റ്റോർ ചെയ്യുക</string>
@@ -165,7 +165,6 @@
<string name="flashing">Innbrenner …</string>
<string name="done">Ferdig!</string>
<string name="failure">Mislykket!</string>
<string name="hide_app_title">Skjuler Magisk-programmet …</string>
<string name="open_link_failed_toast">Ingen programmer kunne åpne lenken</string>
<string name="complete_uninstall">Fullfør avinstallasjon</string>
<string name="restore_img">Gjenopprett avtrykk</string>
@@ -187,7 +187,6 @@
<string name="flashing">Flashowanie…</string>
<string name="done">Gotowe!</string>
<string name="failure">Błąd</string>
<string name="hide_app_title">Ukrywanie aplikacji Magisk…</string>
<string name="open_link_failed_toast">Nie znaleziono aplikacji do otwarcia linku</string>
<string name="complete_uninstall">Odinstaluj całkowicie</string>
<string name="restore_img">Przywróć obrazy</string>
@@ -190,7 +190,6 @@
<string name="flashing">Flashando…</string> <string name="done">Concluído!</string>
<string name="done_action">Ação de execução de %1$s concluída</string>
<string name="failure">Falhou!</string>
<string name="hide_app_title">Ocultando o app do Magisk…</string>
<string name="open_link_failed_toast">Nenhum app encontrado para abrir o link</string>
<string name="complete_uninstall">Desinstalação completa</string>
<string name="restore_img">Restaurar imagens</string>
@@ -190,7 +190,6 @@
<string name="flashing">Flashando…</string> <string name="done">Concluído!</string>
<string name="done_action">Ação de execução de %1$s concluída</string>
<string name="failure">Falhou!</string>
<string name="hide_app_title">A ocultar o app do Magisk…</string>
<string name="open_link_failed_toast">Nenhum app encontrado para abrir o link</string>
<string name="complete_uninstall">Desinstalação completa</string>
<string name="restore_img">Restaurar imagens</string>
@@ -190,7 +190,6 @@
<string name="flashing">Se scrie în memoria flash…</string>
<string name="done">Terminat!</string>
<string name="failure">Eșec!</string>
<string name="hide_app_title">Se ascunde aplicația Magisk…</string>
<string name="open_link_failed_toast">Nu a fost găsită nicio aplicație pentru a deschide linkul</string>
<string name="complete_uninstall">Finalizează dezinstalarea</string>
<string name="restore_img">Restaurează imagini</string>
@@ -189,7 +189,6 @@
<string name="flashing">Установка…</string>
<string name="done">Завершено!</string>
<string name="failure">Ошибка!</string>
<string name="hide_app_title">Скрытие приложения Magisk…</string>
<string name="open_link_failed_toast">Приложения для открытия ссылки не найдены</string>
<string name="complete_uninstall">Полное удаление</string>
<string name="restore_img">Восстановить разделы</string>
@@ -190,7 +190,6 @@
<string name="flashing">Flashovanie...</string>
<string name="done">Hotovo!</string>
<string name="failure">Zlyhalo!</string>
<string name="hide_app_title">Skrýva sa aplikácia Magisk…</string>
<string name="open_link_failed_toast">Nepodarilo sa nájsť vhodnú aplikáciu na otvorenie odkazu</string>
<string name="complete_uninstall">Úplne odinštalovať</string>
<string name="restore_img">Obnoviť obrazy</string>
@@ -203,7 +203,6 @@
<string name="flashing">Duke u flash-uar…</string> <string name="done">U krye!</string>
<string name="done_action">U krye veprimi i %1$s</string>
<string name="failure">Dështoi!</string>
<string name="hide_app_title">Duke fshehur aplikacionin Magisk…</string>
<string name="open_link_failed_toast">Nuk u gjet asnjë aplikacion për të hapur lidhjen</string>
<string name="complete_uninstall">Çinstalim i plotë</string>
<string name="restore_img">Rikthe imazhet</string>
@@ -208,7 +208,6 @@
<string name="flashing">Флешовање…</string> <string name="done">Завршено!</string>
<string name="done_action">Покретање акције %1$s завршено</string>
<string name="failure">Неуспешно!</string>
<string name="hide_app_title">Скривање Magisk апликације…</string>
<string name="open_link_failed_toast">Није пронађена апликација за отварање линка</string>
<string name="complete_uninstall">Комплетна деинсталација</string>
<string name="restore_img">Поврати слике</string>
@@ -165,7 +165,6 @@
<string name="flashing">Flashar…</string>
<string name="done">Färdig!</string>
<string name="failure">Misslyckades!</string>
<string name="hide_app_title">Gömmer Magisk-appen…</string>
<string name="open_link_failed_toast">Ingen app hittades som kan öppna länken link</string>
<string name="complete_uninstall">Komplett avinstallation</string>
<string name="restore_img">Återställ avbilder</string>
@@ -177,7 +177,6 @@
<string name="flashing">Flashing…</string>
<string name="done">Done!</string>
<string name="failure">Failed!</string>
<string name="hide_app_title">Hiding the Magisk app…</string>
<string name="open_link_failed_toast">No app found to open the link</string>
<string name="complete_uninstall">Complete Uninstall</string>
<string name="restore_img">Restore Images</string>
@@ -165,7 +165,6 @@
<string name="flashing">ஏற்றுகிறது…</string>
<string name="done">முடிந்தது!</string>
<string name="failure">தோல்வி!</string>
<string name="hide_app_title">மேஜிஸ்க் பயன்பாட்டை மறைக்கிறது…</string>
<string name="open_link_failed_toast">இணைப்பைத் திறக்க எந்த பயன்பாடும் கிடைக்கவில்லை</string>
<string name="complete_uninstall">நிறுவல் நீக்குதல்</string>
<string name="restore_img">படங்களை மீட்டமை</string>
@@ -203,7 +203,6 @@
<string name="flashing">Yazılıyor…</string> <string name="done">Tamamlandı!</string>
<string name="done_action">%1$s işlemi tamamlandı</string>
<string name="failure">Başarısız!</string>
<string name="hide_app_title">Magisk uygulaması gizleniyor…</string>
<string name="open_link_failed_toast">Bağlantıyı açacak uygulama bulunamadı</string>
<string name="complete_uninstall">Tamamen kaldır</string>
<string name="restore_img">İmajları geri yükle</string>
@@ -207,7 +207,6 @@
<string name="flashing">Прошивання…</string> <string name="done">Готово!</string>
<string name="done_action">Дію %1$s виконано</string>
<string name="failure">Не вдалося!</string>
<string name="hide_app_title">Ховання застосунку Magisk…</string>
<string name="open_link_failed_toast">Не знайдено застосунку для відкриття посилання</string>
<string name="complete_uninstall">Повне видалення</string>
<string name="restore_img">Відновити розділи</string>
@@ -175,7 +175,6 @@
<string name="flashing">فلیش ہو رہا ہے…</string>
<string name="done">ہو گیا!</string>
<string name="failure">ناکام!</string>
<string name="hide_app_title">Magisk ایپ کو چھپایا جا رہا ہے…</string>
<string name="open_link_failed_toast">لنک کھولنے کے لیے کوئی ایپ نہیں ملی</string>
<string name="complete_uninstall">مکمل ان انسٹال</string>
<string name="restore_img">تصاویر بحال کریں</string>
@@ -179,7 +179,6 @@
<string name="flashing">Đang cài…</string>
<string name="done">Xong!</string>
<string name="failure">Thất bại!</string>
<string name="hide_app_title">Đang ẩn ứng dụng Magisk…</string>
<string name="open_link_failed_toast">Không tìm thấy ứng dụng nào để mở liên kết</string>
<string name="complete_uninstall">Hoàn thành Gỡ cài đặt</string>
<string name="restore_img">Khôi phục đĩa ảnh boot (boot image)</string>
@@ -218,7 +218,6 @@
<string name="flashing">正在刷入</string> <string name="done">完成!</string>
<string name="done_action">%1$s 操作运行完成</string>
<string name="failure">失败</string>
<string name="hide_app_title">正在隐藏 Magisk 应用</string>
<string name="open_link_failed_toast">找不到能打开此链接的应用</string>
<string name="complete_uninstall">完全卸载</string>
<string name="restore_img">还原原厂映像</string>
@@ -225,7 +225,6 @@
<string name="done_action">%1$s 的動作執行完成</string>
<string name="done">完成!</string>
<string name="failure">失敗!</string>
<string name="hide_app_title">正在隱藏 Magisk……</string>
<string name="open_link_failed_toast">沒有可以開啟此連結的應用程式</string>
<string name="complete_uninstall">完全解除安裝</string>
<string name="restore_img">還原原始映像檔</string>
-1
View File
@@ -215,7 +215,6 @@
<string name="flashing">Flashing…</string> <string name="done">Done!</string>
<string name="done_action">Done running action of %1$s</string>
<string name="failure">Failed!</string>
<string name="hide_app_title">Hiding the Magisk app…</string>
<string name="open_link_failed_toast">No app found to open the link</string>
<string name="complete_uninstall">Complete uninstall</string>
<string name="restore_img">Restore images</string>
-1
View File
@@ -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" }
-4
View File
@@ -16,8 +16,4 @@
android:name="com.topjohnwu.magisk.test.AppTestRunner"
android:targetPackage="com.topjohnwu.magisk" />
<instrumentation
android:name="com.topjohnwu.magisk.test.TestRunner"
android:targetPackage="com.topjohnwu.magisk.test" />
</manifest>
@@ -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<BroadcastReceiver>()
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")
}
}
-1
View File
@@ -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
-14
View File
@@ -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
}