Android 8.0+ 后台广播限制分析

2024-10-30  本文已影响0人  Stan_Z

一、背景

广播限制官方文档

为了减少后台应用的系统资源消耗,提升用户体验,Android 7.0(API 级别 24)对广播施加了限制,Android 8.0(API 级别 26)让这些限制更为严格。

限制点Android 8.0 +版本的应用无法静态注册广播接收者接收到隐式广播。

基于android-13.0.0_r43 源码测试:

广播接收者 广播发送方 结果
静态注册 隐式广播
静态注册 显式广播
静态注册 隐式广播 + addFlags(0x01000000)FLAG_RECEIVER_INCLUDE_BACKGROUND
静态注册 豁免的系统隐式广播
测试:BOOT_COMPLETED
注:接收方需要添加权限:<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
动态注册 隐式/显式广播

另外:需要签名权限的广播不受此限制所限,因为这些广播只会发送到使用相同证书签名的应用,而不是发送到设备上的所有应用。

二、限制点源码分析

2.1 调试发送广播方法梳理出核心调用栈:

at com.android.server.am.BroadcastQueue.performReceiveLocked(Native Method)
at com.android.server.am.BroadcastQueue.processNextBroadcastLocked(BroadcastQueue.java:1359)
at com.android.server.am.BroadcastQueue.processNextBroadcast(BroadcastQueue.java:1155)
at com.android.server.am.BroadcastQueue$BroadcastHandler.handleMessage(BroadcastQueue.java:224)
at com.android.server.am.BroadcastQueue.scheduleBroadcastsLocked(Native Method)
at com.android.server.am.ActivityManagerService.broadcastIntentLocked(ActivityManagerService.java:14208)
at com.android.server.am.ActivityManagerService.broadcastIntentWithFeature(ActivityManagerService.java:14461)
at android.app.ContextImpl.sendBroadcastAsUser(ContextImpl.java:1416)

2.2 核心限制点逻辑分析

Background execution not allowed: receiving Intent { act=android.intent.action.EVAN flg=0x10 } to com.stan.simpledemo/.TestReceiver

基于系统限制日志, 定位代码:

com.android.server.am.BroadcastQueue#processNextBroadcastLocked(boolean fromMsg, boolean skipOomAdj)

...
        // 静态注册的广播接收者限制点
        if (!skip) {
              // ① AMS. getAppStartModeLOSP 返回的mode值
            final int allowed = mService.getAppStartModeLOSP( 成mode
                    info.activityInfo.applicationInfo.uid, info.activityInfo.packageName,
                    info.activityInfo.applicationInfo.targetSdkVersion, -1, true, false, false);
            if (allowed != ActivityManager.APP_START_MODE_NORMAL) {
                // We won't allow this receiver to be launched if the app has been
                // completely disabled from launches, or it was not explicitly sent
                // to it and the app is in a state that should not receive it
                // (depending on how getAppStartModeLOSP has determined that).
                if (allowed == ActivityManager.APP_START_MODE_DISABLED) {
                    Slog.w(TAG, "Background execution disabled: receiving "
                            + r.intent + " to "
                            + component.flattenToShortString());
                    skip = true;
                  // ② intent参数判断
                } else if (((r.intent.getFlags()&Intent.FLAG_RECEIVER_EXCLUDE_BACKGROUND) != 0)
                        || (r.intent.getComponent() == null
                            && r.intent.getPackage() == null
                            && ((r.intent.getFlags()
                                    & Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND) == 0)
                            && !isSignaturePerm(r.requiredPermissions))) { 
                    mService.addBackgroundCheckViolationLocked(r.intent.getAction(),
                            component.getPackageName());
                    Slog.w(TAG, "Background execution not allowed: receiving "
                            + r.intent + " to "
                            + component.flattenToShortString());
                    skip = true;
                }
            }
        }
        ...

这里主要有两个部分:

结合前面的测试,来看下是如何限制的:
① getAppStartModeLOSP 核心逻辑:

 final int startMode = (alwaysRestrict)  //当前路径下alwaysRestrict = true
                        ? appRestrictedInBackgroundLOSP(uid, packageName, packageTargetSdk)
                        : appServicesRestrictedInBackgroundLOSP(uid, packageName,
                                packageTargetSdk);

而appRestrictedInBackgroundLOSP开头就是版本限制:

int appRestrictedInBackgroundLOSP(int uid, String packageName, int packageTargetSdk) {
        // Apps that target O+ are always subject to background check
        if (packageTargetSdk >= Build.VERSION_CODES.O) {
            if (DEBUG_BACKGROUND_CHECK) {
                Slog.i(TAG, "App " + uid + "/" + packageName + " targets O+, restricted");
            }
            return ActivityManager.APP_START_MODE_DELAYED_RIGID;
        }
...
从调试看,基本都是返回 2 即:APP_START_MODE_DELAYED_RIGID

② intent参数判断

((r.intent.getFlags()&Intent.FLAG_RECEIVER_EXCLUDE_BACKGROUND) != 0)
 
 || (r.intent.getComponent() == null 
     && r.intent.getPackage() == null 
     && ((r.intent.getFlags()& Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND) == 0)
     && !isSignaturePerm(r.requiredPermissions))

二者满足其一,广播接收就会被限制。

不限制条件总结:
首先,intent不包含FLAG_RECEIVER_EXCLUDE_BACKGROUND,在此基础上:

至此,我们已经知道了,为什么发送显示广播、添加FLAG_RECEIVER_INCLUDE_BACKGROUND flag 、满足组件签名权限条件可以绕过后台广播限制。

那么最后,豁免的系统隐式广播是怎么绕过的呢? 还是BOOT_COMPLETED举例分析:

com.android.server.am.UserController#sendLockedBootCompletedBroadcast

    private void sendLockedBootCompletedBroadcast(IIntentReceiver receiver, @UserIdInt int userId) {
        final Intent intent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED, null);
        intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
        intent.addFlags(Intent.FLAG_RECEIVER_NO_ABORT
                | Intent.FLAG_RECEIVER_OFFLOAD
                | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND); // 添加了FLAG_RECEIVER_INCLUDE_BACKGROUND
        mInjector.broadcastIntent(intent, null, receiver, 0, null, null,
                new String[]{android.Manifest.permission.RECEIVE_BOOT_COMPLETED},
                AppOpsManager.OP_NONE,
                getTemporaryAppAllowlistBroadcastOptions(REASON_LOCKED_BOOT_COMPLETED)
                        .toBundle(), true,
                false, MY_PID, SYSTEM_UID,
                Binder.getCallingUid(), Binder.getCallingPid(), userId);
    }

这里明显看到构建Intent的时候,添加了FLAG_RECEIVER_INCLUDE_BACKGROUND。

2.3 厂商魔改分析
经过测试,普通三方应用静态注册的情况下,基于原生系统显式广播/flag/豁免系统广播方式均可拉活应用,但是厂商(小米、华为、荣耀、vivo、oppo)均无法拉活, 主要是针对三方应用非存活状态下广播接收做了限制。

oppo(colorOs14 android 14)为例:
系统日志:

2024-10-24 17:08:54.652  1816-1877  OplusAppStartupManager  system_server                        W  prevent start com.stan.simpledemo, cmp ComponentInfo{com.stan.simpledemo/com.stan.simpledemo.TestReceiver} by broadcast com.stan.evan callingUid 10176, scenePriority = 0

定位到触发的方法:com.android.server.am.OplusAppStartupManager#shouldPreventSendReceiverReal
限制关键方法:com.android.server.am.OplusAppStartupManager#isAllowForSPS

 private SPSCase isAllowForSPS(Intent intent, int callingUid, String pkgName, String cpnName, int uid, String cpnType, ApplicationInfo appInfo) {
        if (this.mOplusStartupStrategy.isInLruProcessesLocked(uid) && uid > 10000) {
            return SPSCase.TRUE;
...
 }

uid大于10000的应用需要进程存活情况下才不会被限制拉活。

其他厂商不做一一分析,这里仅贴下关键系统日志:
xiaomi:

10-24 16:35:34.018  2267  2311 W WakePathChecker: MIUILOG-AutoStart, Service/Provider/Broadcast Reject userId= 0 caller= com.stan.evan callee= com.stan.simpledemo classname=com.stan.simpledemo.TestReceiver action=android.intent.action.EVAN wakeType=2

10-24 16:35:34.018  2267  2311 W BroadcastQueueInjector: Unable to launch app com.stan.simpledemo/10181 for broadcast Intent { act=android.intent.action.EVAN flg=0x10 cmp=com.stan.simpledemo/.TestReceiver }: process is not permitted to  wake path

vivo:

10-24 17:16:29.321  1486  1680 D _V_VivoBroadcastQueueModernImpl: intent:Intent { act=android.intent.action.EVAN flg=0x10 cmp=com.stan.simpledemo/.TestReceiver },toBeFiltered:true,userid:10325,packageName:com.stan.simpledemo

huawei/honor:

10-24 16:48:39.746  1692  3400 I ActivityManager: App 10040/com.stan.simpledemo targets O+, restricted
上一篇 下一篇

猜你喜欢

热点阅读