Magisk/app/src/main/java/com/topjohnwu/magisk/core/GeneralReceiver.kt

61 lines
2.2 KiB
Kotlin
Raw Normal View History

2020-01-13 15:01:46 +01:00
package com.topjohnwu.magisk.core
Support loading Magisk Manager from stub on 9.0+ In the effort of preventing apps from crawling APK contents across the whole installed app list to detect Magisk Manager, the solution here is to NOT install the actual APK into the system, but instead dynamically load the full app at runtime by a stub app. The full APK will be stored in the application's private internal data where non-root processes cannot read or scan. The basis of this implementation is the class "AppComponentFactory" that is introduced in API 28. If assigned, the system framework will delegate app component instantiation to our custom implementation, which allows us to do all sorts of crazy stuffs, in our case dynamically load classes and create objects that does not exist in our APK. There are a few challenges to achieve our goal though. First, Java ClassLoaders follow the "delegation pattern", which means class loading resolution will first be delegated to the parent loader before we get a chance to do anything. This includes DexClassLoader, which is what we will be using to load DEX files at runtime. This is a problem because our stub app and full app share quite a lot of class names. A custom ClassLoader, DynamicClassLoader, is created to overcome this issue: it will always load classes in its current dex path before delegating it to the parent. Second, all app components (with the exception of runtime BroadcastReceivers) are required to be declared in AndroidManifest.xml. The full Magisk Manager has quite a lot of components (including those from WorkManager and Room). The solution is to copy the complete AndroidManifest.xml from the full app to the stub, and our AppComponentFactory is responsible to construct the proper objects or return dummy implementations in case the full APK isn't downloaded yet. Third, other than classes, all resources required to run the full app are also not bundled with the stub APK. We have to call an internal API `AssetManager.addAssetPath(String)` to add our downloaded full APK into AssetManager in order to access resources within our full app. That internal API has existed forever, and is whitelisted from restricted API access on modern Android versions, so it is pretty safe to use. Fourth, on the subject of resources, some resources are not just being used by our app at runtime. Resources such as the app icon, app label, launch theme, basically everything referred in AndroidManifest.xml, are used by the system to display the app properly. The system get these resources via resource IDs and direct loading from the installed APK. This subset of resources would have to be copied into the stub to make the app work properly. Fifth, resource IDs are used all over the place in XMLs and Java code. The resource IDs in the stub and full app cannot missmatch, or somewhere, either it be the system or AssetManager, will refer to the incorrect resource. The full app will have to include all resources in the stub, and all of them have to be assigned to the exact same IDs in both APKs. To achieve this, we use AAPT2's "--emit-ids" option to dump the resource ID mapping when building the stub, and "--stable-ids" when building the full APK to make sure all overlapping resources in full and stub are always assigned to the same ID. Finally, both stub and full app have to work properly independently. On 9.0+, the stub will have to first launch an Activity to download the full APK before it can relaunch into the full app. On pre-9.0, the stub should behave as it always did: download and prompt installation to upgrade itself to full Magisk Manager. In the full app, the goal is to introduce minimal intrusion to the code base to make sure this whole thing is maintainable in the future. Fortunately, the solution ends up pretty slick: all ContextWrappers in the app will be injected with custom Contexts. The custom Contexts will return our patched Resources object and the ClassLoader that loads itself, which will be DynamicClassLoader in the case of running as a delegate app. By directly patching the base Context of ContextWrappers (which covers tons of app components) and in the Koin DI, the effect propagates deep into every aspect of the code, making this change basically fully transparent to almost every piece of code in full Magisk Manager. After this commit, the stub app is able to properly download and launch the full app, with most basic functionalities working just fine. Do not expect Magisk Manager upgrades and hiding (repackaging) to work properly, and some other minor issues might pop up. This feature is still in the early WIP stages.
2019-10-14 09:49:17 +02:00
import android.content.ContextWrapper
import android.content.Intent
2020-01-13 15:01:46 +01:00
import com.topjohnwu.magisk.core.base.BaseReceiver
import com.topjohnwu.magisk.core.download.DownloadService
import com.topjohnwu.magisk.core.magiskdb.PolicyDao
2020-01-14 17:51:27 +01:00
import com.topjohnwu.magisk.core.model.ManagerJson
2020-01-13 15:01:46 +01:00
import com.topjohnwu.magisk.core.su.SuCallbackHandler
2020-01-14 17:51:27 +01:00
import com.topjohnwu.magisk.core.view.Shortcuts
2019-07-28 11:10:22 +02:00
import com.topjohnwu.magisk.extensions.reboot
import com.topjohnwu.magisk.model.entity.internal.Configuration
import com.topjohnwu.magisk.model.entity.internal.DownloadSubject
import com.topjohnwu.superuser.Shell
2020-07-09 13:49:14 +02:00
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
Support loading Magisk Manager from stub on 9.0+ In the effort of preventing apps from crawling APK contents across the whole installed app list to detect Magisk Manager, the solution here is to NOT install the actual APK into the system, but instead dynamically load the full app at runtime by a stub app. The full APK will be stored in the application's private internal data where non-root processes cannot read or scan. The basis of this implementation is the class "AppComponentFactory" that is introduced in API 28. If assigned, the system framework will delegate app component instantiation to our custom implementation, which allows us to do all sorts of crazy stuffs, in our case dynamically load classes and create objects that does not exist in our APK. There are a few challenges to achieve our goal though. First, Java ClassLoaders follow the "delegation pattern", which means class loading resolution will first be delegated to the parent loader before we get a chance to do anything. This includes DexClassLoader, which is what we will be using to load DEX files at runtime. This is a problem because our stub app and full app share quite a lot of class names. A custom ClassLoader, DynamicClassLoader, is created to overcome this issue: it will always load classes in its current dex path before delegating it to the parent. Second, all app components (with the exception of runtime BroadcastReceivers) are required to be declared in AndroidManifest.xml. The full Magisk Manager has quite a lot of components (including those from WorkManager and Room). The solution is to copy the complete AndroidManifest.xml from the full app to the stub, and our AppComponentFactory is responsible to construct the proper objects or return dummy implementations in case the full APK isn't downloaded yet. Third, other than classes, all resources required to run the full app are also not bundled with the stub APK. We have to call an internal API `AssetManager.addAssetPath(String)` to add our downloaded full APK into AssetManager in order to access resources within our full app. That internal API has existed forever, and is whitelisted from restricted API access on modern Android versions, so it is pretty safe to use. Fourth, on the subject of resources, some resources are not just being used by our app at runtime. Resources such as the app icon, app label, launch theme, basically everything referred in AndroidManifest.xml, are used by the system to display the app properly. The system get these resources via resource IDs and direct loading from the installed APK. This subset of resources would have to be copied into the stub to make the app work properly. Fifth, resource IDs are used all over the place in XMLs and Java code. The resource IDs in the stub and full app cannot missmatch, or somewhere, either it be the system or AssetManager, will refer to the incorrect resource. The full app will have to include all resources in the stub, and all of them have to be assigned to the exact same IDs in both APKs. To achieve this, we use AAPT2's "--emit-ids" option to dump the resource ID mapping when building the stub, and "--stable-ids" when building the full APK to make sure all overlapping resources in full and stub are always assigned to the same ID. Finally, both stub and full app have to work properly independently. On 9.0+, the stub will have to first launch an Activity to download the full APK before it can relaunch into the full app. On pre-9.0, the stub should behave as it always did: download and prompt installation to upgrade itself to full Magisk Manager. In the full app, the goal is to introduce minimal intrusion to the code base to make sure this whole thing is maintainable in the future. Fortunately, the solution ends up pretty slick: all ContextWrappers in the app will be injected with custom Contexts. The custom Contexts will return our patched Resources object and the ClassLoader that loads itself, which will be DynamicClassLoader in the case of running as a delegate app. By directly patching the base Context of ContextWrappers (which covers tons of app components) and in the Koin DI, the effect propagates deep into every aspect of the code, making this change basically fully transparent to almost every piece of code in full Magisk Manager. After this commit, the stub app is able to properly download and launch the full app, with most basic functionalities working just fine. Do not expect Magisk Manager upgrades and hiding (repackaging) to work properly, and some other minor issues might pop up. This feature is still in the early WIP stages.
2019-10-14 09:49:17 +02:00
import org.koin.core.inject
Support loading Magisk Manager from stub on 9.0+ In the effort of preventing apps from crawling APK contents across the whole installed app list to detect Magisk Manager, the solution here is to NOT install the actual APK into the system, but instead dynamically load the full app at runtime by a stub app. The full APK will be stored in the application's private internal data where non-root processes cannot read or scan. The basis of this implementation is the class "AppComponentFactory" that is introduced in API 28. If assigned, the system framework will delegate app component instantiation to our custom implementation, which allows us to do all sorts of crazy stuffs, in our case dynamically load classes and create objects that does not exist in our APK. There are a few challenges to achieve our goal though. First, Java ClassLoaders follow the "delegation pattern", which means class loading resolution will first be delegated to the parent loader before we get a chance to do anything. This includes DexClassLoader, which is what we will be using to load DEX files at runtime. This is a problem because our stub app and full app share quite a lot of class names. A custom ClassLoader, DynamicClassLoader, is created to overcome this issue: it will always load classes in its current dex path before delegating it to the parent. Second, all app components (with the exception of runtime BroadcastReceivers) are required to be declared in AndroidManifest.xml. The full Magisk Manager has quite a lot of components (including those from WorkManager and Room). The solution is to copy the complete AndroidManifest.xml from the full app to the stub, and our AppComponentFactory is responsible to construct the proper objects or return dummy implementations in case the full APK isn't downloaded yet. Third, other than classes, all resources required to run the full app are also not bundled with the stub APK. We have to call an internal API `AssetManager.addAssetPath(String)` to add our downloaded full APK into AssetManager in order to access resources within our full app. That internal API has existed forever, and is whitelisted from restricted API access on modern Android versions, so it is pretty safe to use. Fourth, on the subject of resources, some resources are not just being used by our app at runtime. Resources such as the app icon, app label, launch theme, basically everything referred in AndroidManifest.xml, are used by the system to display the app properly. The system get these resources via resource IDs and direct loading from the installed APK. This subset of resources would have to be copied into the stub to make the app work properly. Fifth, resource IDs are used all over the place in XMLs and Java code. The resource IDs in the stub and full app cannot missmatch, or somewhere, either it be the system or AssetManager, will refer to the incorrect resource. The full app will have to include all resources in the stub, and all of them have to be assigned to the exact same IDs in both APKs. To achieve this, we use AAPT2's "--emit-ids" option to dump the resource ID mapping when building the stub, and "--stable-ids" when building the full APK to make sure all overlapping resources in full and stub are always assigned to the same ID. Finally, both stub and full app have to work properly independently. On 9.0+, the stub will have to first launch an Activity to download the full APK before it can relaunch into the full app. On pre-9.0, the stub should behave as it always did: download and prompt installation to upgrade itself to full Magisk Manager. In the full app, the goal is to introduce minimal intrusion to the code base to make sure this whole thing is maintainable in the future. Fortunately, the solution ends up pretty slick: all ContextWrappers in the app will be injected with custom Contexts. The custom Contexts will return our patched Resources object and the ClassLoader that loads itself, which will be DynamicClassLoader in the case of running as a delegate app. By directly patching the base Context of ContextWrappers (which covers tons of app components) and in the Koin DI, the effect propagates deep into every aspect of the code, making this change basically fully transparent to almost every piece of code in full Magisk Manager. After this commit, the stub app is able to properly download and launch the full app, with most basic functionalities working just fine. Do not expect Magisk Manager upgrades and hiding (repackaging) to work properly, and some other minor issues might pop up. This feature is still in the early WIP stages.
2019-10-14 09:49:17 +02:00
open class GeneralReceiver : BaseReceiver() {
2019-07-28 12:47:07 +02:00
private val policyDB: PolicyDao by inject()
private fun getPkg(intent: Intent): String {
2019-08-12 10:54:33 +02:00
return intent.data?.encodedSchemeSpecificPart.orEmpty()
}
Support loading Magisk Manager from stub on 9.0+ In the effort of preventing apps from crawling APK contents across the whole installed app list to detect Magisk Manager, the solution here is to NOT install the actual APK into the system, but instead dynamically load the full app at runtime by a stub app. The full APK will be stored in the application's private internal data where non-root processes cannot read or scan. The basis of this implementation is the class "AppComponentFactory" that is introduced in API 28. If assigned, the system framework will delegate app component instantiation to our custom implementation, which allows us to do all sorts of crazy stuffs, in our case dynamically load classes and create objects that does not exist in our APK. There are a few challenges to achieve our goal though. First, Java ClassLoaders follow the "delegation pattern", which means class loading resolution will first be delegated to the parent loader before we get a chance to do anything. This includes DexClassLoader, which is what we will be using to load DEX files at runtime. This is a problem because our stub app and full app share quite a lot of class names. A custom ClassLoader, DynamicClassLoader, is created to overcome this issue: it will always load classes in its current dex path before delegating it to the parent. Second, all app components (with the exception of runtime BroadcastReceivers) are required to be declared in AndroidManifest.xml. The full Magisk Manager has quite a lot of components (including those from WorkManager and Room). The solution is to copy the complete AndroidManifest.xml from the full app to the stub, and our AppComponentFactory is responsible to construct the proper objects or return dummy implementations in case the full APK isn't downloaded yet. Third, other than classes, all resources required to run the full app are also not bundled with the stub APK. We have to call an internal API `AssetManager.addAssetPath(String)` to add our downloaded full APK into AssetManager in order to access resources within our full app. That internal API has existed forever, and is whitelisted from restricted API access on modern Android versions, so it is pretty safe to use. Fourth, on the subject of resources, some resources are not just being used by our app at runtime. Resources such as the app icon, app label, launch theme, basically everything referred in AndroidManifest.xml, are used by the system to display the app properly. The system get these resources via resource IDs and direct loading from the installed APK. This subset of resources would have to be copied into the stub to make the app work properly. Fifth, resource IDs are used all over the place in XMLs and Java code. The resource IDs in the stub and full app cannot missmatch, or somewhere, either it be the system or AssetManager, will refer to the incorrect resource. The full app will have to include all resources in the stub, and all of them have to be assigned to the exact same IDs in both APKs. To achieve this, we use AAPT2's "--emit-ids" option to dump the resource ID mapping when building the stub, and "--stable-ids" when building the full APK to make sure all overlapping resources in full and stub are always assigned to the same ID. Finally, both stub and full app have to work properly independently. On 9.0+, the stub will have to first launch an Activity to download the full APK before it can relaunch into the full app. On pre-9.0, the stub should behave as it always did: download and prompt installation to upgrade itself to full Magisk Manager. In the full app, the goal is to introduce minimal intrusion to the code base to make sure this whole thing is maintainable in the future. Fortunately, the solution ends up pretty slick: all ContextWrappers in the app will be injected with custom Contexts. The custom Contexts will return our patched Resources object and the ClassLoader that loads itself, which will be DynamicClassLoader in the case of running as a delegate app. By directly patching the base Context of ContextWrappers (which covers tons of app components) and in the Koin DI, the effect propagates deep into every aspect of the code, making this change basically fully transparent to almost every piece of code in full Magisk Manager. After this commit, the stub app is able to properly download and launch the full app, with most basic functionalities working just fine. Do not expect Magisk Manager upgrades and hiding (repackaging) to work properly, and some other minor issues might pop up. This feature is still in the early WIP stages.
2019-10-14 09:49:17 +02:00
override fun onReceive(context: ContextWrapper, intent: Intent?) {
2019-08-12 10:54:33 +02:00
intent ?: return
Introduce component agnostic communication Usually, the communication between native and the app is done via sending intents to either broadcast or activity. These communication channels are for launching root requests dialogs, sending root request notifications (the toast you see when an app gained root access), and root request logging. Sending intents by am (activity manager) usually requires specifying the component name in the format of <pkg>/<class name>. This means parts of Magisk Manager cannot be randomized or else the native daemon is unable to know where to send data to the app. On modern Android (not sure which API is it introduced), it is possible to send broadcasts to a package, not a specific component. Which component will receive the intent depends on the intent filter declared in AndroidManifest.xml. Since we already have a mechanism in native code to keep track of the package name of Magisk Manager, this makes it perfect to pass intents to Magisk Manager that have components being randomly obfuscated (stub APKs). There are a few caveats though. Although this broadcasting method works perfectly fine on AOSP and most systems, there are OEMs out there shipping ROMs blocking broadcasts unexpectedly. In order to make sure Magisk works in all kinds of scenarios, we run actual tests every boot to determine which communication method should be used. We have 3 methods in total, ordered in preference: 1. Broadcasting to a package 2. Broadcasting to a specific component 3. Starting a specific activity component Method 3 will always work on any device, but the downside is anytime a communication happens, Magisk Manager will steal foreground focus regardless of whether UI is drawn. Method 1 is the only way to support obfuscated stub APKs. The communication test will test method 1 and 2, and if Magisk Manager is able to receive the messages, it will then update the daemon configuration to use whichever is preferable. If none of the broadcasts can be delivered, then the fallback method 3 will be used.
2019-10-21 19:59:04 +02:00
2020-07-09 13:49:14 +02:00
fun rmPolicy(pkg: String) = GlobalScope.launch {
policyDB.delete(pkg)
}
2019-08-12 10:54:33 +02:00
when (intent.action ?: return) {
Intent.ACTION_REBOOT -> {
2020-01-14 17:51:27 +01:00
SuCallbackHandler(context, intent.getStringExtra("action"), intent.extras)
}
Use ContentProvider call method for communication Previously, we use either BroadcastReceivers or Activities to receive messages from our native daemon, but both have their own downsides. Some OEMs blocks broadcasts if the app is not running in the background, regardless of who the caller is. Activities on the other hand, despite working 100% of the time, will steal the focus of the current foreground app, even though we are just doing some logging and showing a toast. In addition, since stubs for hiding Magisk Manager is introduced, our only communication method is left with the broadcast option, as only broadcasting allows targeting a specific package name, not a component name (which will be obfuscated in the case of stubs). To make sure root requests will work on all devices, Magisk had to do some experiments every boot to test whether broadcast is deliverable or not. This makes the whole thing even more complicated then ever. So lets take a look at another kind of component in Android apps: ContentProviders. It is a vital part of Android's ecosystem, and as far as I know no OEMs will block requests to ContentProviders (or else tons of functionality will break catastrophically). Starting at API 11, the system supports calling a specific method in ContentProviders, optionally sending extra data along with the method call. This is perfect for the native daemon to start a communication with Magisk Manager. Another cool thing is that we no longer need to know the component name of the reciever, as ContentProviders identify themselves with an "authority" name, which in Magisk Manager's case is tied to the package name. We already have a mechanism to keep track of our current manager package name, so this works out of the box. So yay! No more flaky broadcast tests, no more stupid OEMs blocking broadcasts for some bizzare reasons. This method should in theory work on almost all devices and situations.
2019-11-04 20:32:28 +01:00
Intent.ACTION_PACKAGE_REPLACED -> {
// This will only work pre-O
if (Config.suReAuth)
2020-07-09 13:49:14 +02:00
rmPolicy(getPkg(intent))
Use ContentProvider call method for communication Previously, we use either BroadcastReceivers or Activities to receive messages from our native daemon, but both have their own downsides. Some OEMs blocks broadcasts if the app is not running in the background, regardless of who the caller is. Activities on the other hand, despite working 100% of the time, will steal the focus of the current foreground app, even though we are just doing some logging and showing a toast. In addition, since stubs for hiding Magisk Manager is introduced, our only communication method is left with the broadcast option, as only broadcasting allows targeting a specific package name, not a component name (which will be obfuscated in the case of stubs). To make sure root requests will work on all devices, Magisk had to do some experiments every boot to test whether broadcast is deliverable or not. This makes the whole thing even more complicated then ever. So lets take a look at another kind of component in Android apps: ContentProviders. It is a vital part of Android's ecosystem, and as far as I know no OEMs will block requests to ContentProviders (or else tons of functionality will break catastrophically). Starting at API 11, the system supports calling a specific method in ContentProviders, optionally sending extra data along with the method call. This is perfect for the native daemon to start a communication with Magisk Manager. Another cool thing is that we no longer need to know the component name of the reciever, as ContentProviders identify themselves with an "authority" name, which in Magisk Manager's case is tied to the package name. We already have a mechanism to keep track of our current manager package name, so this works out of the box. So yay! No more flaky broadcast tests, no more stupid OEMs blocking broadcasts for some bizzare reasons. This method should in theory work on almost all devices and situations.
2019-11-04 20:32:28 +01:00
}
Intent.ACTION_PACKAGE_FULLY_REMOVED -> {
val pkg = getPkg(intent)
2020-07-09 13:49:14 +02:00
rmPolicy(pkg)
Shell.su("magiskhide --rm $pkg").submit()
}
Intent.ACTION_LOCALE_CHANGED -> Shortcuts.setup(context)
Const.Key.BROADCAST_MANAGER_UPDATE -> {
intent.getParcelableExtra<ManagerJson>(Const.Key.INTENT_SET_APP)?.let {
Info.remote = Info.remote.copy(app = it)
}
DownloadService(context) {
subject = DownloadSubject.Manager(Configuration.APK.Upgrade)
}
}
Const.Key.BROADCAST_REBOOT -> reboot()
}
}
}