垃圾软件后台弹窗一直是 Android 生态上难以治理的顽疾,流氓软件利用系统漏洞绕过系统限制,不断从后台弹出广告或实施 Activity 劫持,严重干扰用户正常使用手机,甚至可能造成财产损失或生命威胁,对老年人来说更是苦不堪言。

本文基于 android-security-17.0.0_r3 即 Android 17 + 2026 年 11 月安全补丁,只分析 Background Activity Launch 相关限制,不涉及 AllowCrossUidActivitySwitchFromBelow 等其他同样复用了相关代码的 Activity Security Model 违规检测

官方文档:
https://developer.android.com/guide/components/activities/secure-bal

ATMS

一切的故事,始于 ActivityTaskManagerService.startActivityAsUser()。
(startActivities() 等 API 走另外一个入口,但是最后还是用的 ActivityStarter,这里不赘述)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
private int startActivityAsUser(IApplicationThread caller, String callingPackage,
@Nullable String callingFeatureId, Intent intent, String resolvedType,
IBinder resultTo, String resultWho, int requestCode, int startFlags,
ProfilerInfo profilerInfo, Bundle bOptions, int userId, boolean validateIncomingUser) {
mAmInternal.addCreatorToken(intent, callingPackage);
final int callingPid = Binder.getCallingPid();
final int callingUid = Binder.getCallingUid();
final SafeActivityOptions opts = SafeActivityOptions.fromBundle(
bOptions, callingPid, callingUid);

assertPackageMatchesCallingUid(callingPackage);
enforceNotIsolatedCaller("startActivityAsUser");

if (isSdkSandboxActivityIntent(mContext, intent)) {
SdkSandboxManagerLocal sdkSandboxManagerLocal = LocalManagerRegistry.getManager(
SdkSandboxManagerLocal.class);
sdkSandboxManagerLocal.enforceAllowedToHostSandboxedActivity(
intent, callingUid, callingPackage
);
}

if (Process.isSdkSandboxUid(callingUid)) {
SdkSandboxManagerLocal sdkSandboxManagerLocal = LocalManagerRegistry.getManager(
SdkSandboxManagerLocal.class);
if (sdkSandboxManagerLocal == null) {
throw new IllegalStateException("SdkSandboxManagerLocal not found when starting"
+ " an activity from an SDK sandbox uid.");
}
sdkSandboxManagerLocal.enforceAllowedToStartActivity(intent);
}

userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
callingPid, callingUid, "startActivityAsUser");

// TODO: Switch to user app stacks here.
return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
.setCaller(caller)
.setCallingPackage(callingPackage)
.setCallingFeatureId(callingFeatureId)
.setResolvedType(resolvedType)
.setResultTo(resultTo)
.setResultWho(resultWho)
.setRequestCode(requestCode)
.setStartFlags(startFlags)
.setProfilerInfo(profilerInfo)
.setActivityOptions(opts)
.setUserId(userId)
.execute();
}

ActivityStarter

ActivityStarter.executeRequest() 内调用到 BackgroundActivityStartController 获取 BAL 判断结果

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/**
* Executing activity start request and starts the journey of starting an activity. Here
* begins with performing several preliminary checks. The normally activity launch flow will
* go through {@link #startActivityUnchecked} to {@link #startActivityInner}.
*/
private int executeRequest(Request request) {
// ...
final BalVerdict balVerdict;
if (!abort) {
try {
Trace.traceBegin(Trace.TRACE_TAG_WINDOW_MANAGER,
"shouldAbortBackgroundActivityStart");
BackgroundActivityStartController balController =
mSupervisor.getBackgroundActivityLaunchController();
balVerdict =
balController.checkBackgroundActivityStart(
callingUid,
callingPid,
callingPackage,
realCallingUid,
realCallingPid,
callerApp,
request.originatingPendingIntent,
request.allowBalExemptionForSystemProcess,
resultRecord,
intent,
checkedOptions);
request.logMessage.append(" (").append(balVerdict).append(")");
} finally {
Trace.traceEnd(Trace.TRACE_TAG_WINDOW_MANAGER);
}
} else {
// Sets ALLOW_BY_DEFAULT as default value as the activity launch will be aborted anyway.
balVerdict = BalVerdict.ALLOW_BY_DEFAULT;
}
mLastStartActivityResult = startActivityUnchecked(r, sourceRecord, voiceSession,
request.voiceInteractor, startFlags, checkedOptions,
inTask, inTaskFragment, balVerdict, intentGrants, realCallingUid,
transition, isIndependent, request.userAllowlistStatus);
return mLastStartActivityResult;
}

最终实现在 startActivityInner():

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/**
* Start an activity and determine if the activity should be adding to the top of an existing
* task or delivered new intent to an existing activity. Also manipulating the activity task
* onto requested or valid root-task/display.
*
* Note: This method should only be called from {@link #startActivityUnchecked}.
*/
// TODO(b/152429287): Make it easier to exercise code paths through startActivityInner
@VisibleForTesting
int startActivityInner(final ActivityRecord r, ActivityRecord sourceRecord,
IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
int startFlags, ActivityOptions options, Task inTask,
TaskFragment inTaskFragment, BalVerdict balVerdict,
NeededUriGrants intentGrants, int realCallingUid) {
setInitialState(r, options, inTask, inTaskFragment, startFlags, sourceRecord,
voiceSession, voiceInteractor, balVerdict, realCallingUid);
// ...
// Check if starting activity on given task or on a new task is allowed.
int startResult = isAllowedToStart(r, newTask, targetTask);
if (startResult != START_SUCCESS) {
if (r.resultTo != null) {
r.resultTo.sendResult(INVALID_UID, r.resultWho, r.requestCode, RESULT_CANCELED,
null /* data */, null /* callerToken */, null /* dataGrants */);
}
return startResult;
}
// ...
}

如果返回的 BalVerdict 结果是 block,设置 mCanMoveToFrontCode 和 mDoResume,不将 activity 带到前台:

1
2
3
4
5
6
7
8
9
private void setInitialState(ActivityRecord r, ActivityOptions options, Task inTask,
TaskFragment inTaskFragment, int startFlags,
ActivityRecord sourceRecord, IVoiceInteractionSession voiceSession,
IVoiceInteractor voiceInteractor, BalVerdict balVerdict, int realCallingUid) {
if (mBalVerdict.blocks() && !mService.isBackgroundActivityStartsEnabled()) {
mCanMoveToFrontCode = MOVE_TO_FRONT_AVOID_LEGACY;
mDoResume = false;
}
}

如果 activity 会被启动到新的 task,则在 isAllowedToStart() 内直接阻断:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@VisibleForTesting
int isAllowedToStart(ActivityRecord r, boolean newTask, Task targetTask) {
// Do not allow background activity start in new task or in a task that uid is not present.
// Also do not allow pinned window to start single instance activity in background,
// as it will recreate the window and makes it to foreground.
boolean blockBalInTask = (newTask
|| !targetTask.isUidPresent(mCallingUid)
|| (LAUNCH_SINGLE_INSTANCE == mLaunchMode && targetTask.inPinnedWindowingMode()));

if (mBalVerdict.blocks() && blockBalInTask
&& handleBackgroundActivityAbort(r)) {
Slog.e(TAG, "Abort background activity starts from " + mCallingUid);
return START_ABORTED;
}

BackgroundActivityStartController

BalVerdict

BalVerdict 表示 BAL 判断结果,可以简单当成一个 boolean 一样用,blocks() == true 表示结果为阻止,allows() == true 为允许

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
static class BalVerdict {
static final BalVerdict BLOCK = new BalVerdict(BAL_BLOCK, "Blocked", true);
static final BalVerdict ALLOW_BY_DEFAULT =
new BalVerdict(BAL_ALLOW_DEFAULT, "Default", true);
// Careful using this - it will bypass all ASM checks.
static final BalVerdict ALLOW_PRIVILEGED =
new BalVerdict(BAL_ALLOW_ALLOWLISTED_UID, "PRIVILEGED", true);
private final @BalCode int mCode;
private final String mMessage;
private final boolean mImmutable;
private String mProcessInfo;
// indicates BAL would be blocked because only creator of the PI has the privilege to allow
// BAL, the sender does not have the privilege to allow BAL.
private boolean mOnlyCreatorAllows;
/** indicates that this verdict is based on the real calling UID and not the calling UID */
private boolean mBasedOnRealCaller;
private boolean mAllowlisteUid;
private boolean mInGracePeriod;
private boolean mAllowsNewTask;
private boolean mVisibleOrForeground;
private SparseBooleanArray mAdditionalBalCodes;
boolean blocks() {
return mCode == BAL_BLOCK;
}

boolean allows() {
return !blocks();
}
}

BalState

保存本次判定过程中需要用到的上下文信息,比如是哪个 app 进行的 startActivity(),它有没有前台 activity;所有名字包含 RealCaller RealCallingUid 字样的都暂时用不到,等待下一篇

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
@VisibleForTesting class BalState {
private final String mCallingPackage;
private final int mCallingUid;
private final int mCallingPid;
private final @ActivityTaskManagerService.AppSwitchState int mAppSwitchState;
private final boolean mCallingUidHasVisibleActivity;
private final boolean mCallingUidHasVisibleNotPinnedActivity;
private final boolean mCallingUidHasNonAppVisibleWindow;
private final @ActivityManager.ProcessState int mCallingUidProcState;
private final boolean mIsCallingUidPersistentSystemProcess;
// --- 以下的暂时用不到 ---
final BackgroundStartPrivileges mBalAllowedByPiSender;
final BackgroundStartPrivileges mBalAllowedByPiCreator;
private final String mRealCallingPackage;
private final int mRealCallingUid;
private final int mRealCallingPid;
private final boolean mRealCallingUidHasVisibleActivity;
private final boolean mRealCallingUidHasVisibleNotPinnedActivity;
private final boolean mRealCallingUidHasNonAppVisibleWindow;
private final @ActivityManager.ProcessState int mRealCallingUidProcState;
private final boolean mIsRealCallingUidPersistentSystemProcess;
private final PendingIntentRecord mOriginatingPendingIntent;
// --- 以上的暂时用不到 ---
private final boolean mAllowBalExemptionForSystemProcess;
private final Intent mIntent;
private final WindowProcessController mCallerApp;
private final WindowProcessController mRealCallerApp; // 暂时用不到
private final boolean mIsCallForResult;
private final ActivityOptions mCheckedOptions;
final String mAutoOptInReason;
private final boolean mAutoOptInCaller;
private BalVerdict mResultForCaller;
private BalVerdict mResultForRealCaller; // 暂时用不到


@VisibleForTesting BalState(int callingUid, int callingPid, final String callingPackage,
int realCallingUid, int realCallingPid,
WindowProcessController callerApp,
PendingIntentRecord originatingPendingIntent,
boolean allowBalExemptionForSystemProcess,
ActivityRecord resultRecord,
Intent intent,
ActivityOptions checkedOptions) {
this.mCallingPackage = callingPackage;
mCallingUid = callingUid;
mCallingPid = callingPid;
mRealCallingUid = realCallingUid;
mRealCallingPid = realCallingPid;
mCallerApp = callerApp;
mAllowBalExemptionForSystemProcess = allowBalExemptionForSystemProcess;
mOriginatingPendingIntent = originatingPendingIntent;
mIntent = intent;
mRealCallingPackage = getService().getPackageNameIfUnique(realCallingUid,
realCallingPid);
mIsCallForResult = resultRecord != null;
mCheckedOptions = checkedOptions;
@BackgroundActivityStartMode int callerBackgroundActivityStartMode =
checkedOptions.getPendingIntentCreatorBackgroundActivityStartMode();
@BackgroundActivityStartMode int realCallerBackgroundActivityStartMode =
checkedOptions.getPendingIntentBackgroundActivityStartMode();

if (originatingPendingIntent == null) {
mAutoOptInReason = AUTO_OPT_IN_NOT_PENDING_INTENT;
mAutoOptInCaller = true;
} /* else 暂时不分析*/


if (mAutoOptInCaller) {
// grant BAL privileges unless explicitly opted out
mBalAllowedByPiCreator =
callerBackgroundActivityStartMode == MODE_BACKGROUND_ACTIVITY_START_DENIED
? BackgroundStartPrivileges.NONE
: BackgroundStartPrivileges.ALLOW_BAL;
} else {
// for PendingIntents we restrict BAL based on target_sdk
mBalAllowedByPiCreator = getBackgroundStartPrivilegesAllowedByCreator(
callingUid, callingPackage, checkedOptions);
}

if (mAutoOptInReason != null) {
// grant BAL privileges unless explicitly opted out
mBalAllowedByPiSender = realCallerBackgroundActivityStartMode
== MODE_BACKGROUND_ACTIVITY_START_DENIED
? BackgroundStartPrivileges.NONE
: BackgroundStartPrivileges.ALLOW_BAL;
} else {
// for PendingIntents we restrict BAL based on target_sdk
mBalAllowedByPiSender =
PendingIntentRecord.getBackgroundStartPrivilegesAllowedByCaller(
checkedOptions, realCallingUid, mRealCallingPackage);
}

mAppSwitchState = getService().getBalAppSwitchesState();
mCallingUidProcState = getService().mActiveUids.getUidState(callingUid);
mIsCallingUidPersistentSystemProcess =
mCallingUidProcState <= ActivityManager.PROCESS_STATE_PERSISTENT_UI;
mCallingUidHasVisibleActivity =
getService().mVisibleActivityProcessTracker.hasVisibleActivity(callingUid);
mCallingUidHasVisibleNotPinnedActivity = getService().mVisibleActivityProcessTracker
.hasVisibleNotPinnedActivity(callingUid);
mCallingUidHasNonAppVisibleWindow = getService().mActiveUids.hasNonAppVisibleWindow(
callingUid);
if (realCallingUid == NO_PROCESS_UID) {
// no process provided
mRealCallingUidProcState = PROCESS_STATE_NONEXISTENT;
mRealCallingUidHasVisibleActivity = false;
mRealCallingUidHasNonAppVisibleWindow = false;
mRealCallingUidHasVisibleNotPinnedActivity = false;
mRealCallerApp = null;
mIsRealCallingUidPersistentSystemProcess = false;
} else if (callingUid == realCallingUid) {
mRealCallingUidProcState = mCallingUidProcState;
mRealCallingUidHasVisibleActivity = mCallingUidHasVisibleActivity;
mRealCallingUidHasVisibleNotPinnedActivity = mCallingUidHasVisibleNotPinnedActivity;
mRealCallingUidHasNonAppVisibleWindow = mCallingUidHasNonAppVisibleWindow;
// In the PendingIntent case callerApp is not passed in, so resolve it ourselves.
mRealCallerApp = callerApp == null
? getService().getProcessController(realCallingPid, realCallingUid)
: callerApp;
mIsRealCallingUidPersistentSystemProcess = mIsCallingUidPersistentSystemProcess;
} /* else 暂时不分析*/
}

checkBackgroundActivityStart()

这就是被 ActivityStarter 调用的那个方法,主要逻辑就在里面:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
/**
* Check if a (background) activity start is allowed.
*
* @param callingUid The UID that wants to start the activity.
* @param callingPid The PID that wants to start the activity.
* @param callingPackage The package name that wants to start the activity.
* @param realCallingUid The UID that actually calls this method (only if this handles a
* PendingIntent, otherwise -1)
* @param realCallingPid The PID that actually calls this method (only if this handles a
* * PendingIntent, otherwise -1)
* @param callerApp The process that calls this method (only if not a PendingIntent)
* @param originatingPendingIntent PendingIntentRecord that originated this activity start or
* null if not originated by PendingIntent
* @param allowBalExemptionForSystemProcess If set to true, the
* PendingIntent's sender will allow additional exemptions.
* This is only possible if the sender of the PendingIntent is a system process.
* @param resultRecord If not null, this indicates that the caller expects a result.
* @param intent Intent that should be started.
* @param checkedOptions ActivityOptions to allow specific opt-ins/opt outs.
*
* @return A verdict denoting which BAL rule allows an activity to be started,
* or if the launch should be blocked.
*/
BalVerdict checkBackgroundActivityStart(
int callingUid,
int callingPid,
final String callingPackage,
int realCallingUid,
int realCallingPid,
WindowProcessController callerApp,
PendingIntentRecord originatingPendingIntent,
boolean allowBalExemptionForSystemProcess,
ActivityRecord resultRecord,
Intent intent,
ActivityOptions checkedOptions) {

if (checkedOptions == null) {
// replace null with a constant to simplify evaluation
checkedOptions = ACTIVITY_OPTIONS_SYSTEM_DEFINED;
}

BalState state = new BalState(callingUid, callingPid, callingPackage,
realCallingUid, realCallingPid, callerApp, originatingPendingIntent,
allowBalExemptionForSystemProcess, resultRecord, intent, checkedOptions);

// In the case of an SDK sandbox calling uid, check if the corresponding app uid has a
// visible window.
if (Process.isSdkSandboxUid(state.mRealCallingUid)) {
int realCallingSdkSandboxUidToAppUid =
Process.getAppUidForSdkSandboxUid(state.mRealCallingUid);
// realCallingSdkSandboxUidToAppUid should probably just be used instead (or in addition
// to realCallingUid when calculating resultForRealCaller below.
if (getService().hasActiveVisibleNotPinnedWindow(realCallingSdkSandboxUidToAppUid)) {
state.setResultForRealCaller(new BalVerdict(BAL_ALLOW_SDK_SANDBOX,
"uid in SDK sandbox has visible (non-toast) window").allowNewTask());
return allowBasedOnRealCaller(state);
}
}

// In the case of a PCC calling uid, check if the corresponding app uid has a
// visible window.
if (enablePccFrameworkSupport() && Process.isPrivateComputeCoreUid(state.mRealCallingUid)) {
int realCallingAppUid =
getService().mContext.getPackageManager()
.getAppUidForPrivateComputeCoreUid(state.mRealCallingUid);

if (getService().hasActiveVisibleNotPinnedWindow(realCallingAppUid)) {
state.setResultForRealCaller(new BalVerdict(
BAL_ALLOW_PCC_DEFINING_APP_HAS_VISIBLE_WINDOW,
"PCC process's parent app has visible (non-toast) window")
.allowNewTask());
return allowBasedOnRealCaller(state);
}
}

BalVerdict resultForCaller = checkBackgroundActivityStartAllowedByCaller(state); // <<< 核心
state.setResultForCaller(resultForCaller);

if (!state.hasRealCaller()) {
if (resultForCaller.allows()) {
return allowBasedOnCaller(state);
}
return abortLaunch(state);
}
// 后面的暂时不重要

checkBackgroundActivityStartAllowedByCaller:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/**
* @return A code denoting which BAL rule allows an activity to be started,
* or {@link #BAL_BLOCK} if the launch should be blocked
*/
BalVerdict checkBackgroundActivityStartAllowedByCaller(BalState state) {
boolean evaluateVisibleOnly =
state.mCheckedOptions.getPendingIntentCreatorBackgroundActivityStartMode()
== MODE_BACKGROUND_ACTIVITY_START_ALLOW_IF_VISIBLE;
boolean basedOnRealCaller = false;
if (evaluateVisibleOnly) { // 不重要
return evaluateChain(state, basedOnRealCaller, mCheckCallerVisible,
mCheckCallerNonAppVisible, mCheckCallerProcessAllowsForeground);
}
if (state.isPendingIntent()) { // 不重要
// PendingIntents should mostly be allowed by the sender (real caller) or a permission
// the creator of the PendingIntent has. Visibility should be the exceptional case, so
// test it last (this does not change the result, just the bal code).
return evaluateChain(state, basedOnRealCaller, mCheckCallerIsAllowlistedUid,
mCheckCallerIsAllowlistedComponent, mCheckCallerHasBackgroundPermission,
mCheckCallerHasSawPermission, mCheckCallerHasBgStartAppOp,
mCheckCallerProcessAllowsBackground, mCheckCallerVisible,
mCheckCallerNonAppVisible, mCheckCallerProcessAllowsForeground,
mCheckCallerProcessInGracePeriod);
}
return evaluateChain(state, basedOnRealCaller, mCheckCallerVisible,
mCheckCallerNonAppVisible, mCheckCallerNonActivityTop,
mCheckCallerProcessAllowsForeground, mCheckCallerIsAllowlistedUid,
mCheckCallerIsAllowlistedComponent, mCheckCallerHasBackgroundPermission,
mCheckCallerHasSawPermission, mCheckCallerHasBgStartAppOp,
mCheckCallerProcessAllowsBackground, mCheckCallerProcessInGracePeriod);
}

Evalate Chain

定义一个接口,然后简单的把所有结果进行逻辑或

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
interface BalExemptionCheck {
BalVerdict evaluate(BalState state);
}

private BalVerdict evaluateChain(BalState state, boolean basedOnRealCaller,
BalExemptionCheck... checks) {
BalVerdict result = BalVerdict.BLOCK;
for (BalExemptionCheck check : checks) {
if (!result.allows()) {
result = check.evaluate(state);
} else {
// we already have a result, but may need to fill in a few missing parts
if (check == mCheckCallerProcessInGracePeriod
|| check == mCheckRealCallerProcessInGracePeriod) {
result.setInGracePeriod(check.evaluate(state).allows());
} else if (check == mCheckCallerIsAllowlistedUid
|| check == mCheckRealCallerAllowlistedUid) {
result.setAllowlisteUid(check.evaluate(state).allows());
} else if (DEBUG_ACTIVITY_STARTS) {
result.addAdditionalVerdict(check.evaluate(state));
}
}
}
if (basedOnRealCaller && !result.isImmutable()) {
result.setBasedOnRealCaller();
}
return result;
}

接下来我们就一个一个看这些允许条件都是什么。

mCheckCallerVisible

BackgroundActivityStartController.java;l=1223

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
private final BalExemptionCheck mCheckCallerVisible = state -> {
// This is used to block background activity launch even if the app is still
// visible to user after user clicking home button.

// Normal apps with visible app window will be allowed to start activity if app switching
// is allowed, or apps like live wallpaper with non app visible window will be allowed.
// The home app can start apps even if app switches are usually disallowed.
final boolean appSwitchAllowedOrFg = state.mAppSwitchState == APP_SWITCH_ALLOW
|| state.mAppSwitchState == APP_SWITCH_FG_ONLY
|| isHomeApp(state.mCallingUid, state.mCallingPackage);
if (appSwitchAllowedOrFg && state.mCallingUidHasVisibleNotPinnedActivity) {
return new BalVerdict(BAL_ALLOW_VISIBLE_WINDOW,
"callingUid has visible non-pinned window")
.allowNewTask().setVisibleOrForeground();
}
return BalVerdict.BLOCK;
};

如果没有 disableAppSwitches(),或调用者是当前的桌面 app,则调用 uid 有可见且非 picture-in-picture 画中画模式 activity 时放行。
mCallingUidHasVisibleNotPinnedActivity 在 BalState 构造函数里被赋值,经过 VisibleActivityProcessTracker 后调用进 WindowProcessController:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
/**
* Check if any Activity is visible (or visibility requested) and not pinned.
*/
boolean hasVisibleNotPinnedActivity() {
if (!hasVisibleActivities()) return false;
for (int i = mActivities.size() - 1; i >= 0; --i) {
final ActivityRecord activityRecord = mActivities.get(i);
if ((activityRecord.isVisible() || activityRecord.isVisibleRequested())
&& !activityRecord.inPinnedWindowingMode()) {
return true;
}
}
return false;
}

所以其实就是 ActivityRecord.isVisible() 和 ActivityRecord.isVisibleRequested()。

mCheckCallerNonActivityTop

BackgroundActivityStartController.java;l=1241

1
2
3
4
5
6
7
8
9
10
11
private final BalExemptionCheck mCheckCallerNonActivityTop = state -> {
// Allows if the UID process state is at the top and the app is not yet hosting any
// activities. This is possible if the application starts an activity within its
// `Application#onCreate` method when the process started, identifying a visible activity
// from that app is not possible because the application process has not yet fully attached.
if (state.mCallerApp != null && !state.mCallerApp.hasActivities()
&& state.mCallingUidProcState == PROCESS_STATE_TOP) {
return new BalVerdict(BAL_ALLOW_FOREGROUND, "callingUid is the current top");
}
return BalVerdict.BLOCK;
};

放行没有 activity 但是进程状态为 top 的进程,主要是为了在 Application.onCreate() 里启动 activity 的 app。

mCheckCallerNonAppVisible

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
private BalVerdict checkNonAppVisibleWindow(int uid, boolean hasNonAppVisibleWindow) {
if (hasNonAppVisibleWindow) {
SparseIntArray nonAppVisibleWindowDetails =
getService().mActiveUids.getNonAppVisibleWindowDetails(uid);
if (nonAppVisibleWindowDetails.size() == 1 && nonAppVisibleWindowDetails.get(
WindowManager.LayoutParams.TYPE_WALLPAPER) > 0) {
return new BalVerdict(BAL_ALLOW_WALLPAPER,
"uid has wallpaper window").allowNewTask().setVisibleOrForeground();
}
return new BalVerdict(BAL_ALLOW_NON_APP_VISIBLE_WINDOW,
"uid has non-app visible window " + nonAppVisibleWindowDetails)
.allowNewTask().setVisibleOrForeground();
}
return BalVerdict.BLOCK;
}

private final BalExemptionCheck mCheckCallerNonAppVisible = state ->
checkNonAppVisibleWindow(state.mCallingUid, state.mCallingUidHasNonAppVisibleWindow);

mCallingUidHasNonAppVisibleWindow 通过 getService().mActiveUids.hasNonAppVisibleWindow(callingUid) 获得,MirrorActiveUids 用于以 uid 为 key 跟踪状态

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/** Called when the surface of non-application (exclude toast) window is shown or hidden. */
synchronized void onNonAppSurfaceVisibilityChanged(int uid, int type, boolean visible) {
updateCount(uid, visible, mNumNonAppVisibleWindowMap);
updateCount(uid, visible, getNumNonAppVisibleWindowMapByType(type));
}

private SparseIntArray getNumNonAppVisibleWindowMapByType(int type) {
SparseIntArray result = mNumNonAppVisibleWindowMapByType.get(type);
if (result == null) {
result = new SparseIntArray();
mNumNonAppVisibleWindowMapByType.append(type, result);
}
return result;
}

private void updateCount(int uid, boolean visible, SparseIntArray numNonAppVisibleWindowMap) {
final int index = numNonAppVisibleWindowMap.indexOfKey(uid);
if (index >= 0) {
final int num = numNonAppVisibleWindowMap.valueAt(index) + (visible ? 1 : -1);
if (num > 0) {
numNonAppVisibleWindowMap.setValueAt(index, num);
} else {
numNonAppVisibleWindowMap.removeAt(index);
}
} else if (visible) {
numNonAppVisibleWindowMap.append(uid, 1);
}
}

/**
* Returns {@code true} if the uid has any non-application (exclude toast) window currently
* visible to the user. The application window visibility of a uid can be found from
* {@link VisibleActivityProcessTracker}.
*/
synchronized boolean hasNonAppVisibleWindow(int uid) {
return mNumNonAppVisibleWindowMap.get(uid) > 0;
}

窗口显示或隐藏时会在 WindowState.onSurfaceShownChanged() 里通知 tracker:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
void onSurfaceShownChanged(boolean shown) {
if (mLastShownChangedReported == shown) {
return;
}
mLastShownChangedReported = shown;

if (shown) {
initExclusionRestrictions();
} else {
logExclusionRestrictions(EXCLUSION_LEFT);
logExclusionRestrictions(EXCLUSION_RIGHT);
getDisplayContent().removeImeScreenshotByTarget(this);
}
// Exclude toast because legacy apps may show toast window by themselves, so the misused
// apps won't always be considered as foreground state.
// Exclude private presentations as they can only be shown on private virtual displays and
// shouldn't be the cause of an app be considered foreground.
// Exclude presentations on virtual displays as they are not actually visible.
if (mAttrs.type >= FIRST_SYSTEM_WINDOW
&& mAttrs.type != TYPE_TOAST
&& mAttrs.type != TYPE_PRIVATE_PRESENTATION
&& !(mAttrs.type == TYPE_PRESENTATION && isOnVirtualDisplay())
) {
mWmService.mAtmService.mActiveUids.onNonAppSurfaceVisibilityChanged(mOwnerUid,
mAttrs.type, shown);
}
}

这里 type >= FIRST_SYSTEM_WINDOW 是过滤掉 TYPE_APPLICATION 等窗口(比如 activity),type != TYPE_TOAST 是因为在 BAL 限制刚刚推出的 android 10 的时候 app 还可以从后台显示 toast,后面两个 presentation 的过滤涉及到 CVE-2021-39758 CVE-2023-35674 两个漏洞,会在后面解析漏洞的文章里分析。

mCheckCallerIsAllowlistedUid

BackgroundActivityStartController.java;l=1272

1
2
3
4
5
6
7
8
9
10
private final BalExemptionCheck mCheckCallerIsAllowlistedUid = state -> {
// don't abort for the most important UIDs
final int callingAppId = UserHandle.getAppId(state.mCallingUid);
if (state.mCallingUid == Process.ROOT_UID
|| callingAppId == Process.SYSTEM_UID
|| callingAppId == Process.NFC_UID) {
return new BalVerdict(BAL_ALLOW_ALLOWLISTED_UID, "Important callingUid");
}
return BalVerdict.BLOCK;
};

对于最重要的三个 UID(root、system、nfc)无条件放行,没什么好说的。

mCheckCallerIsAllowlistedComponent

BackgroundActivityStartController.java;l=1283

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
private final BalExemptionCheck mCheckCallerIsAllowlistedComponent = state -> {
// Always allow home application to start activities.
if (isHomeApp(state.mCallingUid, state.mCallingPackage)) {
return new BalVerdict(BAL_ALLOW_ALLOWLISTED_COMPONENT, "Home app").allowNewTask();
}

final int callingAppId = UserHandle.getAppId(state.mCallingUid);
// IME should always be allowed to start activity, like IME settings.
final WindowState imeWindow = getService().mRootWindowContainer.getCurrentImeWindow();
if (imeWindow != null && callingAppId == imeWindow.mOwnerUid) {
return new BalVerdict(BAL_ALLOW_ALLOWLISTED_COMPONENT, "Active ime").allowNewTask();
}

// don't abort if the callingUid is a persistent system process
if (state.mIsCallingUidPersistentSystemProcess) {
return new BalVerdict(BAL_ALLOW_ALLOWLISTED_COMPONENT,
"callingUid is persistent system process").allowNewTask();
}

// don't abort if the caller has the same uid as the recents component
if (getSupervisor().mRecentTasks.isCallerRecents(state.mCallingUid)) {
return new BalVerdict(BAL_ALLOW_ALLOWLISTED_COMPONENT, "Recents Component")
.allowNewTask();
}
// don't abort if the callingUid is the device owner
if (getService().isDeviceOwner(state.mCallingUid)) {
return new BalVerdict(BAL_ALLOW_ALLOWLISTED_COMPONENT, "Device Owner").allowNewTask();
}
// don't abort if the callingUid is a affiliated profile owner
if (getService().isAffiliatedProfileOwner(state.mCallingUid)) {
return new BalVerdict(BAL_ALLOW_ALLOWLISTED_COMPONENT, "Affiliated Profile Owner")
.allowNewTask();
}
// don't abort if the callingUid has companion device
final int callingUserId = UserHandle.getUserId(state.mCallingUid);
if (getService().isAssociatedCompanionApp(callingUserId, state.mCallingUid)) {
return new BalVerdict(BAL_ALLOW_ALLOWLISTED_COMPONENT, "Companion App").allowNewTask();
}
return BalVerdict.BLOCK;
};

isHomeApp() 判断是不是桌面:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
private boolean isHomeApp(int uid, @Nullable String packageName) {
WindowProcessController homeProcess = getService().mHomeProcess;
if (homeProcess != null && (homeProcess.mUid != SYSTEM_UID || packageName == null)) {
// Fast check (skip if sharing system UID and we have a package name)
return uid == homeProcess.mUid;
}
if (packageName == null) {
return false;
}
ComponentName activity =
getService().getPackageManagerInternalLocked()
.getDefaultHomeActivity(UserHandle.getUserId(uid));
return activity != null && packageName.equals(activity.getPackageName());
}

mIsCallingUidPersistentSystemProcess 取决于进程状态,一般只有设置了 android:persistent=true (比如 SystemUI),被系统以 BIND_ABOVE_CLIENT、BIND_IMPORTANT 绑定的系统服务,或者不受 AMS 管理的 native 进程会符合这一条

1
2
3
mCallingUidProcState = getService().mActiveUids.getUidState(callingUid);
mIsCallingUidPersistentSystemProcess =
mCallingUidProcState <= ActivityManager.PROCESS_STATE_PERSISTENT_UI;

isCallerRecents() 就是和系统内部保存的 recents UID 进行比对,这里 recents 是最近任务屏幕,一般是 Launcher 或者 SystemUI

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/**
* Keeps track of the static recents package/component which is granted additional permissions
* to call recents-related APIs.
*/
private int mRecentsUid = -1;
/**
* Loads the static recents component. This is called after the system is ready, but before
* any dependent services (like SystemUI) is started.
*/
void loadRecentsComponent(Resources res) {
final String rawRecentsComponent = res.getString(
com.android.internal.R.string.config_recentsComponentName);
if (TextUtils.isEmpty(rawRecentsComponent)) {
return;
}

final ComponentName cn = ComponentName.unflattenFromString(rawRecentsComponent);
if (cn != null) {
try {
final ApplicationInfo appInfo = AppGlobals.getPackageManager().getApplicationInfo(
cn.getPackageName(),
PackageManager.MATCH_UNINSTALLED_PACKAGES
| PackageManager.MATCH_DISABLED_COMPONENTS,
mService.mContext.getUserId());
if (appInfo != null) {
mRecentsUid = appInfo.uid;
mRecentsComponent = cn;
}
} catch (RemoteException e) {
Slog.w(TAG, "Could not load application info for recents component: " + cn);
}
}
}
/**
* @return whether the current caller has the same uid as the recents component.
*/
boolean isCallerRecents(int callingUid) {
return isSameApp(callingUid, mRecentsUid);
}

isDeviceOwner() 和 isAffiliatedProfileOwner() 判断是不是符合条件的设备管理应用,这个 Affiliated Profile Owner 是专用设备上的概念,见文档
ActivityTaskManagerService.java;l=6362

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
boolean isDeviceOwner(int uid) {
return uid >= 0 && mDeviceOwnerUid == uid;
}

void setDeviceOwnerUid(int uid) {
mDeviceOwnerUid = uid;
}

boolean isAffiliatedProfileOwner(int uid) {
return uid >= 0 && mProfileOwnerUids.contains(uid)
&& DeviceStateCache.getInstance().hasAffiliationWithDevice(UserHandle.getUserId(uid));
}

void setProfileOwnerUids(Set<Integer> uids) {
mProfileOwnerUids = uids;
}

isAssociatedCompanionApp() 就是检查有没有配套设备(比如手表)连接

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// A map userId and all its companion app uids
private final Map<Integer, Set<Integer>> mCompanionAppUidsMap = new ArrayMap<>();
boolean isAssociatedCompanionApp(int userId, int uid) {
final Set<Integer> allUids = mCompanionAppUidsMap.get(userId);
if (allUids == null) {
return false;
}
return allUids.contains(uid);
}
@Override
public void setCompanionAppUids(int userId, Set<Integer> companionAppUids) {
synchronized (mGlobalLock) {
mCompanionAppUidsMap.put(userId, companionAppUids);
}
}

CompanionExemptionProcessor.java;l=116

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
public CompanionExemptionProcessor(Context context, PowerExemptionManager powerExemptionManager,
AppOpsManager appOpsManager, PackageManagerInternal packageManager,
ActivityTaskManagerInternal atmInternal, ActivityManagerInternal amInternal,
AssociationStore associationStore, CompanionExemptionStore companionExemptionStore) {
mAssociationStore.registerLocalListener(new AssociationStore.OnChangeListener() {
@Override
public void onAssociationChanged(int changeType, AssociationInfo association) {
final int userId = association.getUserId();
final List<AssociationInfo> updatedAssociations =
mAssociationStore.getActiveAssociationsByUser(userId);

updateAtm(userId, updatedAssociations);
}
});
}

/**
* Update ActivityManager and ActivityTaskManager exemptions
*/
public void updateAtm(int userId, List<AssociationInfo> associations) {
final Set<Integer> companionAppUids = new ArraySet<>();
for (AssociationInfo association : associations) {
int uid = mPackageManager.getPackageUid(association.getPackageName(), 0, userId);
if (uid >= 0) {
companionAppUids.add(uid);
}
}
if (mAtmInternal != null) {
mAtmInternal.setCompanionAppUids(userId, companionAppUids);
}
if (mAmInternal != null) {
// Make a copy of the set and send it to ActivityManager.
mAmInternal.setCompanionAppUids(userId, new ArraySet<>(companionAppUids));
}
}

mCheckCallerHasBackgroundPermission

如果持有 START_ACTIVITIES_FROM_BACKGROUND 特权则放行

1
2
3
4
5
6
7
8
9
10
11
12
private final BalExemptionCheck mCheckCallerHasBackgroundPermission = state -> {
// don't abort if the callingUid has START_ACTIVITIES_FROM_BACKGROUND permission
if (hasBalPermission(state.mCallingUid, state.mCallingPid)) {
return new BalVerdict(BAL_ALLOW_PERMISSION,
"START_ACTIVITIES_FROM_BACKGROUND permission granted").allowNewTask();
}
return BalVerdict.BLOCK;
};
@VisibleForTesting boolean hasBalPermission(int uid, int pid) {
return ActivityTaskManagerService.checkPermission(START_ACTIVITIES_FROM_BACKGROUND,
pid, uid) == PERMISSION_GRANTED;
}

普通 app 拿不到这个权限,洗洗睡吧

1
2
3
4
<!-- @SystemApi @hide Allows an application to start activities from background -->
<permission android:name="android.permission.START_ACTIVITIES_FROM_BACKGROUND"
android:protectionLevel="signature|privileged|vendorPrivileged|oem|verifier|role"
android:permissionFlags="allowedInPrivateComputeCore" />

mCheckCallerHasSawPermission

用户授权了 SYSTEM_ALERT_WINDOW 悬浮窗权限则放行

1
2
3
4
5
6
7
8
9
private final BalExemptionCheck mCheckCallerHasSawPermission = state -> {
// don't abort if the callingUid has SYSTEM_ALERT_WINDOW permission
if (getService().hasSystemAlertWindowPermission(state.mCallingUid, state.mCallingPid,
state.mCallingPackage)) {
return new BalVerdict(BAL_ALLOW_SAW_PERMISSION,
"SYSTEM_ALERT_WINDOW permission is granted").allowNewTask();
}
return BalVerdict.BLOCK;
};

mCheckCallerHasBgStartAppOp

检查有没有 OP_SYSTEM_EXEMPT_FROM_ACTIVITY_BG_START_RESTRICTION

1
2
3
4
5
6
7
8
9
10
11
12
private final BalExemptionCheck mCheckCallerHasBgStartAppOp = state -> {
// don't abort if the callingUid and callingPackage have the
// OP_SYSTEM_EXEMPT_FROM_ACTIVITY_BG_START_RESTRICTION appop
if (isSystemExemptFlagEnabled() && getService().getAppOpsManager().checkOpNoThrow(
AppOpsManager.OP_SYSTEM_EXEMPT_FROM_ACTIVITY_BG_START_RESTRICTION,
state.mCallingUid, state.mCallingPackage) == AppOpsManager.MODE_ALLOWED) {
return new BalVerdict(BAL_ALLOW_PERMISSION,
"OP_SYSTEM_EXEMPT_FROM_ACTIVITY_BG_START_RESTRICTION appop is granted")
.allowNewTask();
}
return BalVerdict.BLOCK;
};

这个 appop 并没有页面控制,所以一般情况下要么是用户通过 adb shell appops 命令主动授权,要么是拥有 MANAGE_DEVICE_POLICY_APP_EXEMPTIONS 权限(只授予 shell 和 android.app.role.DEVICE_POLICY_MANAGEMENT 这个 role 的持有者)的 app 主动调用 setApplicationExemptions() 放行。

mCheckCallerProcessAllowsForeground / mCheckCallerProcessAllowsBackground / mCheckCallerProcessInGracePeriod

为什么把这三个放一起讲,因为这三个实际上都是 checkProcessAllowsBal()

1
2
3
4
5
6
7
8
9
// Don't abort if the callerApp or other processes of that uid are considered to be in the
// foreground.
private final BalExemptionCheck mCheckCallerProcessAllowsForeground =
state -> checkProcessAllowsBal(state.mCallerApp, state, BAL_CHECK_FOREGROUND);
// Don't abort if the callerApp or other processes of that uid are allowed in any way.
private final BalExemptionCheck mCheckCallerProcessAllowsBackground =
state -> checkProcessAllowsBal(state.mCallerApp, state, BAL_CHECK_BACKGROUND);
private final BalExemptionCheck mCheckCallerProcessInGracePeriod =
state -> checkProcessAllowsBal(state.mCallerApp, state, BAL_CHECK_GRACE_PERIOD);

checkProcessAllowsBal() 的实现如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/**
* Check if the app allows BAL.
* <p>
* See {@link BackgroundLaunchProcessController#areBackgroundActivityStartsAllowed(int, int,
* String, int, boolean, boolean, boolean, long, long, long)} for details on the
* exceptions.
*/
@VisibleForTesting BalVerdict checkProcessAllowsBal(WindowProcessController app,
BalState state, BalCheckConfiguration balCheckConfiguration) {
if (app == null) {
return BalVerdict.BLOCK;
}
// first check the original calling process
final BalVerdict balAllowedForCaller = app
.areBackgroundActivityStartsAllowed(state.mAppSwitchState, balCheckConfiguration);
if (balAllowedForCaller.allows()) {
return balAllowedForCaller.withProcessInfo("callerApp process", app);
} else {
// only if that one wasn't allowed, check the other ones
final ArraySet<WindowProcessController> uidProcesses =
getService().mProcessMap.getProcesses(app.mUid);
if (uidProcesses != null) {
for (int i = uidProcesses.size() - 1; i >= 0; i--) {
final WindowProcessController proc = uidProcesses.valueAt(i);
if (proc != app) {
BalVerdict balAllowedForUid = proc.areBackgroundActivityStartsAllowed(
state.mAppSwitchState, balCheckConfiguration);
if (balAllowedForUid.allows()) {
return balAllowedForUid.withProcessInfo("process", proc);
}
}
}
}
}
return BalVerdict.BLOCK;
}

WindowProcessController & BackgroundLaunchProcessController

进入 WindowProcessController.areBackgroundActivityStartsAllowed(),对 WindowManager service 来说一个进程对应一个 WindowProcessController

1
2
3
4
5
6
7
8
9
BackgroundActivityStartController.BalVerdict areBackgroundActivityStartsAllowed(
int appSwitchState, BalCheckConfiguration checkConfiguration) {
return mBgLaunchController.areBackgroundActivityStartsAllowed(mPid, mUid,
mInfo.packageName, appSwitchState, checkConfiguration,
hasActivityInVisibleTask(), inPinnedWindowingMode(),
mInstrumentingWithBackgroundActivityStartPrivileges,
mAtm.getLastStopAppSwitchesTime(),
mLastActivityLaunchTime, mLastActivityFinishTime);
}

BackgroundLaunchProcessController 是 WindowProcessController 的成员变量,所以也是一个进程对应一个
BackgroundLaunchProcessController.areBackgroundActivityStartsAllowed() 实现如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
BalVerdict areBackgroundActivityStartsAllowed(
int pid, int uid, String packageName,
int appSwitchState, BalCheckConfiguration checkConfiguration,
boolean hasActivityInVisibleTask, boolean inPinnedWindow,
boolean hasBackgroundActivityStartPrivileges,
long lastStopAppSwitchesTime, long lastActivityLaunchTime,
long lastActivityFinishTime) {
// Allow if the proc is instrumenting with background activity starts privs.
if (checkConfiguration.checkOtherExemptions && hasBackgroundActivityStartPrivileges) {
return new BalVerdict(BAL_ALLOW_PERMISSION, /*background*/
"process instrumenting with background activity starts privileges")
.allowNewTask();
}
// Allow if the token is explicitly allowed.
if (checkConfiguration.checkOtherExemptions) {
BalVerdict tokenVerdict = isBackgroundStartAllowedByToken(uid,
packageName, checkConfiguration.isCheckingForFgsStart);
if (tokenVerdict.allows()) {
return tokenVerdict;
}
}
// Allow if the caller is bound by a UID that's currently foreground.
// But still respect the appSwitchState.
if (checkConfiguration.checkVisibility && appSwitchState != APP_SWITCH_DISALLOW
&& isBoundByForegroundUid(checkConfiguration.isCheckingForFgsStart
? mUidHasActiveVisibleWindowPredicate
: mUidHasActiveVisibleNotPinnedWindowPredicate)) {
return new BalVerdict(BAL_ALLOW_BOUND_BY_FOREGROUND, "process bound by foreground uid")
.allowNewTask().setVisibleOrForeground();
}
// Allow if the caller has an activity in any foreground task, unless it's a pinned window
// and not a foreground service start.
if ((checkConfiguration.isCheckingForFgsStart || !inPinnedWindow)
&& checkConfiguration.checkOtherExemptions
&& hasActivityInVisibleTask && appSwitchState != APP_SWITCH_DISALLOW) {
return new BalVerdict(BAL_ALLOW_FOREGROUND, /*background*/
"process has activity in foreground task").setVisibleOrForeground();
}

// If app switching is not allowed, we ignore all the start activity grace period
// exception so apps cannot start itself in onPause() after pressing home button.
if (checkConfiguration.gracePeriod > 0 && appSwitchState == APP_SWITCH_ALLOW) {
// Allow if any activity in the caller has either started or finished very recently, and
// it must be started or finished after last stop app switches time.
if (lastActivityLaunchTime > lastStopAppSwitchesTime
|| lastActivityFinishTime > lastStopAppSwitchesTime) {
final long now = SystemClock.uptimeMillis();
long timeSinceLastStartOrFinish = now - Math.max(lastActivityLaunchTime,
lastActivityFinishTime);
if (timeSinceLastStartOrFinish < checkConfiguration.gracePeriod) {
return new BalVerdict(BAL_ALLOW_GRACE_PERIOD, /*background*/
"within " + checkConfiguration.gracePeriod + "ms grace period ("
+ timeSinceLastStartOrFinish + "ms)");
}
}
}
return BalVerdict.BLOCK;
}

hasBackgroundActivityStartPrivileges

这个来自于 WindowProcessController.mInstrumentingWithBackgroundActivityStartPrivileges,只在有 instrument 正在调试当前 app 的情况下才可能有,不太重要(实际 release build 运行时基本不可能满足),这里简单过一下流程
https://cs.android.com/android/platform/superproject/+/android-security-17.0.0_r3:frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java;l=15474

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// =========================================================
// INSTRUMENTATION
// =========================================================

public boolean startInstrumentation(ComponentName className,
String profileFile, int flags, Bundle arguments,
IInstrumentationWatcher watcher, IUiAutomationConnection uiAutomationConnection,
@CanBeCURRENT @UserIdInt int userId, String abiOverride) {
enforceNotIsolatedCaller("startInstrumentation");
final int callingUid = Binder.getCallingUid();
final int callingPid = Binder.getCallingPid();


if (!Build.IS_DEBUGGABLE && callingUid != ROOT_UID && callingUid != SHELL_UID
&& callingUid != SYSTEM_UID && !hasActiveInstrumentationLocked(callingPid)) {
// If it's not debug build and not called from root/shell/system uid, reject it.
final String msg = "Permission Denial: instrumentation test "
+ className + " from pid=" + callingPid + ", uid=" + callingUid
+ ", pkgName=" + mInternal.getPackageNameByPid(callingPid)
+ " not allowed because it's not started from SHELL";
Slog.wtfQuiet(TAG, msg);
reportStartInstrumentationFailureLocked(watcher, className, msg);
throw new SecurityException(msg);
}
// ...
activeInstr.mHasBackgroundActivityStartsPermission = checkPermission(
START_ACTIVITIES_FROM_BACKGROUND, callingPid, callingUid)
== PackageManager.PERMISSION_GRANTED;
app.setActiveInstrumentation(activeInstr);
}

ProcessRecord.java;l=1049

1
2
3
4
5
6
7
8
9
10
@GuardedBy({"mService", "mProcLock"})
void setActiveInstrumentation(ActiveInstrumentation instr) {
mInstr = instr;
boolean isInstrumenting = instr != null;
mWindowProcessController.setInstrumenting(
isInstrumenting,
isInstrumenting ? instr.mSourceUid : -1,
isInstrumenting && instr.mHasBackgroundActivityStartsPermission);
mService.mProcessStateController.setHasActiveInstrumentation(this, isInstrumenting);
}

WindowProcessController.java;l=784

1
2
3
4
5
6
7
8
9
10
11
12
/**
* Set instrumentation-related info.
*
* If {@code instrumenting} is {@code false}, {@code sourceUid} has to be -1.
*/
public void setInstrumenting(boolean instrumenting, int sourceUid,
boolean hasBackgroundActivityStartPrivileges) {
checkArgument(instrumenting || sourceUid == -1);
mInstrumenting = instrumenting;
mInstrumentationSourceUid = sourceUid;
mInstrumentingWithBackgroundActivityStartPrivileges = hasBackgroundActivityStartPrivileges;
}

isBackgroundStartAllowedByToken

[BackgroundLaunchProcessController.java;l=194](https://cs.android.com/android/platform/superproject/+/android-security-17.0.0_r3:frameworks/base/services/core/java/com/android/server/wm/BackgroundLaunchProcessController.java;l=194

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/**
* A set of tokens that currently contribute to this process being temporarily allowed
* to start activities even if it's not in the foreground. The values of this map are optional
* (can be null) and are used to trace back the grant to the notification token mechanism.
*/
@GuardedBy("this")
private @Nullable ArrayMap<Binder, BackgroundStartPrivileges> mBackgroundStartPrivileges;

/**
* If there are no tokens, we don't allow *by token*. If there are tokens and
* isCheckingForFgsStart is false, we ask the callback if the start is allowed for these tokens,
* otherwise if there is no callback we allow.
*/
private BalVerdict isBackgroundStartAllowedByToken(int uid, String packageName,
boolean isCheckingForFgsStart) {
synchronized (this) {
if (mBackgroundStartPrivileges == null
|| mBackgroundStartPrivileges.isEmpty()) {
// no tokens to allow anything
return BalVerdict.BLOCK;
}
List<IBinder> binderTokens = new ArrayList<>();
for (int i = mBackgroundStartPrivileges.size(); i-- > 0; ) {
BackgroundStartPrivileges backgroundStartPrivileges =
mBackgroundStartPrivileges.valueAt(i);
if (isCheckingForFgsStart) {
if (!backgroundStartPrivileges.allowsBackgroundFgsStarts()) {
continue;
}
return new BalVerdict(BAL_ALLOW_TOKEN, "process allowed by token");
}
if (!backgroundStartPrivileges.allowsBackgroundActivityStarts()) {
continue;
}
if (backgroundStartPrivileges.getOriginatingToken() == null) {
// internal token - always allow
return new BalVerdict(BAL_ALLOW_TOKEN, "process allowed by token")
.allowNewTask();
}
if (mBackgroundActivityStartCallback == null) {
// without a callback accept any token
return new BalVerdict(BAL_ALLOW_TOKEN, "process allowed by token")
.allowNewTask();
}
if (!(Flags.balIgnoreCallback() && CompatChanges.isChangeEnabled(CALLBACK_IS_NOOP,
packageName, UserHandle.getUserHandleForUid(uid)))) {
binderTokens.add(backgroundStartPrivileges.getOriginatingToken());
}
}
if (binderTokens.isEmpty()) {
// no tokens to allow anything
return BalVerdict.BLOCK;
}
// The callback will decide if the token is accepted.
BackgroundActivityStartCallback.BackgroundActivityStartCallbackResult
activityStartAllowed = mBackgroundActivityStartCallback.isActivityStartAllowed(
binderTokens, uid, packageName);
if (!activityStartAllowed.allowed()) {
return BalVerdict.BLOCK;
}
return new BalVerdict(BAL_ALLOW_NOTIFICATION_TOKEN,
"process allowed by callback (token: " + activityStartAllowed.token()
+ ") tokens: " + binderTokens).allowNewTask();
}
}

BackgroundStartPrivileges 是代表临时授予的后台启动能力的对象,有两种类型,一种是不带 token 的,一种是带 token 的。不带 token 的也分三种:ALLOW_BAL 允许启动 activity 和前台服务(因为启动 activity 本身会让进程有前台可见窗口,所以允许 BAL 就隐含了 FGS);ALLOW_FGS 允许启动前台服务但不允许启动 activity,NONE 则什么都不允许。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/**
* Privileges granted to a Process that allows it to execute starts from the background.
* @hide
*/
public final class BackgroundStartPrivileges {
/** No privileges. */
public static final BackgroundStartPrivileges NONE = new BackgroundStartPrivileges(
false, false, null);
/** Allow activity starts (and implies allowing foreground service starts). */
public static final BackgroundStartPrivileges ALLOW_BAL = new BackgroundStartPrivileges(
true, true, null);
/** Allow foreground service starts. */
public static final BackgroundStartPrivileges ALLOW_FGS = new BackgroundStartPrivileges(
false, true, null);

private final boolean mAllowsBackgroundActivityStarts;
private final boolean mAllowsBackgroundForegroundServiceStarts;
private final IBinder mOriginatingToken;

private BackgroundStartPrivileges(boolean allowsBackgroundActivityStarts,
boolean allowsBackgroundForegroundServiceStarts, @Nullable IBinder originatingToken) {
Preconditions.checkArgument(
!allowsBackgroundActivityStarts || allowsBackgroundForegroundServiceStarts,
"backgroundActivityStarts implies bgFgServiceStarts");
mAllowsBackgroundActivityStarts = allowsBackgroundActivityStarts;
mAllowsBackgroundForegroundServiceStarts = allowsBackgroundForegroundServiceStarts;
mOriginatingToken = originatingToken;
}

对于带 token 的对象,通过 BackgroundStartPrivileges.allowBackgroundActivityStarts() 获得,注意这里没有对应的 allowForegroundServiceStarts() 方法,也就是说,带 token 的对象一定是允许 BAL 的(但是还要看 callback):

1
2
3
4
5
6
7
8
9
10
11
12
/**
* Return a token that allows background activity starts and attributes it to a specific
* originatingToken.
*/
public static BackgroundStartPrivileges allowBackgroundActivityStarts(
@Nullable IBinder originatingToken) {
if (originatingToken == null) {
// try to avoid creating new instances
return ALLOW_BAL;
}
return new BackgroundStartPrivileges(true, true, originatingToken);
}

至于这个 token 到底是何方神圣,这个很复杂,我打算在下一篇文章里详细介绍。现在你只需要知道这是 system server 创建的一个 binder 对象,可以在进程之间传递就行了。

言归正传,这个判断检查的是 BackgroundLaunchProcessController 里的 mBackgroundStartPrivileges,也就是检查有没有允许 BAL 的 BackgroundStartPrivileges 附着在了当前进程上。什么时候会发生这种情况?最常见的情况就是当前进程里有服务被特权进程使用 BIND_ALLOW_BACKGROUND_ACTIVITY_STARTS 绑定:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/**
* A running application service.
*/
final class ServiceRecord extends ServiceRecordInternal implements ComponentName.WithComponentName {
// any current binding to this service has BIND_ALLOW_BACKGROUND_ACTIVITY_STARTS flag?
private boolean mIsAllowedBgActivityStartsByBinding;

void updateIsAllowedBgActivityStartsByBinding() {
boolean isAllowedByBinding = false;
for (int conni = connections.size() - 1; conni >= 0; conni--) {
ArrayList<ConnectionRecord> cr = connections.valueAt(conni);
for (int i = 0; i < cr.size(); i++) {
if (cr.get(i).hasFlag(Context.BIND_ALLOW_BACKGROUND_ACTIVITY_STARTS)) {
isAllowedByBinding = true;
break;
}
}
if (isAllowedByBinding) {
break;
}
}
setAllowedBgActivityStartsByBinding(isAllowedByBinding);
}

void setAllowedBgActivityStartsByBinding(boolean newValue) {
mIsAllowedBgActivityStartsByBinding = newValue;
updateParentProcessBgActivityStartsToken();
}

/**
* Whether the process this service runs in should be temporarily allowed to start
* activities from background depends on the current state of both
* {@code mIsAllowedBgActivityStartsByStart} and
* {@code mIsAllowedBgActivityStartsByBinding}. If either is true, this ServiceRecord
* should be contributing as a token in parent ProcessRecord.
*
* @see com.android.server.am.ProcessRecord#addOrUpdateBackgroundStartPrivileges(Binder,
* BackgroundStartPrivileges)
* @see com.android.server.am.ProcessRecord#removeBackgroundStartPrivileges(Binder)
*/
private void updateParentProcessBgActivityStartsToken() {
if (getHostProcess() == null) {
return;
}
BackgroundStartPrivileges backgroundStartPrivileges =
getBackgroundStartPrivilegesWithExclusiveToken();
if (backgroundStartPrivileges.allowsAny()) {
// if the token is already there it's safe to "re-add it" - we're dealing with
// a set of Binder objects
getHostProcess().addOrUpdateBackgroundStartPrivileges(this,
backgroundStartPrivileges);
} else {
getHostProcess().removeBackgroundStartPrivileges(this);
}
}

/**
* Returns {@link BackgroundStartPrivileges} that represents the privileges a specific
* originating token or a generic aggregate token.
*
* If all privileges are associated with the same token (i.e. the service is only allowed due
* to starts) the token will be retained, otherwise (e.g. the privileges were granted by
* bindings) the originating token will be empty.
*/
@Nullable
private BackgroundStartPrivileges getBackgroundStartPrivilegesWithExclusiveToken() {
if (mIsAllowedBgActivityStartsByBinding) {
return BackgroundStartPrivileges.ALLOW_BAL;
}
if (mBackgroundStartPrivilegesByStart.isEmpty()) {
return BackgroundStartPrivileges.NONE;
}
return mBackgroundStartPrivilegesByStartMerged;
}

还有 app 接收到特权进程发送的使用了 setBackgroundActivityStartsAllowed(true) 的广播时,此时 BackgroundStartPrivileges 会被添加到进程状态里,几秒钟后撤销

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
if (brOptions.allowsBackgroundActivityStarts()) {
// See if the caller is allowed to do this. Note we are checking against
// the actual real caller (not whoever provided the operation as say a
// PendingIntent), because that who is actually supplied the arguments.
if (checkComponentPermission(
android.Manifest.permission.START_ACTIVITIES_FROM_BACKGROUND,
realCallingPid, realCallingUid, -1, true)
!= PackageManager.PERMISSION_GRANTED) {
String msg = "Permission Denial: " + intent.getAction()
+ " broadcast from " + callerPackage + " (pid=" + callingPid
+ ", uid=" + callingUid + ")"
+ " requires "
+ android.Manifest.permission.START_ACTIVITIES_FROM_BACKGROUND;
Slog.w(TAG, msg);
throw new SecurityException(msg);
} else {
// We set the token to null since if it wasn't for it we'd allow anyway here
backgroundStartPrivileges = BackgroundStartPrivileges.ALLOW_BAL;
}
}

其实还有 PendingIntent 的情况,但是这篇的重点是直接启动 activity,所以 PendingIntent 放到下期再讲。
ActivityStartCallback 也是只跟 token 有关,所以一起放到下期。

isBoundByForegroundUid

isBoundByForegroundUid 实现如下:

1
2
3
4
5
6
7
8
9
10
11
12
private boolean isBoundByForegroundUid(IntPredicate uidVisibilityPredicate) {
synchronized (this) {
if (mBalOptInBoundClientUids != null) {
for (int i = mBalOptInBoundClientUids.size() - 1; i >= 0; i--) {
if (uidVisibilityPredicate.test(mBalOptInBoundClientUids.get(i))) {
return true;
}
}
}
}
return false;
}

mBalOptInBoundClientUids 是绑定到当前进程提供的服务并且允许了 activity 启动(指定了 BIND_ALLOW_ACTIVITY_STARTS 或者 targetSdkVersion 小于 android 14)的服务。注意这里是 BIND_ALLOW_ACTIVITY_STARTS 不是 BIND_ALLOW_BACKGROUND_ACTIVITY_STARTS,前者不需要特权,后者需要系统特权。当进程 A 绑定到进程 B 时,如果使用前者,则只有 A 在前台时允许 B 启动 activity;而如果使用的是后者,则进程 B 无论如何都能启动 activity,但是 A 需要有系统特权。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/** If enabled BAL are prevented by default in applications targeting U and later. */
@ChangeId
@EnabledSince(targetSdkVersion = Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
@Overridable
private static final long DEFAULT_RESCIND_BAL_FG_PRIVILEGES_BOUND_SERVICE = 261072174;

/** Set of UIDs of clients currently bound to this process and opt in to allow this process to
* launch background activity.
*/
@GuardedBy("this")
private @Nullable IntArray mBalOptInBoundClientUids;

void addBoundClientUid(int clientUid, String clientPackageName, long bindFlags) {
if (!CompatChanges.isChangeEnabled(
DEFAULT_RESCIND_BAL_FG_PRIVILEGES_BOUND_SERVICE,
clientPackageName,
UserHandle.getUserHandleForUid(clientUid))
|| (bindFlags & Context.BIND_ALLOW_ACTIVITY_STARTS) != 0) {
if (mBalOptInBoundClientUids == null) {
mBalOptInBoundClientUids = new IntArray();
}
if (mBalOptInBoundClientUids.indexOf(clientUid) == -1) {
mBalOptInBoundClientUids.add(clientUid);
}
}
}

ServiceRecord.addConnection():

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
void addConnection(IBinder binder, ConnectionRecord c) {
ArrayList<ConnectionRecord> clist = connections.get(binder);
if (clist == null) {
clist = new ArrayList<>();
connections.put(binder, clist);
}
clist.add(c);

// if we have a process attached, add bound client uid of this connection to it
if (getHostProcess() != null) {
getHostProcess().mServices.addBoundClientUid(c.clientUid, c.clientPackageName,
c.getFlags());
getHostProcess().mProfile.addHostingComponentType(HOSTING_COMPONENT_TYPE_BOUND_SERVICE);
}
}

对于 activity 启动,uidVisibilityPredicate 实际上是 ActivityTaskManagerService.hasActiveVisibleNotPinnedWindow(),里面实际上就是判断这个 uid 有没有可见窗口,没什么好说的。

1
2
3
4
5
6
7
8
/** Similar to {@link #hasActiveVisibleWindow(int)}, but only considers non pinned app
* windows */
boolean hasActiveVisibleNotPinnedWindow(int uid) {
if (mVisibleActivityProcessTracker.hasVisibleNotPinnedActivity(uid)) {
return true;
}
return mActiveUids.hasNonAppVisibleWindow(uid);
}

hasActivityInVisibleTask

就是判断进程有没有 activity 在可见 task 里而已

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/**
* The state for oom-adjustment calculation. The higher 16 bits are the activity states, and the
* lower 16 bits are the task layer rank (see {@link Task#mLayerRank}). This field is written by
* window manager and read by activity manager.
*/
private volatile int mActivityStateFlags = ACTIVITY_STATE_FLAG_MASK_MIN_TASK_LAYER;

boolean hasActivityInVisibleTask() {
return (mActivityStateFlags & ACTIVITY_STATE_FLAG_HAS_ACTIVITY_IN_VISIBLE_TASK) != 0;
}

void computeProcessActivityState() {
// Since there could be more than one activities in a process record, we don't need to
// compute the OomAdj with each of them, just need to find out the activity with the
// "best" state, the order would be visible, pausing, stopping...
for (int i = mActivities.size() - 1; i >= 0; i--) {
final ActivityRecord r = mActivities.get(i);
if (r.isVisible()) {
stateFlags |= ACTIVITY_STATE_FLAG_IS_WINDOW_VISIBLE;
}
final Task task = r.getTask();
if (task == null) {
Slog.e(TAG, "Unexpected detached " + r + " in " + this);
continue;
}
if (task.mLayerRank != Task.LAYER_RANK_INVISIBLE) {
stateFlags |= ACTIVITY_STATE_FLAG_HAS_ACTIVITY_IN_VISIBLE_TASK;
}
// ...
}
}

gracePeriod

lastActivityLaunchTime 和 lastActivityFinishTime 来自上层 WindowProcessController,当有 activity 启动或者被 finish 时会记录最后时间,当然这个 finish 不是说随便找个后台 activity 给它 finish 掉就能过的,在 finish 的时候当前进程需要在可见 task 里有 activity

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// The last time an activity was launched in the process
private volatile long mLastActivityLaunchTime;
// The last time an activity was finished in the process while the process participated
// in a visible task
private volatile long mLastActivityFinishTime;

void setLastActivityLaunchTime(ActivityRecord r) {
long launchTime = r.lastLaunchTime;
if (launchTime <= mLastActivityLaunchTime) {
if (launchTime < mLastActivityLaunchTime) {
Slog.w(TAG,
"Tried to set launchTime (" + launchTime + ") < mLastActivityLaunchTime ("
+ mLastActivityLaunchTime + ")");
}
return;
}
updateRapidActivityLaunch(r, launchTime, mLastActivityLaunchTime);
mLastActivityLaunchTime = launchTime;
}

void setLastActivityFinishTimeIfNeeded(long finishTime) {
if (finishTime <= mLastActivityFinishTime || !hasActivityInVisibleTask()) {
return;
}
mLastActivityFinishTime = finishTime;
}

这个 grace period 具体是多久来自于 BackgroundActivityStartController.BAL_CHECK_GRACE_PERIOD:

1
2
3
4
5
private static final BalCheckConfiguration BAL_CHECK_GRACE_PERIOD = new BalCheckConfiguration(
/* isCheckingForFgsStarts */ false,
/* checkVisibility */ false,
/* checkOtherExemptions */ false,
ACTIVITY_BG_START_GRACE_PERIOD_MS);

目前 ACTIVITY_BG_START_GRACE_PERIOD_MS 被定义为 10 秒钟:

1
2
3
// How long we permit background activity starts after an activity in the process
// started or finished.
static final long ACTIVITY_BG_START_GRACE_PERIOD_MS = 10 * 1000;

也就是说,这条实际上是:如果有 activity 启动或者结束(且结束前该进程在可见 task 里有 activity),即使进程现在不满足可见条件,只要系统没有 stopAppSwitches()(通常是因为用户按 home 键),在 activity 启动或结束的 10 秒钟内该进程仍然可以启动新的 activity。

其他

其实还有很多其他允许情况,比如 startDreamActivity() 就是无条件允许 BAL:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
private IAppTask startDreamActivityLocked(
@NonNull Intent intent,
int callingUid,
int callingPid,
@NonNull WindowProcessController process,
@NonNull ApplicationInfo appInfo) {
final int res =
getActivityStartController()
.obtainStarter(intent, "dream")
.setCallingUid(callingUid)
.setCallingPid(callingPid)
.setCallingPackage(intent.getPackage())
.setActivityInfo(a)
.setActivityOptions(createSafeActivityOptionsWithBalAllowed(options))
.setOutActivity(outActivity)
// To start the dream from background, we need to start it from a persistent
// system process. Here we set the real calling uid to the system server
// uid.
.setRealCallingUid(Binder.getCallingUid())
.setAllowBalExemptionForSystemProcess(true)
.execute();

}

/**
* Wrap the {@link ActivityOptions} in {@link SafeActivityOptions} and attach caller options
* that allow using the callers permissions to start background activities.
*/
private SafeActivityOptions createSafeActivityOptionsWithBalAllowed(
@Nullable ActivityOptions options) {
if (options == null) {
options = ActivityOptions.makeBasic().setPendingIntentBackgroundActivityStartMode(
ActivityOptions.MODE_BACKGROUND_ACTIVITY_START_ALLOWED);
} else if (options.getPendingIntentBackgroundActivityStartMode()
== ActivityOptions.MODE_BACKGROUND_ACTIVITY_START_SYSTEM_DEFINED) {
options.setPendingIntentBackgroundActivityStartMode(
ActivityOptions.MODE_BACKGROUND_ACTIVITY_START_ALLOWED);
}
return new SafeActivityOptions(options, Binder.getCallingPid(), Binder.getCallingUid());
}

其他有这种特殊处理的还有 startActivityAsCaller()、startVoiceActivity()、startAssistantActivity() 等,但是这些 API 基本都需要权限,不在我们讨论范围之内。

总结

经过如上分析,我们得到结论,在 Android 17 上,一个 app 直接调用 startActivity() 能成功启动 activity 需要满足以下任意一条:

  • 调用 App 有前台可见的(且不处于 PiP 模式的) Activity
  • 调用进程处于 top 状态(且当前没有 activity)
  • 调用 App 有不是 toast 且不在 virtual display 上的其他系统类型可见窗口,比如壁纸(注:从 Android 17 QPR2 开始,在非手表设备上壁纸窗口需要用户在 10 秒内和壁纸有交互才可以)
  • 调用 App 是 ROOT/SYSTEM/NFC UID
  • 调用 App 是当前的桌面
  • 调用 App 是当前的输入法
  • 调用 App 是设置了 android:persistent=true 或者被系统以 BIND_ABOVE_CLIENT、BIND_IMPORTANT 绑定的关键系统服务,或者是不受 AMS 管理的 native 进程
  • 调用 App 负责显示最近任务屏幕,通常是系统自带的启动器 App 或者 SystemUI
  • 调用 App 是专用设备上的设备管理应用
  • 调用 App 连接了配套设备,这里指的是通过 CompanionDeviceManager 建立的连接,不是说自己申请蓝牙权限然后配对个设备就算。注:从 Android 18 开始,target Android 18 的 app 不再获得此项豁免,应该是为了缓解在野滥用
  • 调用 App 持有 START_ACTIVITIES_FROM_BACKGROUND 系统级特权
  • 调用 App 持有 SYSTEM_ALERT_WINDOW 悬浮窗权限,这是特殊权限,需要用户手动开启
  • 系统中的其他组件向调用 App 授予了 OP_SYSTEM_EXEMPT_FROM_ACTIVITY_BG_START_RESTRICTION 豁免,比如用户主动使用 adb shell,或者设备策略管理 App 手动授予
  • 调用 App 正在被拥有 START_ACTIVITIES_FROM_BACKGROUND 系统级特权的进程调试
  • 调用 App 被有 START_ACTIVITIES_FROM_BACKGROUND 系统级特权的进程使用 BIND_ALLOW_BACKGROUND_ACTIVITY_STARTS 绑定
  • 调用 App 响应其他进程的 intent,并且发送 intent 的进程主动允许接收者启动 Activity,在收到 intent 之后有几秒钟的时间处于豁免状态
  • 调用 App 被带有 BAL allowlist token 的 intent 启动,具体放到下一章再讲
  • 调用 App 被另一个前台可见的 App 绑定,且该 App 使用了 BIND_ALLOW_ACTIVITY_STARTS 显式允许,或者 targetSdkVersion 低于 Android 14
  • 调用 App 在可见的 task 里有 Activity
  • 调用 App 在 10 秒内有 Activity 创建或结束,且用户没有按下 home 键
  • 设备 default_background_activity_starts_enabled 这一项 device config 处于打开状态,所以 Google 可以云控开关

看起来很多?其实对于流氓广告 app 来说基本上是没有几条可以满足的。那为什么后台弹广告还是如此泛滥?当然是因为漏洞很好用啊~
自 Android 10 推出 BAL 限制以来,各种流氓 app 各显神通,想出一切办法绕过系统限制弹广告挣钱,而系统的限制逻辑实现在一系列 if 中,任何一个判断出问题都会导致整个防御阵线直接崩塌。
下一篇预计分析 PendingIntent 相关的 BAL 限制逻辑,把整个机制盘一遍就可以好好分析历史漏洞了