app: harden security and clean up build & R8 rules

Harden external intent handling in MainActivity: only accept module
installation, and drop any other action, including uninstallation.
Require explicit user confirmation before flashing, unless the intent
carries the per-process token attached to our own one-shot module
download intents, which the user already chose to install. Hide
overlay windows while the confirmation is shown. Look up the file name
from the external provider with a timeout, and sanitize it and the
provider authority shown in the confirmation. Avoid external intent
indirection in HomeScreen when triggering uninstallation.

Restore callback-based confirm dialogs together with their content
after configuration changes. Dialogs awaited by a coroutine are not
restored, as nothing would receive their result.

Register dynamic USB receivers in InstallDialog as not exported via
registerRuntimeReceiver (RECEIVER_NOT_EXPORTED, enforced on API 33+).

Enable android:enableOnBackInvokedCallback in core manifest to support
predictive back gestures. Fix MagiskDialog modifier parameter ordering
to adhere to Compose lint rules.

Remove the obsolete release manifest and redundant R8 configuration in
core and apk modules: the Parcelable CREATOR and Continuation keep
rules and -allowaccessmodification are covered by
proguard-android-optimize.txt and library consumer rules, and
-shrinkunusedprotofields has no effect with Wire.

Assisted-by: Gemini 4 Argon
Assisted-by: Claude Opus 5.5
This commit is contained in:
topjohnwu
2026-10-24 13:01:45 -07:00
committed by John Wu
parent a51dc10f88
commit 7e4eeb4f8d
10 changed files with 193 additions and 66 deletions
-1
View File
@@ -1,3 +1,2 @@
# Excessive obfuscation
-flattenpackagehierarchy
-allowaccessmodification
@@ -6,7 +6,11 @@ import android.content.Context
import android.content.Intent
import android.content.pm.ApplicationInfo
import android.content.res.Resources
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.CancellationSignal
import android.provider.OpenableColumns
import android.view.WindowManager
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
@@ -20,6 +24,7 @@ import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalResources
import androidx.core.net.toUri
import androidx.lifecycle.compose.collectAsStateWithLifecycle
@@ -37,6 +42,7 @@ import com.topjohnwu.magisk.core.base.ActivityExtension
import com.topjohnwu.magisk.core.base.SplashController
import com.topjohnwu.magisk.core.base.SplashScreenHost
import com.topjohnwu.magisk.core.wrap
import com.topjohnwu.magisk.ui.component.ConfirmResult
import com.topjohnwu.magisk.ui.component.rememberConfirmDialog
import com.topjohnwu.magisk.ui.deny.DenyListScreen
import com.topjohnwu.magisk.ui.deny.DenyListViewModel
@@ -53,10 +59,17 @@ import com.topjohnwu.magisk.ui.superuser.SuperuserDetailScreen
import com.topjohnwu.magisk.ui.superuser.SuperuserGrantScreen
import com.topjohnwu.magisk.ui.superuser.SuperuserGrantViewModel
import com.topjohnwu.magisk.ui.superuser.SuperuserViewModel
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.flow.MutableStateFlow
import java.io.File
import kotlinx.coroutines.withTimeoutOrNull
import com.topjohnwu.magisk.core.R as CoreR
private const val MAX_DISPLAY_NAME_LENGTH = 100
private const val DISPLAY_NAME_QUERY_TIMEOUT_MS = 3000L
class MainActivity : ComponentActivity(), SplashScreenHost {
override val extension = ActivityExtension(this)
@@ -204,16 +217,110 @@ class MainActivity : ComponentActivity(), SplashScreenHost {
@Composable
private fun HandleFlashIntent(navigator: Navigator) {
val confirmDialog = rememberConfirmDialog()
val context = LocalContext.current
val resources = LocalResources.current
val intentVersion by intentState.collectAsStateWithLifecycle()
LaunchedEffect(intentVersion) {
val currentIntent = intent ?: return@LaunchedEffect
if (currentIntent.action == FlashUtils.INTENT_FLASH) {
if (currentIntent.action != FlashUtils.INTENT_FLASH) return@LaunchedEffect
val action = currentIntent.getStringExtra(FlashUtils.EXTRA_FLASH_ACTION)
?: return@LaunchedEffect
val uri = currentIntent.getStringExtra(FlashUtils.EXTRA_FLASH_URI)
navigator.push(Route.Flash(action, uri))
currentIntent.action = null
val uriString = currentIntent.getStringExtra(FlashUtils.EXTRA_FLASH_URI)
val route = when (action) {
Const.Value.FLASH_ZIP -> {
if (uriString.isNullOrEmpty()) {
null
} else if (FlashUtils.isTrusted(currentIntent)) {
// Sent by our own module download, which the user already chose to install
Route.Flash(action, uriString)
} else {
val uri = uriString.toUri()
val name = queryDisplayName(context, uri)?.sanitizeDisplayName()?.ifEmpty { null }
?: uri.lastPathSegment?.sanitizeDisplayName()?.ifEmpty { null }
?: "module.zip"
// The name is chosen by the app that sent the intent, so also show where it comes from
val authority = uri.authority?.sanitizeDisplayName()?.ifEmpty { null }
val displayName = authority?.let { "$name ($it)" } ?: name
// This confirmation is the only safeguard, so don't let other apps draw over it
setHideOverlayWindows(true)
val result = try {
confirmDialog.awaitConfirm(
title = resources.getString(CoreR.string.confirm_install_title),
content = resources.getString(CoreR.string.confirm_install, displayName)
)
} finally {
setHideOverlayWindows(false)
}
if (result == ConfirmResult.Confirmed) Route.Flash(action, uriString) else null
}
}
// Only installing modules can be requested through this intent (our module
// downloads use it too); drop any other action, e.g. uninstalling Magisk
else -> null
}
// Only consume the intent once the request is resolved. If a configuration change
// cancels this effect while the confirmation is showing, the new Activity replays it.
currentIntent.action = null
route?.let { navigator.push(it) }
}
}
/**
* Names from external apps are untrusted: drop control and formatting characters
* (e.g. bidi overrides that can reorder the text) and cap the length.
*/
private fun String.sanitizeDisplayName(): String {
val sb = StringBuilder()
var count = 0
var i = 0
// Work on code points, so supplementary characters (e.g. invisible tag characters)
// are recognized and never split
while (i < length && count < MAX_DISPLAY_NAME_LENGTH) {
val cp = codePointAt(i)
i += Character.charCount(cp)
val type = Character.getType(cp)
if (Character.isISOControl(cp) || type == Character.FORMAT.toInt() ||
type == Character.SURROGATE.toInt()) continue
sb.appendCodePoint(cp)
count++
}
return sb.toString().trim()
}
/**
* Query the display name from the provider of an external URI. The provider is controlled
* by another app, so never block on it indefinitely: give up after a timeout and cancel it.
*/
private suspend fun queryDisplayName(context: Context, uri: Uri): String? {
val signal = CancellationSignal()
// Not a child of the caller, so giving up doesn't have to wait for the provider
val query = CoroutineScope(Dispatchers.IO).async {
runCatching {
context.contentResolver.query(
uri, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null, signal
)?.use { cursor ->
val idx = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)
if (cursor.moveToFirst() && idx >= 0) cursor.getString(idx) else null
}
}.getOrNull()
}
return try {
withTimeoutOrNull(DISPLAY_NAME_QUERY_TIMEOUT_MS) { query.await() }
} finally {
if (!query.isCompleted) {
signal.cancel()
query.cancel()
}
}
}
private fun setHideOverlayWindows(hide: Boolean) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
window.setHideOverlayWindows(hide)
}
}
@@ -40,6 +40,7 @@ import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.saveable.listSaver
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
@@ -80,6 +81,42 @@ data class DialogVisuals(
val dismiss: String? = null,
)
private class ConfirmDialogState(
visible: Boolean = false,
visuals: DialogVisuals = DialogVisuals(),
) {
var visible by mutableStateOf(visible)
var visuals by mutableStateOf(visuals)
// Whether the dialog was shown by awaitConfirm
var awaiting = false
companion object {
/**
* Restores the dialog with its content after a configuration change. A dialog shown by
* awaitConfirm is not restored: the coroutine waiting for its result does not survive,
* so confirming it would do nothing. Callers that need it show it again.
*/
val Saver = listSaver<ConfirmDialogState, Any?>(
save = {
val v = it.visuals
listOf(it.visible && !it.awaiting, v.title, v.content, v.markdown, v.confirm, v.dismiss)
},
restore = {
ConfirmDialogState(
visible = it[0] as Boolean,
visuals = DialogVisuals(
title = it[1] as String,
content = it[2] as String?,
markdown = it[3] as Boolean,
confirm = it[4] as String?,
dismiss = it[5] as String?,
),
)
}
)
}
}
interface LoadingDialogHandle {
suspend fun <R> withLoading(block: suspend () -> R): R
}
@@ -119,15 +156,12 @@ private class LoadingDialogHandleImpl(
}
private class ConfirmDialogHandleImpl(
private val visible: MutableState<Boolean>,
private val state: ConfirmDialogState,
private val coroutineScope: CoroutineScope,
private val callback: ConfirmCallback,
private val resultChannel: Channel<ConfirmResult>
) : ConfirmDialogHandle {
var visuals by mutableStateOf(DialogVisuals())
private set
private var awaitContinuation: CancellableContinuation<ConfirmResult>? = null
init {
@@ -140,7 +174,7 @@ private class ConfirmDialogHandleImpl(
if (it.isActive) it.resume(result)
}
}
.onEach { visible.value = false }
.onEach { state.visible = false }
.collect { result ->
when (result) {
ConfirmResult.Confirmed -> callback.onConfirm?.invoke()
@@ -158,8 +192,9 @@ private class ConfirmDialogHandleImpl(
dismiss: String?
) {
coroutineScope.launch {
visuals = DialogVisuals(title, content, markdown, confirm, dismiss)
visible.value = true
state.visuals = DialogVisuals(title, content, markdown, confirm, dismiss)
state.awaiting = false
state.visible = true
}
}
@@ -171,12 +206,13 @@ private class ConfirmDialogHandleImpl(
dismiss: String?
): ConfirmResult {
coroutineScope.launch {
visuals = DialogVisuals(title, content, markdown, confirm, dismiss)
visible.value = true
state.visuals = DialogVisuals(title, content, markdown, confirm, dismiss)
state.awaiting = true
state.visible = true
}
return suspendCancellableCoroutine { cont ->
awaitContinuation = cont.apply {
invokeOnCancellation { visible.value = false }
invokeOnCancellation { state.visible = false }
}
}
}
@@ -220,23 +256,23 @@ fun rememberConfirmDialog(
@Composable
fun rememberConfirmDialog(callback: ConfirmCallback): ConfirmDialogHandle {
val visible = rememberSaveable { mutableStateOf(false) }
val state = rememberSaveable(saver = ConfirmDialogState.Saver) { ConfirmDialogState() }
val scope = rememberCoroutineScope()
val resultChannel = remember { Channel<ConfirmResult>() }
val handle = remember {
ConfirmDialogHandleImpl(visible, scope, callback, resultChannel)
ConfirmDialogHandleImpl(state, scope, callback, resultChannel)
}
if (visible.value) {
if (state.visible) {
ConfirmDialogContent(
visuals = handle.visuals,
visuals = state.visuals,
confirm = {
visible.value = false
state.visible = false
scope.launch { resultChannel.send(ConfirmResult.Confirmed) }
},
dismiss = {
visible.value = false
state.visible = false
scope.launch { resultChannel.send(ConfirmResult.Canceled) }
}
)
@@ -389,8 +425,8 @@ fun MagiskDialog(
@Composable
fun MagiskDialog(
onDismissRequest: () -> Unit,
title: String? = null,
modifier: Modifier = Modifier,
title: String? = null,
dismissOnClickOutside: Boolean = true,
dismissOnBackPress: Boolean = true,
confirmText: String? = null,
@@ -7,24 +7,40 @@ import android.net.Uri
import com.topjohnwu.magisk.core.Const
import com.topjohnwu.magisk.core.cmp
import com.topjohnwu.magisk.ui.MainActivity
import java.util.UUID
object FlashUtils {
const val INTENT_FLASH = "com.topjohnwu.magisk.intent.FLASH"
const val EXTRA_FLASH_ACTION = "flash_action"
const val EXTRA_FLASH_URI = "flash_uri"
private const val EXTRA_FLASH_TOKEN = "flash_token"
fun installIntent(context: Context, file: Uri): PendingIntent {
// Random per-process token attached to our own install intents. Other apps cannot read
// the extras of our PendingIntents, so a matching token proves the request came from us.
private val token = UUID.randomUUID().toString()
fun isTrusted(intent: Intent) = intent.getStringExtra(EXTRA_FLASH_TOKEN) == token
/**
* Creates the intent to install a downloaded module. [requestCode] must be unique per
* download (e.g. its notification ID), so re-downloads of the same file each get their
* own one-shot PendingIntent.
*/
fun installIntent(context: Context, file: Uri, requestCode: Int): PendingIntent {
val intent = Intent(context, MainActivity::class.java).apply {
component = MainActivity::class.java.cmp(context.packageName)
action = INTENT_FLASH
putExtra(EXTRA_FLASH_ACTION, Const.Value.FLASH_ZIP)
putExtra(EXTRA_FLASH_URI, file.toString())
putExtra(EXTRA_FLASH_TOKEN, token)
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP
}
// One-shot: it skips the install confirmation, so whoever holds it (e.g. a notification
// listener) must not be able to send it again
return PendingIntent.getActivity(
context, file.hashCode(), intent,
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
context, requestCode, intent,
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_ONE_SHOT
)
}
}
@@ -1,6 +1,5 @@
package com.topjohnwu.magisk.ui.home
import android.content.Intent
import android.os.Build
import android.os.Handler
import android.os.Looper
@@ -90,9 +89,10 @@ import com.topjohnwu.magisk.ui.component.MagiskDialog
import com.topjohnwu.magisk.ui.component.MarkdownTextAsync
import com.topjohnwu.magisk.ui.component.rememberLoadingDialog
import com.topjohnwu.magisk.ui.component.verticalScrollbar
import com.topjohnwu.magisk.ui.flash.FlashUtils
import com.topjohnwu.magisk.ui.install.InstallDialog
import com.topjohnwu.magisk.ui.install.InstallViewModel
import com.topjohnwu.magisk.ui.navigation.LocalNavigator
import com.topjohnwu.magisk.ui.navigation.Route
import kotlinx.coroutines.launch
import java.io.File
import com.topjohnwu.magisk.core.R as CoreR
@@ -106,6 +106,7 @@ fun HomeScreen(
) {
val uiState by viewModel.uiState.collectAsStateWithLifecycle()
val context = LocalContext.current
val navigator = LocalNavigator.current
val scrollBehavior = TopAppBarDefaults.pinnedScrollBehavior()
val scope = rememberCoroutineScope()
val loadingDialog = rememberLoadingDialog()
@@ -141,12 +142,7 @@ fun HomeScreen(
onDismiss = { showUninstallDialog = false },
onCompleteUninstall = {
showUninstallDialog = false
val intent = Intent(context, context.javaClass).apply {
action = FlashUtils.INTENT_FLASH
putExtra(FlashUtils.EXTRA_FLASH_ACTION, Const.Value.UNINSTALL)
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP
}
context.startActivity(intent)
navigator.push(Route.Flash(Const.Value.UNINSTALL))
},
onRestoreImage = {
showUninstallDialog = false
@@ -72,12 +72,12 @@ import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
import androidx.core.content.ContextCompat
import androidx.core.net.toUri
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.window.core.layout.WindowSizeClass
import com.topjohnwu.magisk.core.Config
import com.topjohnwu.magisk.core.Info
import com.topjohnwu.magisk.core.ktx.registerRuntimeReceiver
import com.topjohnwu.magisk.core.repository.FirmwareCrawler
import com.topjohnwu.magisk.core.utils.MediaStoreUtils.displayName
import com.topjohnwu.magisk.core.utils.UsbBlockDevice
@@ -328,7 +328,7 @@ fun PatchComposableDialog(
addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED)
addAction(UsbManager.ACTION_USB_DEVICE_DETACHED)
}
ContextCompat.registerReceiver(context, receiver, filter, ContextCompat.RECEIVER_EXPORTED)
context.registerRuntimeReceiver(receiver, filter)
onDispose {
runCatching { context.unregisterReceiver(receiver) }
}
@@ -61,7 +61,7 @@ class OnlineModuleSubject(
override val autoLaunch: Boolean,
override val notifyId: Int = Notifications.nextId(),
) : Subject.Module() {
override fun pendingIntent(context: Context) = FlashUtils.installIntent(context, file)
override fun pendingIntent(context: Context) = FlashUtils.installIntent(context, file, notifyId)
}
class ModuleViewModel : AsyncLoadViewModel() {
-14
View File
@@ -1,14 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<application>
<!-- Remove PreviewActivity in release builds -->
<activity
android:name="androidx.compose.ui.tooling.PreviewActivity"
android:exported="true"
tools:node="remove" />
</application>
</manifest>
-13
View File
@@ -1,8 +1,3 @@
# Parcelable
-keepclassmembers class * implements android.os.Parcelable {
public static final ** CREATOR;
}
# Kotlin
-assumenosideeffects class kotlin.jvm.internal.Intrinsics {
public static void check*(...);
@@ -21,13 +16,5 @@
public void d(**);
}
# Protobuf
-shrinkunusedprotofields
# With R8 full mode generic signatures are stripped for classes that are not
# kept. Suspend functions are wrapped in continuations where the type argument
# is used.
-keep,allowobfuscation,allowshrinking class kotlin.coroutines.Continuation
-dontwarn org.junit.**
-dontwarn org.apache.**
+1 -1
View File
@@ -36,7 +36,7 @@
<application
android:name=".App"
android:allowBackup="false"
android:enableOnBackInvokedCallback="false"
android:enableOnBackInvokedCallback="true"
android:icon="@drawable/ic_launcher"
android:label="Magisk"
android:requestLegacyExternalStorage="true"