From 9c5c42ad035a493d68669628ed7ac21e6fbed7f9 Mon Sep 17 00:00:00 2001 From: Jeff Chang Date: Tue, 18 Jan 2022 18:29:52 +0800 Subject: [RESTRICT AUTOMERGE] Add hide-non-system-overlay flag for HarmfulAppWarningActivity A malicious application could overlay the activity. The overlay is able to be tapped through, which can trick the user into starting a harmful activity. The CL added the flag SYSTEM_FLAG_HIDE_NON_SYSTEM_OVERLAY_WINDOWS for the activity to prevent the tapjacking/overlay attack. Bug: 205595291 Test: atest CtsHarmfulAppWarningHostTestCases Change-Id: Ia1a1ae0dc451e04bf5c31e3cb8cf30a0d8e32991 (cherry picked from commit a04b3666b8619e09e08646c6d5c529d016cbfb47) --- core/java/com/android/internal/app/HarmfulAppWarningActivity.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/core/java/com/android/internal/app/HarmfulAppWarningActivity.java b/core/java/com/android/internal/app/HarmfulAppWarningActivity.java index ce2d229d41b3..33209e110123 100644 --- a/core/java/com/android/internal/app/HarmfulAppWarningActivity.java +++ b/core/java/com/android/internal/app/HarmfulAppWarningActivity.java @@ -16,6 +16,8 @@ package com.android.internal.app; +import static android.view.WindowManager.LayoutParams.SYSTEM_FLAG_HIDE_NON_SYSTEM_OVERLAY_WINDOWS; + import android.content.Context; import android.content.DialogInterface; import android.content.Intent; @@ -27,6 +29,7 @@ import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.TextView; + import com.android.internal.R; /** @@ -48,6 +51,7 @@ public class HarmfulAppWarningActivity extends AlertActivity implements protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); + getWindow().addSystemFlags(SYSTEM_FLAG_HIDE_NON_SYSTEM_OVERLAY_WINDOWS); final Intent intent = getIntent(); mPackageName = intent.getStringExtra(Intent.EXTRA_PACKAGE_NAME); mTarget = intent.getParcelableExtra(Intent.EXTRA_INTENT); -- cgit v1.2.3 From 2c87a8a7cec276a9e4cf88e0ae410fd43ffb0b38 Mon Sep 17 00:00:00 2001 From: Jeff Chang Date: Tue, 18 Jan 2022 18:29:52 +0800 Subject: [RESTRICT AUTOMERGE] Add hide-non-system-overlay flag for HarmfulAppWarningActivity A malicious application could overlay the activity. The overlay is able to be tapped through, which can trick the user into starting a harmful activity. The CL added the flag SYSTEM_FLAG_HIDE_NON_SYSTEM_OVERLAY_WINDOWS for the activity to prevent the tapjacking/overlay attack. Bug: 205595291 Test: atest CtsHarmfulAppWarningHostTestCases Change-Id: Ia1a1ae0dc451e04bf5c31e3cb8cf30a0d8e32991 (cherry picked from commit a04b3666b8619e09e08646c6d5c529d016cbfb47) --- core/java/com/android/internal/app/HarmfulAppWarningActivity.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/core/java/com/android/internal/app/HarmfulAppWarningActivity.java b/core/java/com/android/internal/app/HarmfulAppWarningActivity.java index ce2d229d41b3..33209e110123 100644 --- a/core/java/com/android/internal/app/HarmfulAppWarningActivity.java +++ b/core/java/com/android/internal/app/HarmfulAppWarningActivity.java @@ -16,6 +16,8 @@ package com.android.internal.app; +import static android.view.WindowManager.LayoutParams.SYSTEM_FLAG_HIDE_NON_SYSTEM_OVERLAY_WINDOWS; + import android.content.Context; import android.content.DialogInterface; import android.content.Intent; @@ -27,6 +29,7 @@ import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.TextView; + import com.android.internal.R; /** @@ -48,6 +51,7 @@ public class HarmfulAppWarningActivity extends AlertActivity implements protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); + getWindow().addSystemFlags(SYSTEM_FLAG_HIDE_NON_SYSTEM_OVERLAY_WINDOWS); final Intent intent = getIntent(); mPackageName = intent.getStringExtra(Intent.EXTRA_PACKAGE_NAME); mTarget = intent.getParcelableExtra(Intent.EXTRA_INTENT); -- cgit v1.2.3 From 53ee9c2472ddba0974e0b6b5dc33dbad67509199 Mon Sep 17 00:00:00 2001 From: Jeff Chang Date: Tue, 18 Jan 2022 18:29:52 +0800 Subject: [RESTRICT AUTOMERGE] Add hide-non-system-overlay flag for HarmfulAppWarningActivity A malicious application could overlay the activity. The overlay is able to be tapped through, which can trick the user into starting a harmful activity. The CL added the flag SYSTEM_FLAG_HIDE_NON_SYSTEM_OVERLAY_WINDOWS for the activity to prevent the tapjacking/overlay attack. Bug: 205595291 Test: atest CtsHarmfulAppWarningHostTestCases Change-Id: Ia1a1ae0dc451e04bf5c31e3cb8cf30a0d8e32991 (cherry picked from commit a04b3666b8619e09e08646c6d5c529d016cbfb47) --- core/java/com/android/internal/app/HarmfulAppWarningActivity.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/core/java/com/android/internal/app/HarmfulAppWarningActivity.java b/core/java/com/android/internal/app/HarmfulAppWarningActivity.java index ce2d229d41b3..33209e110123 100644 --- a/core/java/com/android/internal/app/HarmfulAppWarningActivity.java +++ b/core/java/com/android/internal/app/HarmfulAppWarningActivity.java @@ -16,6 +16,8 @@ package com.android.internal.app; +import static android.view.WindowManager.LayoutParams.SYSTEM_FLAG_HIDE_NON_SYSTEM_OVERLAY_WINDOWS; + import android.content.Context; import android.content.DialogInterface; import android.content.Intent; @@ -27,6 +29,7 @@ import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.TextView; + import com.android.internal.R; /** @@ -48,6 +51,7 @@ public class HarmfulAppWarningActivity extends AlertActivity implements protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); + getWindow().addSystemFlags(SYSTEM_FLAG_HIDE_NON_SYSTEM_OVERLAY_WINDOWS); final Intent intent = getIntent(); mPackageName = intent.getStringExtra(Intent.EXTRA_PACKAGE_NAME); mTarget = intent.getParcelableExtra(Intent.EXTRA_INTENT); -- cgit v1.2.3 From d5abccff3c61b81aeb67d6fda10d9a27d3e326bd Mon Sep 17 00:00:00 2001 From: Hui Yu Date: Mon, 7 Feb 2022 10:12:49 -0800 Subject: BG-FGS-start while-in-use permission restriction improvement. [This is a resbumit, previous fix ag/I0aca484e5a0dd051bbeac379d30b0fb4ecfa2da0 was reverted because the incorrect resetFgsRestrictionLocked() call] Foreground service started from background shall not have while-in-use access like location/camera/microphone. Previously we set mAllowWhileInUsePermissionInFgs only at service start by startService() or bindService() command. But after service start, the Service.startForeground() call may be some time later and at that time the caller may not be in the foreground any more. This CL will add further restriction on that. 1. If the first Service.startForeground() call is more than 10 seconds (can be configured by DeviceConfig key "fgs_start_foreground_timeout") after the Context.startService() call, check the service's app proc state and set mAllowWhileInUsePermissionInFgs again. 2. At Service.stopForeground() call, mAllowWhileInUsePermissionInFgs should be reset to false so FGS while-in-use permission is not allowed. 3. After Context.startForegroundService()(or Context.startService()) -> Service.startForeground() -> Service.stopForeground(), the second or more times Service.startForeground() is called, check the service's app proc state and set mAllowWhileInUsePermissionInFgs again. This CL is the backport of ag/Idc88f274c7a323d175d65bb47eca041772ae9bb7 from S branch. Bug: 183147114 Bug: 183204439 Test: atest cts/tests/app/src/android/app/cts/ActivityManagerFgsBgStartTest.java#testStartForegroundTimeout Test: atest cts/tests/app/src/android/app/cts/ActivityManagerFgsBgStartTest.java#testSecondStartForeground Change-Id: Ie8712b8efe85aa8a6769b811c85a29c4013e58b9 Merged-In: Idc88f274c7a323d175d65bb47eca041772ae9bb7 --- .../java/com/android/server/am/ActiveServices.java | 107 +++++++++++++++++---- .../server/am/ActivityManagerConstants.java | 20 ++++ .../java/com/android/server/am/ServiceRecord.java | 6 ++ 3 files changed, 112 insertions(+), 21 deletions(-) diff --git a/services/core/java/com/android/server/am/ActiveServices.java b/services/core/java/com/android/server/am/ActiveServices.java index b8de4a759b60..c82a45feb682 100644 --- a/services/core/java/com/android/server/am/ActiveServices.java +++ b/services/core/java/com/android/server/am/ActiveServices.java @@ -734,11 +734,8 @@ public final class ActiveServices { } ComponentName cmp = startServiceInnerLocked(smap, service, r, callerFg, addToStarting); - if (!r.mAllowWhileInUsePermissionInFgs) { - r.mAllowWhileInUsePermissionInFgs = - shouldAllowWhileInUsePermissionInFgsLocked(callingPackage, callingPid, - callingUid, service, r, allowBackgroundActivityStarts); - } + setFgsRestrictionLocked(callingPackage, callingPid, callingUid, r, + allowBackgroundActivityStarts); return cmp; } @@ -1400,14 +1397,6 @@ public final class ActiveServices { + String.format("0x%08X", manifestType) + " in service element of manifest file"); } - // If the foreground service is not started from TOP process, do not allow it to - // have while-in-use location/camera/microphone access. - if (!r.mAllowWhileInUsePermissionInFgs) { - Slog.w(TAG, - "Foreground service started from background can not have " - + "location/camera/microphone access: service " - + r.shortInstanceName); - } } boolean alreadyStartedOp = false; boolean stopProcStatsOp = false; @@ -1455,6 +1444,56 @@ public final class ActiveServices { ignoreForeground = true; } + if (!ignoreForeground) { + if (r.mStartForegroundCount == 0) { + /* + If the service was started with startService(), not + startForegroundService(), and if startForeground() isn't called within + mFgsStartForegroundTimeoutMs, then we check the state of the app + (who owns the service, which is the app that called startForeground()) + again. If the app is in the foreground, or in any other cases where + FGS-starts are allowed, then we still allow the FGS to be started. + Otherwise, startForeground() would fail. + + If the service was started with startForegroundService(), then the service + must call startForeground() within a timeout anyway, so we don't need this + check. + */ + if (!r.fgRequired) { + final long delayMs = SystemClock.elapsedRealtime() - r.createRealTime; + if (delayMs > mAm.mConstants.mFgsStartForegroundTimeoutMs) { + resetFgsRestrictionLocked(r); + setFgsRestrictionLocked(r.serviceInfo.packageName, r.app.pid, + r.appInfo.uid, r, false); + EventLog.writeEvent(0x534e4554, "183147114", + r.appInfo.uid, + "call setFgsRestrictionLocked again due to " + + "startForegroundTimeout"); + } + } + } else if (r.mStartForegroundCount >= 1) { + // The second or later time startForeground() is called after service is + // started. Check for app state again. + final long delayMs = SystemClock.elapsedRealtime() - + r.mLastSetFgsRestrictionTime; + if (delayMs > mAm.mConstants.mFgsStartForegroundTimeoutMs) { + setFgsRestrictionLocked(r.serviceInfo.packageName, r.app.pid, + r.appInfo.uid, r, false); + EventLog.writeEvent(0x534e4554, "183147114", r.appInfo.uid, + "call setFgsRestrictionLocked for " + + (r.mStartForegroundCount + 1) + "th startForeground"); + } + } + // If the foreground service is not started from TOP process, do not allow it to + // have while-in-use location/camera/microphone access. + if (!r.mAllowWhileInUsePermissionInFgs) { + Slog.w(TAG, + "Foreground service started from background can not have " + + "location/camera/microphone access: service " + + r.shortInstanceName); + } + } + // Apps under strict background restrictions simply don't get to have foreground // services, so now that we've enforced the startForegroundService() contract // we only do the machinery of making the service foreground when the app @@ -1490,6 +1529,7 @@ public final class ActiveServices { active.mNumActive++; } r.isForeground = true; + r.mStartForegroundCount++; if (!stopProcStatsOp) { ServiceState stracker = r.getTracker(); if (stracker != null) { @@ -1548,6 +1588,7 @@ public final class ActiveServices { decActiveForegroundAppLocked(smap, r); } r.isForeground = false; + resetFgsRestrictionLocked(r); ServiceState stracker = r.getTracker(); if (stracker != null) { stracker.setForeground(false, mAm.mProcessStats.getMemFactorLocked(), @@ -2107,12 +2148,7 @@ public final class ActiveServices { } } - if (!s.mAllowWhileInUsePermissionInFgs) { - s.mAllowWhileInUsePermissionInFgs = - shouldAllowWhileInUsePermissionInFgsLocked(callingPackage, - callingPid, callingUid, - service, s, false); - } + setFgsRestrictionLocked(callingPackage, callingPid, callingUid, s, false); if (s.app != null) { if ((flags&Context.BIND_TREAT_LIKE_ACTIVITY) != 0) { @@ -3408,7 +3444,7 @@ public final class ActiveServices { r.isForeground = false; r.foregroundId = 0; r.foregroundNoti = null; - r.mAllowWhileInUsePermissionInFgs = false; + resetFgsRestrictionLocked(r); // Clear start entries. r.clearDeliveredStartsLocked(); @@ -4889,7 +4925,7 @@ public final class ActiveServices { * @return true if allow, false otherwise. */ private boolean shouldAllowWhileInUsePermissionInFgsLocked(String callingPackage, - int callingPid, int callingUid, Intent intent, ServiceRecord r, + int callingPid, int callingUid, ServiceRecord r, boolean allowBackgroundActivityStarts) { // Is the background FGS start restriction turned on? if (!mAm.mConstants.mFlagBackgroundFgsStartRestrictionEnabled) { @@ -4960,4 +4996,33 @@ public final class ActiveServices { } return false; } + + boolean canAllowWhileInUsePermissionInFgsLocked(int callingPid, int callingUid, + String callingPackage) { + return shouldAllowWhileInUsePermissionInFgsLocked( + callingPackage, callingPid, callingUid, null, false); + } + + /** + * In R, mAllowWhileInUsePermissionInFgs is to allow while-in-use permissions in foreground + * service or not. while-in-use permissions in FGS started from background might be restricted. + * @param callingPackage caller app's package name. + * @param callingUid caller app's uid. + * @param r the service to start. + * @return true if allow, false otherwise. + */ + private void setFgsRestrictionLocked(String callingPackage, + int callingPid, int callingUid, ServiceRecord r, + boolean allowBackgroundActivityStarts) { + r.mLastSetFgsRestrictionTime = SystemClock.elapsedRealtime(); + if (!r.mAllowWhileInUsePermissionInFgs) { + r.mAllowWhileInUsePermissionInFgs = shouldAllowWhileInUsePermissionInFgsLocked( + callingPackage, callingPid, callingUid, r, allowBackgroundActivityStarts); + } + } + + private void resetFgsRestrictionLocked(ServiceRecord r) { + r.mAllowWhileInUsePermissionInFgs = false; + r.mLastSetFgsRestrictionTime = 0; + } } diff --git a/services/core/java/com/android/server/am/ActivityManagerConstants.java b/services/core/java/com/android/server/am/ActivityManagerConstants.java index 135ac9a7846e..cc1bda76812c 100644 --- a/services/core/java/com/android/server/am/ActivityManagerConstants.java +++ b/services/core/java/com/android/server/am/ActivityManagerConstants.java @@ -87,6 +87,7 @@ final class ActivityManagerConstants extends ContentObserver { static final String KEY_PROCESS_START_ASYNC = "process_start_async"; static final String KEY_MEMORY_INFO_THROTTLE_TIME = "memory_info_throttle_time"; static final String KEY_TOP_TO_FGS_GRACE_DURATION = "top_to_fgs_grace_duration"; + static final String KEY_FGS_START_FOREGROUND_TIMEOUT = "fgs_start_foreground_timeout"; static final String KEY_PENDINGINTENT_WARNING_THRESHOLD = "pendingintent_warning_threshold"; private static final int DEFAULT_MAX_CACHED_PROCESSES = 32; @@ -120,6 +121,7 @@ final class ActivityManagerConstants extends ContentObserver { private static final boolean DEFAULT_PROCESS_START_ASYNC = true; private static final long DEFAULT_MEMORY_INFO_THROTTLE_TIME = 5*60*1000; private static final long DEFAULT_TOP_TO_FGS_GRACE_DURATION = 15 * 1000; + private static final int DEFAULT_FGS_START_FOREGROUND_TIMEOUT_MS = 10 * 1000; private static final int DEFAULT_PENDINGINTENT_WARNING_THRESHOLD = 2000; // Flag stored in the DeviceConfig API. @@ -272,6 +274,12 @@ final class ActivityManagerConstants extends ContentObserver { // this long. public long TOP_TO_FGS_GRACE_DURATION = DEFAULT_TOP_TO_FGS_GRACE_DURATION; + /** + * When service started from background, before the timeout it can be promoted to FGS by calling + * Service.startForeground(). + */ + volatile long mFgsStartForegroundTimeoutMs = DEFAULT_FGS_START_FOREGROUND_TIMEOUT_MS; + // Indicates whether the activity starts logging is enabled. // Controlled by Settings.Global.ACTIVITY_STARTS_LOGGING_ENABLED volatile boolean mFlagActivityStartsLoggingEnabled; @@ -415,6 +423,9 @@ final class ActivityManagerConstants extends ContentObserver { case KEY_MIN_ASSOC_LOG_DURATION: updateMinAssocLogDuration(); break; + case KEY_FGS_START_FOREGROUND_TIMEOUT: + updateFgsStartForegroundTimeout(); + break; default: break; } @@ -687,6 +698,13 @@ final class ActivityManagerConstants extends ContentObserver { /* defaultValue */ DEFAULT_MIN_ASSOC_LOG_DURATION); } + private void updateFgsStartForegroundTimeout() { + mFgsStartForegroundTimeoutMs = DeviceConfig.getLong( + DeviceConfig.NAMESPACE_ACTIVITY_MANAGER, + KEY_FGS_START_FOREGROUND_TIMEOUT, + DEFAULT_FGS_START_FOREGROUND_TIMEOUT_MS); + } + void dump(PrintWriter pw) { pw.println("ACTIVITY MANAGER SETTINGS (dumpsys activity settings) " + Settings.Global.ACTIVITY_MANAGER_CONSTANTS + ":"); @@ -759,6 +777,8 @@ final class ActivityManagerConstants extends ContentObserver { pw.println(Arrays.toString(IMPERCEPTIBLE_KILL_EXEMPT_PACKAGES.toArray())); pw.print(" "); pw.print(KEY_MIN_ASSOC_LOG_DURATION); pw.print("="); pw.println(MIN_ASSOC_LOG_DURATION); + pw.print(" "); pw.print(KEY_FGS_START_FOREGROUND_TIMEOUT); pw.print("="); + pw.println(mFgsStartForegroundTimeoutMs); pw.println(); if (mOverrideMaxCachedProcesses >= 0) { diff --git a/services/core/java/com/android/server/am/ServiceRecord.java b/services/core/java/com/android/server/am/ServiceRecord.java index 9c96e6e02566..5583c5129287 100644 --- a/services/core/java/com/android/server/am/ServiceRecord.java +++ b/services/core/java/com/android/server/am/ServiceRecord.java @@ -138,6 +138,10 @@ final class ServiceRecord extends Binder implements ComponentName.WithComponentN // allow while-in-use permissions in foreground service or not. // while-in-use permissions in FGS started from background might be restricted. boolean mAllowWhileInUsePermissionInFgs; + // The number of times Service.startForeground() is called; + int mStartForegroundCount; + // Last time mAllowWhileInUsePermissionInFgs is set. + long mLastSetFgsRestrictionTime; // the most recent package that start/bind this service. String mRecentCallingPackage; @@ -400,6 +404,8 @@ final class ServiceRecord extends Binder implements ComponentName.WithComponentN } pw.print(prefix); pw.print("allowWhileInUsePermissionInFgs="); pw.println(mAllowWhileInUsePermissionInFgs); + pw.print(prefix); pw.print("startForegroundCount="); + pw.println(mStartForegroundCount); pw.print(prefix); pw.print("recentCallingPackage="); pw.println(mRecentCallingPackage); if (delayed) { -- cgit v1.2.3 From 6b2d0885cb1cd2598d24808042d6a21e31f3ee1f Mon Sep 17 00:00:00 2001 From: Jeff Chang Date: Tue, 8 Feb 2022 10:13:36 +0000 Subject: Revert "[RESTRICT AUTOMERGE]Only allow system and same app to apply relinquishTaskIdentity" This reverts commit 2844258da4148259305797b09e92a6f16fcf451c. Reason for revert: b/218243793 Change-Id: I28dcf89e8c4f0fdf032537650cb893d20f9801ce Merged-In: Iadc00568b09d0e122eefbe25c0c44820b3c24815 --- services/core/java/com/android/server/wm/Task.java | 49 +++++----------------- .../src/com/android/server/wm/TaskRecordTests.java | 46 +------------------- 2 files changed, 11 insertions(+), 84 deletions(-) diff --git a/services/core/java/com/android/server/wm/Task.java b/services/core/java/com/android/server/wm/Task.java index 9708c98fbb70..98df383579c9 100644 --- a/services/core/java/com/android/server/wm/Task.java +++ b/services/core/java/com/android/server/wm/Task.java @@ -119,7 +119,6 @@ import android.graphics.Point; import android.graphics.Rect; import android.os.Debug; import android.os.IBinder; -import android.os.Process; import android.os.RemoteException; import android.os.SystemClock; import android.os.Trace; @@ -228,11 +227,6 @@ class Task extends WindowContainer { // Do not move the stack as a part of reparenting static final int REPARENT_LEAVE_STACK_IN_PLACE = 2; - /** - * Used to identify if the activity that is installed from device's system image. - */ - boolean mIsEffectivelySystemApp; - String affinity; // The affinity name for this task, or null; may change identity. String rootAffinity; // Initial base affinity, or null; does not change from initial root. String mWindowLayoutAffinity; // Launch param affinity of this task or null. Used when saving @@ -483,24 +477,11 @@ class Task extends WindowContainer { if (r.finishing) return false; - if (mRoot == null || mRoot.finishing) { - // Set this as the candidate root since it isn't finishing. - mRoot = r; - } - - final int uid = mRoot == r ? effectiveUid : r.info.applicationInfo.uid; - if (ignoreRelinquishIdentity - || (mRoot.info.flags & FLAG_RELINQUISH_TASK_IDENTITY) == 0 - || (mRoot.info.applicationInfo.uid != Process.SYSTEM_UID - && !mRoot.info.applicationInfo.isSystemApp() - && mRoot.info.applicationInfo.uid != uid)) { - // No need to relinquish identity, end search. - return true; - } - - // Relinquish to next activity + // Set this as the candidate root since it isn't finishing. mRoot = r; - return false; + + // Only end search if we are ignore relinquishing identity or we are not relinquishing. + return ignoreRelinquishIdentity || (r.info.flags & FLAG_RELINQUISH_TASK_IDENTITY) == 0; } } @@ -948,20 +929,10 @@ class Task extends WindowContainer { * @param info The activity info which could be different from {@code r.info} if set. */ void setIntent(ActivityRecord r, @Nullable Intent intent, @Nullable ActivityInfo info) { - boolean updateIdentity = false; - if (this.intent == null) { - updateIdentity = true; - } else if (!mNeverRelinquishIdentity) { - final ActivityInfo activityInfo = info != null ? info : r.info; - updateIdentity = (effectiveUid == Process.SYSTEM_UID || mIsEffectivelySystemApp - || effectiveUid == activityInfo.applicationInfo.uid); - } - if (updateIdentity) { - mCallingUid = r.launchedFromUid; - mCallingPackage = r.launchedFromPackage; - mCallingFeatureId = r.launchedFromFeatureId; - setIntent(intent != null ? intent : r.intent, info != null ? info : r.info); - } + mCallingUid = r.launchedFromUid; + mCallingPackage = r.launchedFromPackage; + mCallingFeatureId = r.launchedFromFeatureId; + setIntent(intent != null ? intent : r.intent, info != null ? info : r.info); setLockTaskAuth(r); final WindowContainer parent = getParent(); @@ -977,7 +948,8 @@ class Task extends WindowContainer { private void setIntent(Intent _intent, ActivityInfo info) { final boolean isLeaf = isLeafTask(); if (intent == null) { - mNeverRelinquishIdentity = (info.flags & FLAG_RELINQUISH_TASK_IDENTITY) == 0; + mNeverRelinquishIdentity = + (info.flags & FLAG_RELINQUISH_TASK_IDENTITY) == 0; } else if (mNeverRelinquishIdentity && isLeaf) { return; } @@ -990,7 +962,6 @@ class Task extends WindowContainer { rootAffinity = affinity; } effectiveUid = info.applicationInfo.uid; - mIsEffectivelySystemApp = info.applicationInfo.isSystemApp(); stringName = null; if (info.targetActivity == null) { diff --git a/services/tests/wmtests/src/com/android/server/wm/TaskRecordTests.java b/services/tests/wmtests/src/com/android/server/wm/TaskRecordTests.java index 95784468efdd..fb24d868e970 100644 --- a/services/tests/wmtests/src/com/android/server/wm/TaskRecordTests.java +++ b/services/tests/wmtests/src/com/android/server/wm/TaskRecordTests.java @@ -591,14 +591,13 @@ public class TaskRecordTests extends ActivityTestsBase { // one above as finishing. final ActivityRecord activity0 = task.getBottomMostActivity(); activity0.info.flags |= FLAG_RELINQUISH_TASK_IDENTITY; - task.effectiveUid = activity0.getUid(); final ActivityRecord activity1 = new ActivityBuilder(mService).setTask(task).build(); activity1.finishing = true; new ActivityBuilder(mService).setTask(task).build(); assertEquals("The first non-finishing activity and non-relinquishing task identity " + "must be reported.", task.getChildAt(2), task.getRootActivity( - false /*ignoreRelinquishIdentity*/, true /*setToBottomIfNone*/)); + false /*ignoreRelinquishIdentity*/, true /*setToBottomIfNone*/)); } /** @@ -626,7 +625,6 @@ public class TaskRecordTests extends ActivityTestsBase { // Set relinquishTaskIdentity for all activities in the task final ActivityRecord activity0 = task.getBottomMostActivity(); activity0.info.flags |= FLAG_RELINQUISH_TASK_IDENTITY; - task.effectiveUid = activity0.getUid(); final ActivityRecord activity1 = new ActivityBuilder(mService).setTask(task).build(); activity1.info.flags |= FLAG_RELINQUISH_TASK_IDENTITY; @@ -779,7 +777,6 @@ public class TaskRecordTests extends ActivityTestsBase { // Make the current root activity relinquish task identity final ActivityRecord activity0 = task.getBottomMostActivity(); activity0.info.flags |= FLAG_RELINQUISH_TASK_IDENTITY; - task.effectiveUid = activity0.getUid(); // Add an extra activity on top - this will be the new root final ActivityRecord activity1 = new ActivityBuilder(mService).setTask(task).build(); // Add one more on top @@ -874,47 +871,6 @@ public class TaskRecordTests extends ActivityTestsBase { verify(task).setIntent(eq(activity0)); } - /** - * Test {@link Task#updateEffectiveIntent()} when activity with relinquishTaskIdentity but - * another with different uid. This should make the task use the root activity when updating the - * intent. - */ - @Test - public void testUpdateEffectiveIntent_relinquishingWithDifferentUid() { - final ActivityRecord activity0 = new ActivityBuilder(mService) - .setActivityFlags(FLAG_RELINQUISH_TASK_IDENTITY).setCreateTask(true).build(); - final Task task = activity0.getTask(); - - // Add an extra activity on top - new ActivityBuilder(mService).setUid(11).setTask(task).build(); - - spyOn(task); - task.updateEffectiveIntent(); - verify(task).setIntent(eq(activity0)); - } - - /** - * Test {@link Task#updateEffectiveIntent()} with activities set as relinquishTaskIdentity. - * This should make the task use the topmost activity when updating the intent. - */ - @Test - public void testUpdateEffectiveIntent_relinquishingMultipleActivities() { - final ActivityRecord activity0 = new ActivityBuilder(mService) - .setActivityFlags(FLAG_RELINQUISH_TASK_IDENTITY).setCreateTask(true).build(); - final Task task = activity0.getTask(); - task.effectiveUid = activity0.getUid(); - // Add an extra activity on top - final ActivityRecord activity1 = new ActivityBuilder(mService).setTask(task).build(); - activity1.info.flags |= FLAG_RELINQUISH_TASK_IDENTITY; - - // Add an extra activity on top - final ActivityRecord activity2 = new ActivityBuilder(mService).setTask(task).build(); - - spyOn(task); - task.updateEffectiveIntent(); - verify(task).setIntent(eq(activity2)); - } - @Test public void testSaveLaunchingStateWhenConfigurationChanged() { LaunchParamsPersister persister = mService.mStackSupervisor.mLaunchParamsPersister; -- cgit v1.2.3 From 4612f3c1c145bb11a8d269cf718773e457b9f400 Mon Sep 17 00:00:00 2001 From: Jeff Chang Date: Tue, 8 Feb 2022 10:24:59 +0000 Subject: Revert "[RESTRICT AUTOMERGE]Only allow system and same app to apply relinquishTaskIdentity" This reverts commit 6898dea5c953f30c07bb99768cf08729806ebfaa. Reason for revert: b/218243793 Change-Id: Iadc00568b09d0e122eefbe25c0c44820b3c24815 --- services/core/java/com/android/server/wm/Task.java | 49 +++++----------------- .../src/com/android/server/wm/TaskRecordTests.java | 47 +-------------------- 2 files changed, 11 insertions(+), 85 deletions(-) diff --git a/services/core/java/com/android/server/wm/Task.java b/services/core/java/com/android/server/wm/Task.java index fb05a29174f2..b68cc7568940 100644 --- a/services/core/java/com/android/server/wm/Task.java +++ b/services/core/java/com/android/server/wm/Task.java @@ -119,7 +119,6 @@ import android.graphics.Point; import android.graphics.Rect; import android.os.Debug; import android.os.IBinder; -import android.os.Process; import android.os.RemoteException; import android.os.SystemClock; import android.os.Trace; @@ -228,11 +227,6 @@ class Task extends WindowContainer { // Do not move the stack as a part of reparenting static final int REPARENT_LEAVE_STACK_IN_PLACE = 2; - /** - * Used to identify if the activity that is installed from device's system image. - */ - boolean mIsEffectivelySystemApp; - String affinity; // The affinity name for this task, or null; may change identity. String rootAffinity; // Initial base affinity, or null; does not change from initial root. String mWindowLayoutAffinity; // Launch param affinity of this task or null. Used when saving @@ -483,24 +477,11 @@ class Task extends WindowContainer { if (r.finishing) return false; - if (mRoot == null || mRoot.finishing) { - // Set this as the candidate root since it isn't finishing. - mRoot = r; - } - - final int uid = mRoot == r ? effectiveUid : r.info.applicationInfo.uid; - if (ignoreRelinquishIdentity - || (mRoot.info.flags & FLAG_RELINQUISH_TASK_IDENTITY) == 0 - || (mRoot.info.applicationInfo.uid != Process.SYSTEM_UID - && !mRoot.info.applicationInfo.isSystemApp() - && mRoot.info.applicationInfo.uid != uid)) { - // No need to relinquish identity, end search. - return true; - } - - // Relinquish to next activity + // Set this as the candidate root since it isn't finishing. mRoot = r; - return false; + + // Only end search if we are ignore relinquishing identity or we are not relinquishing. + return ignoreRelinquishIdentity || (r.info.flags & FLAG_RELINQUISH_TASK_IDENTITY) == 0; } } @@ -948,20 +929,10 @@ class Task extends WindowContainer { * @param info The activity info which could be different from {@code r.info} if set. */ void setIntent(ActivityRecord r, @Nullable Intent intent, @Nullable ActivityInfo info) { - boolean updateIdentity = false; - if (this.intent == null) { - updateIdentity = true; - } else if (!mNeverRelinquishIdentity) { - final ActivityInfo activityInfo = info != null ? info : r.info; - updateIdentity = (effectiveUid == Process.SYSTEM_UID || mIsEffectivelySystemApp - || effectiveUid == activityInfo.applicationInfo.uid); - } - if (updateIdentity) { - mCallingUid = r.launchedFromUid; - mCallingPackage = r.launchedFromPackage; - mCallingFeatureId = r.launchedFromFeatureId; - setIntent(intent != null ? intent : r.intent, info != null ? info : r.info); - } + mCallingUid = r.launchedFromUid; + mCallingPackage = r.launchedFromPackage; + mCallingFeatureId = r.launchedFromFeatureId; + setIntent(intent != null ? intent : r.intent, info != null ? info : r.info); setLockTaskAuth(r); final WindowContainer parent = getParent(); @@ -977,7 +948,8 @@ class Task extends WindowContainer { private void setIntent(Intent _intent, ActivityInfo info) { final boolean isLeaf = isLeafTask(); if (intent == null) { - mNeverRelinquishIdentity = (info.flags & FLAG_RELINQUISH_TASK_IDENTITY) == 0; + mNeverRelinquishIdentity = + (info.flags & FLAG_RELINQUISH_TASK_IDENTITY) == 0; } else if (mNeverRelinquishIdentity && isLeaf) { return; } @@ -990,7 +962,6 @@ class Task extends WindowContainer { rootAffinity = affinity; } effectiveUid = info.applicationInfo.uid; - mIsEffectivelySystemApp = info.applicationInfo.isSystemApp(); stringName = null; if (info.targetActivity == null) { diff --git a/services/tests/wmtests/src/com/android/server/wm/TaskRecordTests.java b/services/tests/wmtests/src/com/android/server/wm/TaskRecordTests.java index 41bcb05306e6..ddaa586fae8a 100644 --- a/services/tests/wmtests/src/com/android/server/wm/TaskRecordTests.java +++ b/services/tests/wmtests/src/com/android/server/wm/TaskRecordTests.java @@ -616,14 +616,13 @@ public class TaskRecordTests extends ActivityTestsBase { // one above as finishing. final ActivityRecord activity0 = task.getBottomMostActivity(); activity0.info.flags |= FLAG_RELINQUISH_TASK_IDENTITY; - task.effectiveUid = activity0.getUid(); final ActivityRecord activity1 = new ActivityBuilder(mService).setTask(task).build(); activity1.finishing = true; new ActivityBuilder(mService).setTask(task).build(); assertEquals("The first non-finishing activity and non-relinquishing task identity " + "must be reported.", task.getChildAt(2), task.getRootActivity( - false /*ignoreRelinquishIdentity*/, true /*setToBottomIfNone*/)); + false /*ignoreRelinquishIdentity*/, true /*setToBottomIfNone*/)); } /** @@ -651,7 +650,6 @@ public class TaskRecordTests extends ActivityTestsBase { // Set relinquishTaskIdentity for all activities in the task final ActivityRecord activity0 = task.getBottomMostActivity(); activity0.info.flags |= FLAG_RELINQUISH_TASK_IDENTITY; - task.effectiveUid = activity0.getUid(); final ActivityRecord activity1 = new ActivityBuilder(mService).setTask(task).build(); activity1.info.flags |= FLAG_RELINQUISH_TASK_IDENTITY; @@ -804,7 +802,6 @@ public class TaskRecordTests extends ActivityTestsBase { // Make the current root activity relinquish task identity final ActivityRecord activity0 = task.getBottomMostActivity(); activity0.info.flags |= FLAG_RELINQUISH_TASK_IDENTITY; - task.effectiveUid = activity0.getUid(); // Add an extra activity on top - this will be the new root final ActivityRecord activity1 = new ActivityBuilder(mService).setTask(task).build(); // Add one more on top @@ -899,48 +896,6 @@ public class TaskRecordTests extends ActivityTestsBase { verify(task).setIntent(eq(activity0)); } - /** - * Test {@link Task#updateEffectiveIntent()} when activity with relinquishTaskIdentity but - * another with different uid. This should make the task use the root activity when updating the - * intent. - */ - @Test - public void testUpdateEffectiveIntent_relinquishingWithDifferentUid() { - final ActivityRecord activity0 = new ActivityBuilder(mService) - .setActivityFlags(FLAG_RELINQUISH_TASK_IDENTITY).setCreateTask(true).build(); - final Task task = activity0.getTask(); - - // Add an extra activity on top - new ActivityBuilder(mService).setUid(11).setTask(task).build(); - - spyOn(task); - task.updateEffectiveIntent(); - verify(task).setIntent(eq(activity0)); - } - - /** - * Test {@link Task#updateEffectiveIntent()} with activities set as relinquishTaskIdentity. - * This should make the task use the topmost activity when updating the intent. - */ - @Test - public void testUpdateEffectiveIntent_relinquishingMultipleActivities() { - final ActivityRecord activity0 = new ActivityBuilder(mService) - .setActivityFlags(FLAG_RELINQUISH_TASK_IDENTITY).setCreateTask(true).build(); - final Task task = activity0.getTask(); - task.effectiveUid = activity0.getUid(); - // Add an extra activity on top - final ActivityRecord activity1 = new ActivityBuilder(mService).setTask(task).build(); - activity1.info.flags |= FLAG_RELINQUISH_TASK_IDENTITY; - - // Add an extra activity on top - final ActivityRecord activity2 = new ActivityBuilder(mService).setTask(task).build(); - - spyOn(task); - task.updateEffectiveIntent(); - verify(task).setIntent(eq(activity2)); - } - - @Test public void testSaveLaunchingStateWhenConfigurationChanged() { LaunchParamsPersister persister = mService.mStackSupervisor.mLaunchParamsPersister; -- cgit v1.2.3 From e41e04bb8cb930c079597bc0008540461c57ffe1 Mon Sep 17 00:00:00 2001 From: Pinyao Ting Date: Wed, 2 Feb 2022 17:23:02 +0000 Subject: Security fixes for PendingIntent related apis in LauncherApps Allowing arbitrary activityOptions during the creation of PendingIntent is a source of security vulnerability. This CL removes activityOptions from the call-site. Bug: 209607104 Test: manual Change-Id: Id262b9a0de58d8834c85d925cf84bb44b8b99742 Merged-In: Id262b9a0de58d8834c85d925cf84bb44b8b99742 --- core/java/android/content/pm/LauncherApps.java | 10 ++++++---- .../core/java/com/android/server/pm/LauncherAppsService.java | 4 ++-- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/core/java/android/content/pm/LauncherApps.java b/core/java/android/content/pm/LauncherApps.java index a8a5837385cb..0f9acadb11f9 100644 --- a/core/java/android/content/pm/LauncherApps.java +++ b/core/java/android/content/pm/LauncherApps.java @@ -739,7 +739,7 @@ public class LauncherApps { * {@link #startMainActivity(ComponentName, UserHandle, Rect, Bundle)}. * * @param component The ComponentName of the activity to launch - * @param startActivityOptions Options to pass to startActivity + * @param startActivityOptions This parameter is no longer supported * @param user The UserHandle of the profile * @hide */ @@ -751,7 +751,8 @@ public class LauncherApps { Log.i(TAG, "GetMainActivityLaunchIntent " + component + " " + user); } try { - return mService.getActivityLaunchIntent(component, startActivityOptions, user); + // due to b/209607104, startActivityOptions will be ignored + return mService.getActivityLaunchIntent(component, null /* opts */, user); } catch (RemoteException re) { throw re.rethrowFromSystemServer(); } @@ -846,7 +847,7 @@ public class LauncherApps { * * @param packageName The packageName of the shortcut * @param shortcutId The id of the shortcut - * @param opts Options to pass to the PendingIntent + * @param opts This parameter is no longer supported * @param user The UserHandle of the profile */ @Nullable @@ -858,8 +859,9 @@ public class LauncherApps { Log.i(TAG, "GetShortcutIntent " + packageName + "/" + shortcutId + " " + user); } try { + // due to b/209607104, opts will be ignored return mService.getShortcutIntent( - mContext.getPackageName(), packageName, shortcutId, opts, user); + mContext.getPackageName(), packageName, shortcutId, null /* opts */, user); } catch (RemoteException re) { throw re.rethrowFromSystemServer(); } diff --git a/services/core/java/com/android/server/pm/LauncherAppsService.java b/services/core/java/com/android/server/pm/LauncherAppsService.java index 419b72675c49..24b9f48e71a6 100644 --- a/services/core/java/com/android/server/pm/LauncherAppsService.java +++ b/services/core/java/com/android/server/pm/LauncherAppsService.java @@ -815,7 +815,7 @@ public class LauncherAppsService extends SystemService { PendingIntent injectCreatePendingIntent(int requestCode, @NonNull Intent[] intents, int flags, Bundle options, String ownerPackage, int ownerUserId) { return mActivityManagerInternal.getPendingIntentActivityAsApp(requestCode, intents, - flags, options, ownerPackage, ownerUserId); + flags, null /* options */, ownerPackage, ownerUserId); } @Override @@ -1117,7 +1117,7 @@ public class LauncherAppsService extends SystemService { // calling identity to mirror the startActivityAsUser() call which does not validate // the calling user return PendingIntent.getActivityAsUser(mContext, 0 /* requestCode */, launchIntent, - FLAG_IMMUTABLE, opts, user); + FLAG_IMMUTABLE, null /* options */, user); } finally { Binder.restoreCallingIdentity(ident); } -- cgit v1.2.3 From d9101cda976263ce758eb04147c4929e522c379e Mon Sep 17 00:00:00 2001 From: junyulai Date: Wed, 9 Feb 2022 22:47:17 +0800 Subject: [MS55.1] Move NetworkStateSnapshot into module folder Test: TH Bug: 197717846 Change-Id: Ib8bb4d67a1774fdb1594c61aed2ce112ce94972e Merged-In: Ib8bb4d67a1774fdb1594c61aed2ce112ce94972e --- core/java/android/net/NetworkStateSnapshot.aidl | 19 ------------------- 1 file changed, 19 deletions(-) delete mode 100644 core/java/android/net/NetworkStateSnapshot.aidl diff --git a/core/java/android/net/NetworkStateSnapshot.aidl b/core/java/android/net/NetworkStateSnapshot.aidl deleted file mode 100644 index cb602d7927ce..000000000000 --- a/core/java/android/net/NetworkStateSnapshot.aidl +++ /dev/null @@ -1,19 +0,0 @@ -/** - * Copyright (c) 2021, The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.net; - -parcelable NetworkStateSnapshot; -- cgit v1.2.3 From 3021dae9b2e8d74a4620f2d6a050a194b753bc19 Mon Sep 17 00:00:00 2001 From: Hui Yu Date: Wed, 9 Feb 2022 18:14:14 +0000 Subject: Revert "Merge "BG-FGS-start while-in-use permission restriction ..." Revert "Merge "Add test cases for background startForeground() i..." Revert submission 16823812-am-d28c94b9fe6445eba259ecb421887d7e Reason for revert: It cause down stream automerge problem into sv-dev. Reverted Changes: I0f8fb6de7:Merge "BG-FGS-start while-in-use permission restri... I6305f8e37:Merge "Add test cases for background startForegrou... Change-Id: I5bb8470e113fc6ce2de5d90159c22002140208c4 --- .../java/com/android/server/am/ActiveServices.java | 102 +++++---------------- .../server/am/ActivityManagerConstants.java | 20 ---- .../java/com/android/server/am/ServiceRecord.java | 6 -- 3 files changed, 22 insertions(+), 106 deletions(-) diff --git a/services/core/java/com/android/server/am/ActiveServices.java b/services/core/java/com/android/server/am/ActiveServices.java index aa38fd1e6fc4..c7391f27bd43 100644 --- a/services/core/java/com/android/server/am/ActiveServices.java +++ b/services/core/java/com/android/server/am/ActiveServices.java @@ -734,8 +734,11 @@ public final class ActiveServices { } ComponentName cmp = startServiceInnerLocked(smap, service, r, callerFg, addToStarting); - setFgsRestrictionLocked(callingPackage, callingPid, callingUid, r, - allowBackgroundActivityStarts); + if (!r.mAllowWhileInUsePermissionInFgs) { + r.mAllowWhileInUsePermissionInFgs = + shouldAllowWhileInUsePermissionInFgsLocked(callingPackage, callingPid, + callingUid, service, r, allowBackgroundActivityStarts); + } return cmp; } @@ -1408,6 +1411,14 @@ public final class ActiveServices { + String.format("0x%08X", manifestType) + " in service element of manifest file"); } + // If the foreground service is not started from TOP process, do not allow it to + // have while-in-use location/camera/microphone access. + if (!r.mAllowWhileInUsePermissionInFgs) { + Slog.w(TAG, + "Foreground service started from background can not have " + + "location/camera/microphone access: service " + + r.shortInstanceName); + } } boolean alreadyStartedOp = false; boolean stopProcStatsOp = false; @@ -1455,56 +1466,6 @@ public final class ActiveServices { ignoreForeground = true; } - if (!ignoreForeground) { - if (r.mStartForegroundCount == 0) { - /* - If the service was started with startService(), not - startForegroundService(), and if startForeground() isn't called within - mFgsStartForegroundTimeoutMs, then we check the state of the app - (who owns the service, which is the app that called startForeground()) - again. If the app is in the foreground, or in any other cases where - FGS-starts are allowed, then we still allow the FGS to be started. - Otherwise, startForeground() would fail. - - If the service was started with startForegroundService(), then the service - must call startForeground() within a timeout anyway, so we don't need this - check. - */ - if (!r.fgRequired) { - final long delayMs = SystemClock.elapsedRealtime() - r.createRealTime; - if (delayMs > mAm.mConstants.mFgsStartForegroundTimeoutMs) { - resetFgsRestrictionLocked(r); - setFgsRestrictionLocked(r.serviceInfo.packageName, r.app.pid, - r.appInfo.uid, r, false); - EventLog.writeEvent(0x534e4554, "183147114", - r.appInfo.uid, - "call setFgsRestrictionLocked again due to " - + "startForegroundTimeout"); - } - } - } else if (r.mStartForegroundCount >= 1) { - // The second or later time startForeground() is called after service is - // started. Check for app state again. - final long delayMs = SystemClock.elapsedRealtime() - - r.mLastSetFgsRestrictionTime; - if (delayMs > mAm.mConstants.mFgsStartForegroundTimeoutMs) { - setFgsRestrictionLocked(r.serviceInfo.packageName, r.app.pid, - r.appInfo.uid, r, false); - EventLog.writeEvent(0x534e4554, "183147114", r.appInfo.uid, - "call setFgsRestrictionLocked for " - + (r.mStartForegroundCount + 1) + "th startForeground"); - } - } - // If the foreground service is not started from TOP process, do not allow it to - // have while-in-use location/camera/microphone access. - if (!r.mAllowWhileInUsePermissionInFgs) { - Slog.w(TAG, - "Foreground service started from background can not have " - + "location/camera/microphone access: service " - + r.shortInstanceName); - } - } - // Apps under strict background restrictions simply don't get to have foreground // services, so now that we've enforced the startForegroundService() contract // we only do the machinery of making the service foreground when the app @@ -1540,7 +1501,6 @@ public final class ActiveServices { active.mNumActive++; } r.isForeground = true; - r.mStartForegroundCount++; if (!stopProcStatsOp) { ServiceState stracker = r.getTracker(); if (stracker != null) { @@ -1599,7 +1559,6 @@ public final class ActiveServices { decActiveForegroundAppLocked(smap, r); } r.isForeground = false; - resetFgsRestrictionLocked(r); ServiceState stracker = r.getTracker(); if (stracker != null) { stracker.setForeground(false, mAm.mProcessStats.getMemFactorLocked(), @@ -2159,7 +2118,12 @@ public final class ActiveServices { } } - setFgsRestrictionLocked(callingPackage, callingPid, callingUid, s, false); + if (!s.mAllowWhileInUsePermissionInFgs) { + s.mAllowWhileInUsePermissionInFgs = + shouldAllowWhileInUsePermissionInFgsLocked(callingPackage, + callingPid, callingUid, + service, s, false); + } if (s.app != null) { if ((flags&Context.BIND_TREAT_LIKE_ACTIVITY) != 0) { @@ -3455,7 +3419,7 @@ public final class ActiveServices { r.isForeground = false; r.foregroundId = 0; r.foregroundNoti = null; - resetFgsRestrictionLocked(r); + r.mAllowWhileInUsePermissionInFgs = false; // Clear start entries. r.clearDeliveredStartsLocked(); @@ -4936,7 +4900,7 @@ public final class ActiveServices { * @return true if allow, false otherwise. */ private boolean shouldAllowWhileInUsePermissionInFgsLocked(String callingPackage, - int callingPid, int callingUid, ServiceRecord r, + int callingPid, int callingUid, Intent intent, ServiceRecord r, boolean allowBackgroundActivityStarts) { // Is the background FGS start restriction turned on? if (!mAm.mConstants.mFlagBackgroundFgsStartRestrictionEnabled) { @@ -5022,29 +4986,7 @@ public final class ActiveServices { boolean canAllowWhileInUsePermissionInFgsLocked(int callingPid, int callingUid, String callingPackage) { return shouldAllowWhileInUsePermissionInFgsLocked( - callingPackage, callingPid, callingUid, null, false); + callingPackage, callingPid, callingUid, null, null, false); } - /** - * In R, mAllowWhileInUsePermissionInFgs is to allow while-in-use permissions in foreground - * service or not. while-in-use permissions in FGS started from background might be restricted. - * @param callingPackage caller app's package name. - * @param callingUid caller app's uid. - * @param r the service to start. - * @return true if allow, false otherwise. - */ - private void setFgsRestrictionLocked(String callingPackage, - int callingPid, int callingUid, ServiceRecord r, - boolean allowBackgroundActivityStarts) { - r.mLastSetFgsRestrictionTime = SystemClock.elapsedRealtime(); - if (!r.mAllowWhileInUsePermissionInFgs) { - r.mAllowWhileInUsePermissionInFgs = shouldAllowWhileInUsePermissionInFgsLocked( - callingPackage, callingPid, callingUid, r, allowBackgroundActivityStarts); - } - } - - private void resetFgsRestrictionLocked(ServiceRecord r) { - r.mAllowWhileInUsePermissionInFgs = false; - r.mLastSetFgsRestrictionTime = 0; - } } diff --git a/services/core/java/com/android/server/am/ActivityManagerConstants.java b/services/core/java/com/android/server/am/ActivityManagerConstants.java index 00d8208ea118..7be843f17863 100644 --- a/services/core/java/com/android/server/am/ActivityManagerConstants.java +++ b/services/core/java/com/android/server/am/ActivityManagerConstants.java @@ -88,7 +88,6 @@ final class ActivityManagerConstants extends ContentObserver { static final String KEY_PROCESS_START_ASYNC = "process_start_async"; static final String KEY_MEMORY_INFO_THROTTLE_TIME = "memory_info_throttle_time"; static final String KEY_TOP_TO_FGS_GRACE_DURATION = "top_to_fgs_grace_duration"; - static final String KEY_FGS_START_FOREGROUND_TIMEOUT = "fgs_start_foreground_timeout"; static final String KEY_PENDINGINTENT_WARNING_THRESHOLD = "pendingintent_warning_threshold"; private static final int DEFAULT_MAX_CACHED_PROCESSES = 32; @@ -122,7 +121,6 @@ final class ActivityManagerConstants extends ContentObserver { private static final boolean DEFAULT_PROCESS_START_ASYNC = true; private static final long DEFAULT_MEMORY_INFO_THROTTLE_TIME = 5*60*1000; private static final long DEFAULT_TOP_TO_FGS_GRACE_DURATION = 15 * 1000; - private static final int DEFAULT_FGS_START_FOREGROUND_TIMEOUT_MS = 10 * 1000; private static final int DEFAULT_PENDINGINTENT_WARNING_THRESHOLD = 2000; // Flag stored in the DeviceConfig API. @@ -275,12 +273,6 @@ final class ActivityManagerConstants extends ContentObserver { // this long. public long TOP_TO_FGS_GRACE_DURATION = DEFAULT_TOP_TO_FGS_GRACE_DURATION; - /** - * When service started from background, before the timeout it can be promoted to FGS by calling - * Service.startForeground(). - */ - volatile long mFgsStartForegroundTimeoutMs = DEFAULT_FGS_START_FOREGROUND_TIMEOUT_MS; - // Indicates whether the activity starts logging is enabled. // Controlled by Settings.Global.ACTIVITY_STARTS_LOGGING_ENABLED volatile boolean mFlagActivityStartsLoggingEnabled; @@ -429,9 +421,6 @@ final class ActivityManagerConstants extends ContentObserver { case KEY_MIN_ASSOC_LOG_DURATION: updateMinAssocLogDuration(); break; - case KEY_FGS_START_FOREGROUND_TIMEOUT: - updateFgsStartForegroundTimeout(); - break; default: break; } @@ -708,13 +697,6 @@ final class ActivityManagerConstants extends ContentObserver { /* defaultValue */ DEFAULT_MIN_ASSOC_LOG_DURATION); } - private void updateFgsStartForegroundTimeout() { - mFgsStartForegroundTimeoutMs = DeviceConfig.getLong( - DeviceConfig.NAMESPACE_ACTIVITY_MANAGER, - KEY_FGS_START_FOREGROUND_TIMEOUT, - DEFAULT_FGS_START_FOREGROUND_TIMEOUT_MS); - } - void dump(PrintWriter pw) { pw.println("ACTIVITY MANAGER SETTINGS (dumpsys activity settings) " + Settings.Global.ACTIVITY_MANAGER_CONSTANTS + ":"); @@ -787,8 +769,6 @@ final class ActivityManagerConstants extends ContentObserver { pw.println(Arrays.toString(IMPERCEPTIBLE_KILL_EXEMPT_PACKAGES.toArray())); pw.print(" "); pw.print(KEY_MIN_ASSOC_LOG_DURATION); pw.print("="); pw.println(MIN_ASSOC_LOG_DURATION); - pw.print(" "); pw.print(KEY_FGS_START_FOREGROUND_TIMEOUT); pw.print("="); - pw.println(mFgsStartForegroundTimeoutMs); pw.println(); if (mOverrideMaxCachedProcesses >= 0) { diff --git a/services/core/java/com/android/server/am/ServiceRecord.java b/services/core/java/com/android/server/am/ServiceRecord.java index 0e628289a09f..1b65dbac2294 100644 --- a/services/core/java/com/android/server/am/ServiceRecord.java +++ b/services/core/java/com/android/server/am/ServiceRecord.java @@ -142,10 +142,6 @@ final class ServiceRecord extends Binder implements ComponentName.WithComponentN // allow while-in-use permissions in foreground service or not. // while-in-use permissions in FGS started from background might be restricted. boolean mAllowWhileInUsePermissionInFgs; - // The number of times Service.startForeground() is called; - int mStartForegroundCount; - // Last time mAllowWhileInUsePermissionInFgs is set. - long mLastSetFgsRestrictionTime; // the most recent package that start/bind this service. String mRecentCallingPackage; @@ -410,8 +406,6 @@ final class ServiceRecord extends Binder implements ComponentName.WithComponentN } pw.print(prefix); pw.print("allowWhileInUsePermissionInFgs="); pw.println(mAllowWhileInUsePermissionInFgs); - pw.print(prefix); pw.print("startForegroundCount="); - pw.println(mStartForegroundCount); pw.print(prefix); pw.print("recentCallingPackage="); pw.println(mRecentCallingPackage); if (delayed) { -- cgit v1.2.3 From 89db7469f65a8771bd99708ddf5eee8975b0e505 Mon Sep 17 00:00:00 2001 From: Hui Yu Date: Mon, 7 Feb 2022 10:12:49 -0800 Subject: BG-FGS-start while-in-use permission restriction improvement. [This is a resbumit, previous fix ag/I0aca484e5a0dd051bbeac379d30b0fb4ecfa2da0 was reverted because the incorrect resetFgsRestrictionLocked() call] Foreground service started from background shall not have while-in-use access like location/camera/microphone. Previously we set mAllowWhileInUsePermissionInFgs only at service start by startService() or bindService() command. But after service start, the Service.startForeground() call may be some time later and at that time the caller may not be in the foreground any more. This CL will add further restriction on that. 1. If the first Service.startForeground() call is more than 10 seconds (can be configured by DeviceConfig key "fgs_start_foreground_timeout") after the Context.startService() call, check the service's app proc state and set mAllowWhileInUsePermissionInFgs again. 2. At Service.stopForeground() call, mAllowWhileInUsePermissionInFgs should be reset to false so FGS while-in-use permission is not allowed. 3. After Context.startForegroundService()(or Context.startService()) -> Service.startForeground() -> Service.stopForeground(), the second or more times Service.startForeground() is called, check the service's app proc state and set mAllowWhileInUsePermissionInFgs again. This CL is the backport of ag/Idc88f274c7a323d175d65bb47eca041772ae9bb7 from S branch. Bug: 183147114 Bug: 183204439 Test: atest cts/tests/app/src/android/app/cts/ActivityManagerFgsBgStartTest.java#testStartForegroundTimeout Test: atest cts/tests/app/src/android/app/cts/ActivityManagerFgsBgStartTest.java#testSecondStartForeground Change-Id: Ie8712b8efe85aa8a6769b811c85a29c4013e58b9 Merged-In: Idc88f274c7a323d175d65bb47eca041772ae9bb7 --- .../java/com/android/server/am/ActiveServices.java | 102 ++++++++++++++++----- .../server/am/ActivityManagerConstants.java | 20 ++++ .../java/com/android/server/am/ServiceRecord.java | 6 ++ 3 files changed, 106 insertions(+), 22 deletions(-) diff --git a/services/core/java/com/android/server/am/ActiveServices.java b/services/core/java/com/android/server/am/ActiveServices.java index c7391f27bd43..aa38fd1e6fc4 100644 --- a/services/core/java/com/android/server/am/ActiveServices.java +++ b/services/core/java/com/android/server/am/ActiveServices.java @@ -734,11 +734,8 @@ public final class ActiveServices { } ComponentName cmp = startServiceInnerLocked(smap, service, r, callerFg, addToStarting); - if (!r.mAllowWhileInUsePermissionInFgs) { - r.mAllowWhileInUsePermissionInFgs = - shouldAllowWhileInUsePermissionInFgsLocked(callingPackage, callingPid, - callingUid, service, r, allowBackgroundActivityStarts); - } + setFgsRestrictionLocked(callingPackage, callingPid, callingUid, r, + allowBackgroundActivityStarts); return cmp; } @@ -1411,14 +1408,6 @@ public final class ActiveServices { + String.format("0x%08X", manifestType) + " in service element of manifest file"); } - // If the foreground service is not started from TOP process, do not allow it to - // have while-in-use location/camera/microphone access. - if (!r.mAllowWhileInUsePermissionInFgs) { - Slog.w(TAG, - "Foreground service started from background can not have " - + "location/camera/microphone access: service " - + r.shortInstanceName); - } } boolean alreadyStartedOp = false; boolean stopProcStatsOp = false; @@ -1466,6 +1455,56 @@ public final class ActiveServices { ignoreForeground = true; } + if (!ignoreForeground) { + if (r.mStartForegroundCount == 0) { + /* + If the service was started with startService(), not + startForegroundService(), and if startForeground() isn't called within + mFgsStartForegroundTimeoutMs, then we check the state of the app + (who owns the service, which is the app that called startForeground()) + again. If the app is in the foreground, or in any other cases where + FGS-starts are allowed, then we still allow the FGS to be started. + Otherwise, startForeground() would fail. + + If the service was started with startForegroundService(), then the service + must call startForeground() within a timeout anyway, so we don't need this + check. + */ + if (!r.fgRequired) { + final long delayMs = SystemClock.elapsedRealtime() - r.createRealTime; + if (delayMs > mAm.mConstants.mFgsStartForegroundTimeoutMs) { + resetFgsRestrictionLocked(r); + setFgsRestrictionLocked(r.serviceInfo.packageName, r.app.pid, + r.appInfo.uid, r, false); + EventLog.writeEvent(0x534e4554, "183147114", + r.appInfo.uid, + "call setFgsRestrictionLocked again due to " + + "startForegroundTimeout"); + } + } + } else if (r.mStartForegroundCount >= 1) { + // The second or later time startForeground() is called after service is + // started. Check for app state again. + final long delayMs = SystemClock.elapsedRealtime() - + r.mLastSetFgsRestrictionTime; + if (delayMs > mAm.mConstants.mFgsStartForegroundTimeoutMs) { + setFgsRestrictionLocked(r.serviceInfo.packageName, r.app.pid, + r.appInfo.uid, r, false); + EventLog.writeEvent(0x534e4554, "183147114", r.appInfo.uid, + "call setFgsRestrictionLocked for " + + (r.mStartForegroundCount + 1) + "th startForeground"); + } + } + // If the foreground service is not started from TOP process, do not allow it to + // have while-in-use location/camera/microphone access. + if (!r.mAllowWhileInUsePermissionInFgs) { + Slog.w(TAG, + "Foreground service started from background can not have " + + "location/camera/microphone access: service " + + r.shortInstanceName); + } + } + // Apps under strict background restrictions simply don't get to have foreground // services, so now that we've enforced the startForegroundService() contract // we only do the machinery of making the service foreground when the app @@ -1501,6 +1540,7 @@ public final class ActiveServices { active.mNumActive++; } r.isForeground = true; + r.mStartForegroundCount++; if (!stopProcStatsOp) { ServiceState stracker = r.getTracker(); if (stracker != null) { @@ -1559,6 +1599,7 @@ public final class ActiveServices { decActiveForegroundAppLocked(smap, r); } r.isForeground = false; + resetFgsRestrictionLocked(r); ServiceState stracker = r.getTracker(); if (stracker != null) { stracker.setForeground(false, mAm.mProcessStats.getMemFactorLocked(), @@ -2118,12 +2159,7 @@ public final class ActiveServices { } } - if (!s.mAllowWhileInUsePermissionInFgs) { - s.mAllowWhileInUsePermissionInFgs = - shouldAllowWhileInUsePermissionInFgsLocked(callingPackage, - callingPid, callingUid, - service, s, false); - } + setFgsRestrictionLocked(callingPackage, callingPid, callingUid, s, false); if (s.app != null) { if ((flags&Context.BIND_TREAT_LIKE_ACTIVITY) != 0) { @@ -3419,7 +3455,7 @@ public final class ActiveServices { r.isForeground = false; r.foregroundId = 0; r.foregroundNoti = null; - r.mAllowWhileInUsePermissionInFgs = false; + resetFgsRestrictionLocked(r); // Clear start entries. r.clearDeliveredStartsLocked(); @@ -4900,7 +4936,7 @@ public final class ActiveServices { * @return true if allow, false otherwise. */ private boolean shouldAllowWhileInUsePermissionInFgsLocked(String callingPackage, - int callingPid, int callingUid, Intent intent, ServiceRecord r, + int callingPid, int callingUid, ServiceRecord r, boolean allowBackgroundActivityStarts) { // Is the background FGS start restriction turned on? if (!mAm.mConstants.mFlagBackgroundFgsStartRestrictionEnabled) { @@ -4986,7 +5022,29 @@ public final class ActiveServices { boolean canAllowWhileInUsePermissionInFgsLocked(int callingPid, int callingUid, String callingPackage) { return shouldAllowWhileInUsePermissionInFgsLocked( - callingPackage, callingPid, callingUid, null, null, false); + callingPackage, callingPid, callingUid, null, false); } + /** + * In R, mAllowWhileInUsePermissionInFgs is to allow while-in-use permissions in foreground + * service or not. while-in-use permissions in FGS started from background might be restricted. + * @param callingPackage caller app's package name. + * @param callingUid caller app's uid. + * @param r the service to start. + * @return true if allow, false otherwise. + */ + private void setFgsRestrictionLocked(String callingPackage, + int callingPid, int callingUid, ServiceRecord r, + boolean allowBackgroundActivityStarts) { + r.mLastSetFgsRestrictionTime = SystemClock.elapsedRealtime(); + if (!r.mAllowWhileInUsePermissionInFgs) { + r.mAllowWhileInUsePermissionInFgs = shouldAllowWhileInUsePermissionInFgsLocked( + callingPackage, callingPid, callingUid, r, allowBackgroundActivityStarts); + } + } + + private void resetFgsRestrictionLocked(ServiceRecord r) { + r.mAllowWhileInUsePermissionInFgs = false; + r.mLastSetFgsRestrictionTime = 0; + } } diff --git a/services/core/java/com/android/server/am/ActivityManagerConstants.java b/services/core/java/com/android/server/am/ActivityManagerConstants.java index 7be843f17863..00d8208ea118 100644 --- a/services/core/java/com/android/server/am/ActivityManagerConstants.java +++ b/services/core/java/com/android/server/am/ActivityManagerConstants.java @@ -88,6 +88,7 @@ final class ActivityManagerConstants extends ContentObserver { static final String KEY_PROCESS_START_ASYNC = "process_start_async"; static final String KEY_MEMORY_INFO_THROTTLE_TIME = "memory_info_throttle_time"; static final String KEY_TOP_TO_FGS_GRACE_DURATION = "top_to_fgs_grace_duration"; + static final String KEY_FGS_START_FOREGROUND_TIMEOUT = "fgs_start_foreground_timeout"; static final String KEY_PENDINGINTENT_WARNING_THRESHOLD = "pendingintent_warning_threshold"; private static final int DEFAULT_MAX_CACHED_PROCESSES = 32; @@ -121,6 +122,7 @@ final class ActivityManagerConstants extends ContentObserver { private static final boolean DEFAULT_PROCESS_START_ASYNC = true; private static final long DEFAULT_MEMORY_INFO_THROTTLE_TIME = 5*60*1000; private static final long DEFAULT_TOP_TO_FGS_GRACE_DURATION = 15 * 1000; + private static final int DEFAULT_FGS_START_FOREGROUND_TIMEOUT_MS = 10 * 1000; private static final int DEFAULT_PENDINGINTENT_WARNING_THRESHOLD = 2000; // Flag stored in the DeviceConfig API. @@ -273,6 +275,12 @@ final class ActivityManagerConstants extends ContentObserver { // this long. public long TOP_TO_FGS_GRACE_DURATION = DEFAULT_TOP_TO_FGS_GRACE_DURATION; + /** + * When service started from background, before the timeout it can be promoted to FGS by calling + * Service.startForeground(). + */ + volatile long mFgsStartForegroundTimeoutMs = DEFAULT_FGS_START_FOREGROUND_TIMEOUT_MS; + // Indicates whether the activity starts logging is enabled. // Controlled by Settings.Global.ACTIVITY_STARTS_LOGGING_ENABLED volatile boolean mFlagActivityStartsLoggingEnabled; @@ -421,6 +429,9 @@ final class ActivityManagerConstants extends ContentObserver { case KEY_MIN_ASSOC_LOG_DURATION: updateMinAssocLogDuration(); break; + case KEY_FGS_START_FOREGROUND_TIMEOUT: + updateFgsStartForegroundTimeout(); + break; default: break; } @@ -697,6 +708,13 @@ final class ActivityManagerConstants extends ContentObserver { /* defaultValue */ DEFAULT_MIN_ASSOC_LOG_DURATION); } + private void updateFgsStartForegroundTimeout() { + mFgsStartForegroundTimeoutMs = DeviceConfig.getLong( + DeviceConfig.NAMESPACE_ACTIVITY_MANAGER, + KEY_FGS_START_FOREGROUND_TIMEOUT, + DEFAULT_FGS_START_FOREGROUND_TIMEOUT_MS); + } + void dump(PrintWriter pw) { pw.println("ACTIVITY MANAGER SETTINGS (dumpsys activity settings) " + Settings.Global.ACTIVITY_MANAGER_CONSTANTS + ":"); @@ -769,6 +787,8 @@ final class ActivityManagerConstants extends ContentObserver { pw.println(Arrays.toString(IMPERCEPTIBLE_KILL_EXEMPT_PACKAGES.toArray())); pw.print(" "); pw.print(KEY_MIN_ASSOC_LOG_DURATION); pw.print("="); pw.println(MIN_ASSOC_LOG_DURATION); + pw.print(" "); pw.print(KEY_FGS_START_FOREGROUND_TIMEOUT); pw.print("="); + pw.println(mFgsStartForegroundTimeoutMs); pw.println(); if (mOverrideMaxCachedProcesses >= 0) { diff --git a/services/core/java/com/android/server/am/ServiceRecord.java b/services/core/java/com/android/server/am/ServiceRecord.java index 1b65dbac2294..0e628289a09f 100644 --- a/services/core/java/com/android/server/am/ServiceRecord.java +++ b/services/core/java/com/android/server/am/ServiceRecord.java @@ -142,6 +142,10 @@ final class ServiceRecord extends Binder implements ComponentName.WithComponentN // allow while-in-use permissions in foreground service or not. // while-in-use permissions in FGS started from background might be restricted. boolean mAllowWhileInUsePermissionInFgs; + // The number of times Service.startForeground() is called; + int mStartForegroundCount; + // Last time mAllowWhileInUsePermissionInFgs is set. + long mLastSetFgsRestrictionTime; // the most recent package that start/bind this service. String mRecentCallingPackage; @@ -406,6 +410,8 @@ final class ServiceRecord extends Binder implements ComponentName.WithComponentN } pw.print(prefix); pw.print("allowWhileInUsePermissionInFgs="); pw.println(mAllowWhileInUsePermissionInFgs); + pw.print(prefix); pw.print("startForegroundCount="); + pw.println(mStartForegroundCount); pw.print(prefix); pw.print("recentCallingPackage="); pw.println(mRecentCallingPackage); if (delayed) { -- cgit v1.2.3 From 563fdf4259d0e28fd960acbb63431e146707d11b Mon Sep 17 00:00:00 2001 From: Matt Pietal Date: Fri, 1 Oct 2021 11:03:16 -0400 Subject: [DO NOT MERGE] Keyguard - Treat messsages to lock with priority When switching users and attempting to lock the device, the sysui main thread becomes overwhelmed with events, creating a significant lag between the time a message is posted and processed on the main thread. This can be dangerous when these events are critical for security, such as calls coming from PhoneWindowManager#lockNow() that call KeyguardViewMediator#doKeyguardTimeout(). On older devices with slower CPUs and less memory, the delay in processing can be significant (15 - 30s). The result of not prioritizing these events leads to a window of time where a guest user can switch back to the owner, and gain access to the owner's homescreen without needing to unlock the device with the owner's credentials. As a mitigation, prioritize two events originating in two specific methods to make sure the device locks as soon as possible as well as have the system server preemptively update its local cache. Bug: 151095871 Test: Very manual race condition - follow steps listed in bug Change-Id: I7585a0a5eeb308e0e32a4f77f581556d883b5cda Merged-In: I7585a0a5eeb308e0e32a4f77f581556d883b5cda (cherry picked from commit 28c53ab8bca26af58b45625c1ebba8b9051c107d) --- .../android/internal/policy/IKeyguardStateCallback.aidl | 2 +- .../android/systemui/keyguard/KeyguardViewMediator.java | 16 +++++++++++----- .../server/policy/keyguard/KeyguardServiceWrapper.java | 6 ++++++ .../server/policy/keyguard/KeyguardStateMonitor.java | 8 +++++++- 4 files changed, 25 insertions(+), 7 deletions(-) diff --git a/core/java/com/android/internal/policy/IKeyguardStateCallback.aidl b/core/java/com/android/internal/policy/IKeyguardStateCallback.aidl index 8e454db4cb04..a8003a1169e9 100644 --- a/core/java/com/android/internal/policy/IKeyguardStateCallback.aidl +++ b/core/java/com/android/internal/policy/IKeyguardStateCallback.aidl @@ -16,7 +16,7 @@ package com.android.internal.policy; interface IKeyguardStateCallback { - void onShowingStateChanged(boolean showing); + void onShowingStateChanged(boolean showing, int userId); void onSimSecureStateChanged(boolean simSecure); void onInputRestrictedStateChanged(boolean inputRestricted); void onTrustedChanged(boolean trusted); diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardViewMediator.java b/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardViewMediator.java index 2bb9423553d5..78be3b81e05b 100644 --- a/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardViewMediator.java +++ b/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardViewMediator.java @@ -1261,7 +1261,9 @@ public class KeyguardViewMediator extends SystemUI { public void doKeyguardTimeout(Bundle options) { mHandler.removeMessages(KEYGUARD_TIMEOUT); Message msg = mHandler.obtainMessage(KEYGUARD_TIMEOUT, options); - mHandler.sendMessage(msg); + // Treat these messages with priority - A call to timeout means the device should lock + // as soon as possible and not wait for other messages on the thread to process first. + mHandler.sendMessageAtFrontOfQueue(msg); } /** @@ -1456,12 +1458,15 @@ public class KeyguardViewMediator extends SystemUI { * @see #handleShow */ private void showLocked(Bundle options) { - Trace.beginSection("KeyguardViewMediator#showLocked aqcuiring mShowKeyguardWakeLock"); + Trace.beginSection("KeyguardViewMediator#showLocked acquiring mShowKeyguardWakeLock"); if (DEBUG) Log.d(TAG, "showLocked"); // ensure we stay awake until we are finished displaying the keyguard mShowKeyguardWakeLock.acquire(); Message msg = mHandler.obtainMessage(SHOW, options); - mHandler.sendMessage(msg); + // Treat these messages with priority - This call can originate from #doKeyguardTimeout, + // meaning the device should lock as soon as possible and not wait for other messages on + // the thread to process first. + mHandler.sendMessageAtFrontOfQueue(msg); Trace.endSection(); } @@ -1620,6 +1625,7 @@ public class KeyguardViewMediator extends SystemUI { case KEYGUARD_TIMEOUT: synchronized (KeyguardViewMediator.this) { doKeyguardLocked((Bundle) msg.obj); + notifyDefaultDisplayCallbacks(mShowing); } break; case DISMISS: @@ -2181,7 +2187,7 @@ public class KeyguardViewMediator extends SystemUI { for (int i = size - 1; i >= 0; i--) { IKeyguardStateCallback callback = mKeyguardStateCallbacks.get(i); try { - callback.onShowingStateChanged(showing); + callback.onShowingStateChanged(showing, KeyguardUpdateMonitor.getCurrentUser()); } catch (RemoteException e) { Slog.w(TAG, "Failed to call onShowingStateChanged", e); if (e instanceof DeadObjectException) { @@ -2229,7 +2235,7 @@ public class KeyguardViewMediator extends SystemUI { mKeyguardStateCallbacks.add(callback); try { callback.onSimSecureStateChanged(mUpdateMonitor.isSimPinSecure()); - callback.onShowingStateChanged(mShowing); + callback.onShowingStateChanged(mShowing, KeyguardUpdateMonitor.getCurrentUser()); callback.onInputRestrictedStateChanged(mInputRestricted); callback.onTrustedChanged(mUpdateMonitor.getUserHasTrust( KeyguardUpdateMonitor.getCurrentUser())); diff --git a/services/core/java/com/android/server/policy/keyguard/KeyguardServiceWrapper.java b/services/core/java/com/android/server/policy/keyguard/KeyguardServiceWrapper.java index 4e848686254a..cf5c587e0494 100644 --- a/services/core/java/com/android/server/policy/keyguard/KeyguardServiceWrapper.java +++ b/services/core/java/com/android/server/policy/keyguard/KeyguardServiceWrapper.java @@ -192,6 +192,12 @@ public class KeyguardServiceWrapper implements IKeyguardService { @Override // Binder interface public void doKeyguardTimeout(Bundle options) { + int userId = mKeyguardStateMonitor.getCurrentUser(); + if (mKeyguardStateMonitor.isSecure(userId)) { + // Preemptively inform the cache that the keyguard will soon be showing, as calls to + // doKeyguardTimeout are a signal to lock the device as soon as possible. + mKeyguardStateMonitor.onShowingStateChanged(true, userId); + } try { mService.doKeyguardTimeout(options); } catch (RemoteException e) { diff --git a/services/core/java/com/android/server/policy/keyguard/KeyguardStateMonitor.java b/services/core/java/com/android/server/policy/keyguard/KeyguardStateMonitor.java index add0b01f1879..f0f62edf8779 100644 --- a/services/core/java/com/android/server/policy/keyguard/KeyguardStateMonitor.java +++ b/services/core/java/com/android/server/policy/keyguard/KeyguardStateMonitor.java @@ -83,8 +83,14 @@ public class KeyguardStateMonitor extends IKeyguardStateCallback.Stub { return mHasLockscreenWallpaper; } + public int getCurrentUser() { + return mCurrentUserId; + } + @Override // Binder interface - public void onShowingStateChanged(boolean showing) { + public void onShowingStateChanged(boolean showing, int userId) { + if (userId != mCurrentUserId) return; + mIsShowing = showing; mCallback.onShowingChanged(); -- cgit v1.2.3 From a68b60babc24e5609c8bc205508023d07908cf44 Mon Sep 17 00:00:00 2001 From: Bill Yi Date: Fri, 11 Feb 2022 23:32:09 +0000 Subject: Import translations. DO NOT MERGE ANYWHERE Auto-generated-cl: translation import Change-Id: Id9e293d69f3cc674e68ab7ddc560e546e08a9e1f --- core/res/res/values-b+sr+Latn/strings.xml | 2 +- core/res/res/values-fr/strings.xml | 2 +- core/res/res/values-ja/strings.xml | 8 ++++---- core/res/res/values-sr/strings.xml | 2 +- core/res/res/values-uz/strings.xml | 2 +- 5 files changed, 8 insertions(+), 8 deletions(-) diff --git a/core/res/res/values-b+sr+Latn/strings.xml b/core/res/res/values-b+sr+Latn/strings.xml index 1e1a359a1328..328fa8d1daa1 100644 --- a/core/res/res/values-b+sr+Latn/strings.xml +++ b/core/res/res/values-b+sr+Latn/strings.xml @@ -78,7 +78,7 @@ "ID pozivaoca podrazumevano nije ograničen. Sledeći poziv: Nije ograničen." "Usluga nije dobavljena." "Ne možete da promenite podešavanje ID-a korisnika." - "Nema usluge prenosa podataka preko mobilnog operatera" + "Nema usluge mobilnih podataka" "Hitni pozivi nisu dostupni" "Nema glasovne usluge" "Nema glasovne usluge ni hitnih poziva" diff --git a/core/res/res/values-fr/strings.xml b/core/res/res/values-fr/strings.xml index 55fa1453caf8..d87587f82a6e 100644 --- a/core/res/res/values-fr/strings.xml +++ b/core/res/res/values-fr/strings.xml @@ -271,7 +271,7 @@ "Paramètres" "Assistance" "Assistance vocale" - "Verrouillé" + "Verrouiller" ">999" "Nouvelle notification" "Clavier virtuel" diff --git a/core/res/res/values-ja/strings.xml b/core/res/res/values-ja/strings.xml index 30a62e3d8df0..514d66ebae51 100644 --- a/core/res/res/values-ja/strings.xml +++ b/core/res/res/values-ja/strings.xml @@ -30,7 +30,7 @@ "<新規>" "(電話番号なし)" "不明" - "ボイスメール" + "留守番電話" "MSISDN1" "接続に問題があるか、MMIコードが正しくありません。" "発信番号制限で指定された番号に対してのみ操作できます。" @@ -92,7 +92,7 @@ "緊急通報待機モード" "モバイルデータのステータス" "SMS メッセージ" - "ボイスメール メッセージ" + "留守番電話メッセージ" "Wi-Fi 通話" "SIM のステータス" "高優先度: SIM のステータス" @@ -1011,8 +1011,8 @@ "モバイル デバイスに保存されているブラウザの履歴やブックマークの変更をアプリに許可します。これにより、アプリがブラウザデータを消去または変更できるようになる可能性があります。注: この許可は、サードパーティブラウザまたはウェブブラウジング機能を備えたその他のアプリでは適用されない場合があります。" "アラームの設定" "インストール済みアラームアプリのアラームを設定することをアプリに許可します。この機能が実装されていないアラームアプリもあります。" - "ボイスメールの追加" - "ボイスメール受信トレイにメッセージを追加することをアプリに許可します。" + "留守番電話の追加" + "留守番電話受信トレイにメッセージを追加することをアプリに許可します。" "ブラウザの現在地情報に対する権限の変更" "ブラウザの現在地情報に対する権限の変更をアプリに許可します。この許可を悪意のあるアプリに利用されると、任意のウェブサイトに現在地情報が送信される恐れがあります。" "このパスワードをブラウザで保存しますか?" diff --git a/core/res/res/values-sr/strings.xml b/core/res/res/values-sr/strings.xml index 353257c93104..976b412789a9 100644 --- a/core/res/res/values-sr/strings.xml +++ b/core/res/res/values-sr/strings.xml @@ -78,7 +78,7 @@ "ИД позиваоца подразумевано није ограничен. Следећи позив: Није ограничен." "Услуга није добављена." "Не можете да промените подешавање ИД-а корисника." - "Нема услуге преноса података преко мобилног оператера" + "Нема услуге мобилних података" "Хитни позиви нису доступни" "Нема гласовне услуге" "Нема гласовне услуге ни хитних позива" diff --git a/core/res/res/values-uz/strings.xml b/core/res/res/values-uz/strings.xml index df7d4670dc29..c25fa0d03b04 100644 --- a/core/res/res/values-uz/strings.xml +++ b/core/res/res/values-uz/strings.xml @@ -883,7 +883,7 @@ "Qulfni ochish uchun \"Menyu\"ga bosing." "Qulfni ochish uchun grafik kalitni chizing" "Favqulodda chaqiruv" - "Qo‘ng‘iroqni qaytarish" + "Chaqiruvga qaytish" "To‘g‘ri!" "Qaytadan urining" "Qaytadan urining" -- cgit v1.2.3 From 35380b93b4e34c07c97cc5acf057539b97335a2b Mon Sep 17 00:00:00 2001 From: Bill Yi Date: Fri, 11 Feb 2022 23:58:11 +0000 Subject: Import translations. DO NOT MERGE ANYWHERE Auto-generated-cl: translation import Change-Id: I3dd4bd848cd6a49968be821c33f435d87f3177e6 --- core/res/res/values-b+sr+Latn/strings.xml | 2 +- core/res/res/values-fr/strings.xml | 2 +- core/res/res/values-ja/strings.xml | 8 ++++---- core/res/res/values-sr/strings.xml | 2 +- core/res/res/values-uz/strings.xml | 2 +- 5 files changed, 8 insertions(+), 8 deletions(-) diff --git a/core/res/res/values-b+sr+Latn/strings.xml b/core/res/res/values-b+sr+Latn/strings.xml index 1e1a359a1328..328fa8d1daa1 100644 --- a/core/res/res/values-b+sr+Latn/strings.xml +++ b/core/res/res/values-b+sr+Latn/strings.xml @@ -78,7 +78,7 @@ "ID pozivaoca podrazumevano nije ograničen. Sledeći poziv: Nije ograničen." "Usluga nije dobavljena." "Ne možete da promenite podešavanje ID-a korisnika." - "Nema usluge prenosa podataka preko mobilnog operatera" + "Nema usluge mobilnih podataka" "Hitni pozivi nisu dostupni" "Nema glasovne usluge" "Nema glasovne usluge ni hitnih poziva" diff --git a/core/res/res/values-fr/strings.xml b/core/res/res/values-fr/strings.xml index 55fa1453caf8..d87587f82a6e 100644 --- a/core/res/res/values-fr/strings.xml +++ b/core/res/res/values-fr/strings.xml @@ -271,7 +271,7 @@ "Paramètres" "Assistance" "Assistance vocale" - "Verrouillé" + "Verrouiller" ">999" "Nouvelle notification" "Clavier virtuel" diff --git a/core/res/res/values-ja/strings.xml b/core/res/res/values-ja/strings.xml index 30a62e3d8df0..514d66ebae51 100644 --- a/core/res/res/values-ja/strings.xml +++ b/core/res/res/values-ja/strings.xml @@ -30,7 +30,7 @@ "<新規>" "(電話番号なし)" "不明" - "ボイスメール" + "留守番電話" "MSISDN1" "接続に問題があるか、MMIコードが正しくありません。" "発信番号制限で指定された番号に対してのみ操作できます。" @@ -92,7 +92,7 @@ "緊急通報待機モード" "モバイルデータのステータス" "SMS メッセージ" - "ボイスメール メッセージ" + "留守番電話メッセージ" "Wi-Fi 通話" "SIM のステータス" "高優先度: SIM のステータス" @@ -1011,8 +1011,8 @@ "モバイル デバイスに保存されているブラウザの履歴やブックマークの変更をアプリに許可します。これにより、アプリがブラウザデータを消去または変更できるようになる可能性があります。注: この許可は、サードパーティブラウザまたはウェブブラウジング機能を備えたその他のアプリでは適用されない場合があります。" "アラームの設定" "インストール済みアラームアプリのアラームを設定することをアプリに許可します。この機能が実装されていないアラームアプリもあります。" - "ボイスメールの追加" - "ボイスメール受信トレイにメッセージを追加することをアプリに許可します。" + "留守番電話の追加" + "留守番電話受信トレイにメッセージを追加することをアプリに許可します。" "ブラウザの現在地情報に対する権限の変更" "ブラウザの現在地情報に対する権限の変更をアプリに許可します。この許可を悪意のあるアプリに利用されると、任意のウェブサイトに現在地情報が送信される恐れがあります。" "このパスワードをブラウザで保存しますか?" diff --git a/core/res/res/values-sr/strings.xml b/core/res/res/values-sr/strings.xml index 353257c93104..976b412789a9 100644 --- a/core/res/res/values-sr/strings.xml +++ b/core/res/res/values-sr/strings.xml @@ -78,7 +78,7 @@ "ИД позиваоца подразумевано није ограничен. Следећи позив: Није ограничен." "Услуга није добављена." "Не можете да промените подешавање ИД-а корисника." - "Нема услуге преноса података преко мобилног оператера" + "Нема услуге мобилних података" "Хитни позиви нису доступни" "Нема гласовне услуге" "Нема гласовне услуге ни хитних позива" diff --git a/core/res/res/values-uz/strings.xml b/core/res/res/values-uz/strings.xml index df7d4670dc29..c25fa0d03b04 100644 --- a/core/res/res/values-uz/strings.xml +++ b/core/res/res/values-uz/strings.xml @@ -883,7 +883,7 @@ "Qulfni ochish uchun \"Menyu\"ga bosing." "Qulfni ochish uchun grafik kalitni chizing" "Favqulodda chaqiruv" - "Qo‘ng‘iroqni qaytarish" + "Chaqiruvga qaytish" "To‘g‘ri!" "Qaytadan urining" "Qaytadan urining" -- cgit v1.2.3 From 5afa9e752e8bb2de4e2014ee1a8f88bef0cd1f3c Mon Sep 17 00:00:00 2001 From: Bill Yi Date: Sat, 12 Feb 2022 03:36:21 +0000 Subject: Import translations. DO NOT MERGE ANYWHERE Auto-generated-cl: translation import Change-Id: I128abe944588d811f91a8622092f4b95a2f40e3b --- packages/SystemUI/res/values-pt-rBR/strings.xml | 2 +- packages/SystemUI/res/values-pt/strings.xml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/SystemUI/res/values-pt-rBR/strings.xml b/packages/SystemUI/res/values-pt-rBR/strings.xml index 8c1af2e28c32..0cf7f28a197e 100644 --- a/packages/SystemUI/res/values-pt-rBR/strings.xml +++ b/packages/SystemUI/res/values-pt-rBR/strings.xml @@ -54,7 +54,7 @@ "Abrir o app %1$s para lidar com o %2$s?" "Nenhum apl. instalado funciona com o USB. Saiba mais sobre o acessório em %1$s" "Acessório USB" - "Visualizar" + "Ver" "Sempre abrir o app %1$s quando %2$s for conectado" "Sempre abrir o app %1$s quando %2$s for conectado" "Permitir a depuração USB?" diff --git a/packages/SystemUI/res/values-pt/strings.xml b/packages/SystemUI/res/values-pt/strings.xml index 8c1af2e28c32..0cf7f28a197e 100644 --- a/packages/SystemUI/res/values-pt/strings.xml +++ b/packages/SystemUI/res/values-pt/strings.xml @@ -54,7 +54,7 @@ "Abrir o app %1$s para lidar com o %2$s?" "Nenhum apl. instalado funciona com o USB. Saiba mais sobre o acessório em %1$s" "Acessório USB" - "Visualizar" + "Ver" "Sempre abrir o app %1$s quando %2$s for conectado" "Sempre abrir o app %1$s quando %2$s for conectado" "Permitir a depuração USB?" -- cgit v1.2.3 From 67ed07c29b9f302ae27a037f345c62d442548911 Mon Sep 17 00:00:00 2001 From: Bill Yi Date: Sat, 12 Feb 2022 03:49:42 +0000 Subject: Import translations. DO NOT MERGE ANYWHERE Auto-generated-cl: translation import Change-Id: Iea4984ed0ce67f276a9c966757e5cd5cb2753d41 --- packages/SystemUI/res/values-pt-rBR/strings.xml | 2 +- packages/SystemUI/res/values-pt/strings.xml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/SystemUI/res/values-pt-rBR/strings.xml b/packages/SystemUI/res/values-pt-rBR/strings.xml index 8c1af2e28c32..0cf7f28a197e 100644 --- a/packages/SystemUI/res/values-pt-rBR/strings.xml +++ b/packages/SystemUI/res/values-pt-rBR/strings.xml @@ -54,7 +54,7 @@ "Abrir o app %1$s para lidar com o %2$s?" "Nenhum apl. instalado funciona com o USB. Saiba mais sobre o acessório em %1$s" "Acessório USB" - "Visualizar" + "Ver" "Sempre abrir o app %1$s quando %2$s for conectado" "Sempre abrir o app %1$s quando %2$s for conectado" "Permitir a depuração USB?" diff --git a/packages/SystemUI/res/values-pt/strings.xml b/packages/SystemUI/res/values-pt/strings.xml index 8c1af2e28c32..0cf7f28a197e 100644 --- a/packages/SystemUI/res/values-pt/strings.xml +++ b/packages/SystemUI/res/values-pt/strings.xml @@ -54,7 +54,7 @@ "Abrir o app %1$s para lidar com o %2$s?" "Nenhum apl. instalado funciona com o USB. Saiba mais sobre o acessório em %1$s" "Acessório USB" - "Visualizar" + "Ver" "Sempre abrir o app %1$s quando %2$s for conectado" "Sempre abrir o app %1$s quando %2$s for conectado" "Permitir a depuração USB?" -- cgit v1.2.3 From 95ada06bca963dc9668ecefc188a26019a74ecaf Mon Sep 17 00:00:00 2001 From: Bill Yi Date: Sat, 12 Feb 2022 11:53:26 +0000 Subject: Import translations. DO NOT MERGE ANYWHERE Auto-generated-cl: translation import Change-Id: I7c01e1671651905651ad3f47fee7088c422bfbba --- packages/SettingsLib/res/values-es/strings.xml | 2 +- packages/SettingsLib/res/values-pt-rBR/strings.xml | 2 +- packages/SettingsLib/res/values-pt/strings.xml | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/SettingsLib/res/values-es/strings.xml b/packages/SettingsLib/res/values-es/strings.xml index aab7a5ad1044..1811c26ff6d1 100644 --- a/packages/SettingsLib/res/values-es/strings.xml +++ b/packages/SettingsLib/res/values-es/strings.xml @@ -216,7 +216,7 @@ "Empareja nuevos dispositivos con el escáner de códigos QR" "Emparejar dispositivo con código de sincronización" "Empareja nuevos dispositivos con un código de seis dígitos" - "Dispositivos vinculados" + "Dispositivos emparejados" "Conectados actualmente" "Datos del dispositivo" "Olvidar" diff --git a/packages/SettingsLib/res/values-pt-rBR/strings.xml b/packages/SettingsLib/res/values-pt-rBR/strings.xml index 4136ec23afae..efb887ad3d2b 100644 --- a/packages/SettingsLib/res/values-pt-rBR/strings.xml +++ b/packages/SettingsLib/res/values-pt-rBR/strings.xml @@ -408,7 +408,7 @@ "Mostrar notificações de transcodificação" "Desativar cache da transcodificação" "Serviços em execução" - "Visualizar e controlar os serviços em execução no momento" + "Ver e controlar os serviços em execução no momento" "Implementação do WebView" "Configurar implementação do WebView" "Esta opção não é mais válida. Tente novamente." diff --git a/packages/SettingsLib/res/values-pt/strings.xml b/packages/SettingsLib/res/values-pt/strings.xml index 4136ec23afae..efb887ad3d2b 100644 --- a/packages/SettingsLib/res/values-pt/strings.xml +++ b/packages/SettingsLib/res/values-pt/strings.xml @@ -408,7 +408,7 @@ "Mostrar notificações de transcodificação" "Desativar cache da transcodificação" "Serviços em execução" - "Visualizar e controlar os serviços em execução no momento" + "Ver e controlar os serviços em execução no momento" "Implementação do WebView" "Configurar implementação do WebView" "Esta opção não é mais válida. Tente novamente." -- cgit v1.2.3 From b6be55ad2a42048b659d7ff45f303e85026227d6 Mon Sep 17 00:00:00 2001 From: Bill Yi Date: Sat, 12 Feb 2022 12:03:43 +0000 Subject: Import translations. DO NOT MERGE ANYWHERE Auto-generated-cl: translation import Change-Id: Icc4251be2571c31657c361f14952fe17897c8891 --- packages/SettingsLib/res/values-es/strings.xml | 2 +- packages/SettingsLib/res/values-pt-rBR/strings.xml | 2 +- packages/SettingsLib/res/values-pt/strings.xml | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/SettingsLib/res/values-es/strings.xml b/packages/SettingsLib/res/values-es/strings.xml index aab7a5ad1044..1811c26ff6d1 100644 --- a/packages/SettingsLib/res/values-es/strings.xml +++ b/packages/SettingsLib/res/values-es/strings.xml @@ -216,7 +216,7 @@ "Empareja nuevos dispositivos con el escáner de códigos QR" "Emparejar dispositivo con código de sincronización" "Empareja nuevos dispositivos con un código de seis dígitos" - "Dispositivos vinculados" + "Dispositivos emparejados" "Conectados actualmente" "Datos del dispositivo" "Olvidar" diff --git a/packages/SettingsLib/res/values-pt-rBR/strings.xml b/packages/SettingsLib/res/values-pt-rBR/strings.xml index 4136ec23afae..efb887ad3d2b 100644 --- a/packages/SettingsLib/res/values-pt-rBR/strings.xml +++ b/packages/SettingsLib/res/values-pt-rBR/strings.xml @@ -408,7 +408,7 @@ "Mostrar notificações de transcodificação" "Desativar cache da transcodificação" "Serviços em execução" - "Visualizar e controlar os serviços em execução no momento" + "Ver e controlar os serviços em execução no momento" "Implementação do WebView" "Configurar implementação do WebView" "Esta opção não é mais válida. Tente novamente." diff --git a/packages/SettingsLib/res/values-pt/strings.xml b/packages/SettingsLib/res/values-pt/strings.xml index 4136ec23afae..efb887ad3d2b 100644 --- a/packages/SettingsLib/res/values-pt/strings.xml +++ b/packages/SettingsLib/res/values-pt/strings.xml @@ -408,7 +408,7 @@ "Mostrar notificações de transcodificação" "Desativar cache da transcodificação" "Serviços em execução" - "Visualizar e controlar os serviços em execução no momento" + "Ver e controlar os serviços em execução no momento" "Implementação do WebView" "Configurar implementação do WebView" "Esta opção não é mais válida. Tente novamente." -- cgit v1.2.3 From 6d8acfba32c289be517b5be2d6f9e37053bc9795 Mon Sep 17 00:00:00 2001 From: Lucas Dupin Date: Fri, 7 Jan 2022 11:54:25 -0800 Subject: Fix brokn theming test Test: atest ThemeOverlayControllerTest Bug: 211838535 Fixes: 219026714 Change-Id: Ibb2a730280a25b39cac96415de8b82430843064b Merged-In: Ibb2a730280a25b39cac96415de8b82430843064b (cherry picked from commit e6e0a6c49b15b14115edb0075517ca0faf6711f7) --- .../src/com/android/systemui/theme/ThemeOverlayControllerTest.java | 6 ------ 1 file changed, 6 deletions(-) diff --git a/packages/SystemUI/tests/src/com/android/systemui/theme/ThemeOverlayControllerTest.java b/packages/SystemUI/tests/src/com/android/systemui/theme/ThemeOverlayControllerTest.java index 5b55c41662a7..8c0a05f2e046 100644 --- a/packages/SystemUI/tests/src/com/android/systemui/theme/ThemeOverlayControllerTest.java +++ b/packages/SystemUI/tests/src/com/android/systemui/theme/ThemeOverlayControllerTest.java @@ -200,12 +200,6 @@ public class ThemeOverlayControllerTest extends SysuiTestCase { verify(mThemeOverlayApplier) .applyCurrentUserOverlays(themeOverlays.capture(), any(), anyInt(), any()); - // Assert that we received the colors that we were expecting - assertThat(themeOverlays.getValue().get(OVERLAY_CATEGORY_SYSTEM_PALETTE)) - .isEqualTo(new OverlayIdentifier("ffff0000")); - assertThat(themeOverlays.getValue().get(OVERLAY_CATEGORY_ACCENT_COLOR)) - .isEqualTo(new OverlayIdentifier("ffff0000")); - // Should not change theme after changing wallpapers, if intent doesn't have // WallpaperManager.EXTRA_FROM_FOREGROUND_APP set to true. clearInvocations(mThemeOverlayApplier); -- cgit v1.2.3 From fad4624dd82c6623d34137d051b76603533ddfc0 Mon Sep 17 00:00:00 2001 From: Vishnu Nair Date: Wed, 26 Jan 2022 23:25:07 +0000 Subject: SurfaceControl: Add setDropInputMode api Introduces an API to drop input events on this SurfaceControl. This policy will be inherited by its children. The caller must hold the ACCESS_SURFACE_FLINGER permission. Options include: ALL: SurfaceControl and its children will not receive any input regardless of whether it has a valid input channel. These policies are used to enable features that allow for a less trusted interaction model between apps. See the bug for more details. Note: this backport doesn't include the oclude mode since its not needed for the security fix. Test: atest libgui_test InputDispatcherDropInputFeatureTest Bug: 197296414 Merged-In: Ifcb4133306a43874e74e8fb0f42b60842daf6f25 Change-Id: Ifcb4133306a43874e74e8fb0f42b60842daf6f25 --- Android.bp | 1 + core/java/android/view/SurfaceControl.java | 16 ++++++++++++++-- core/jni/android_view_SurfaceControl.cpp | 11 +++++++++++ 3 files changed, 26 insertions(+), 2 deletions(-) diff --git a/Android.bp b/Android.bp index 14a2bff8ad13..c8befafddb0d 100644 --- a/Android.bp +++ b/Android.bp @@ -255,6 +255,7 @@ filegroup { ":framework_native_aidl", ":gatekeeper_aidl", ":gsiservice_aidl", + ":guiconstants_aidl", ":incidentcompanion_aidl", ":installd_aidl", ":keystore_aidl", diff --git a/core/java/android/view/SurfaceControl.java b/core/java/android/view/SurfaceControl.java index 1a4b303bd267..0dc7f5ad26fb 100644 --- a/core/java/android/view/SurfaceControl.java +++ b/core/java/android/view/SurfaceControl.java @@ -42,6 +42,7 @@ import android.graphics.PixelFormat; import android.graphics.Point; import android.graphics.Rect; import android.graphics.Region; +import android.gui.DropInputMode; import android.hardware.display.DeviceProductInfo; import android.hardware.display.DisplayedContentSample; import android.hardware.display.DisplayedContentSamplingAttributes; @@ -49,7 +50,6 @@ import android.os.Build; import android.os.IBinder; import android.os.Parcel; import android.os.Parcelable; -import android.os.Trace; import android.util.ArrayMap; import android.util.Log; import android.util.SparseIntArray; @@ -141,7 +141,8 @@ public final class SurfaceControl implements Parcelable { int layerStack); private static native void nativeSetTrustedOverlay(long transactionObj, long nativeObject, boolean isTrustedOverlay); - + private static native void nativeSetDropInputMode( + long transactionObj, long nativeObject, int flags); private static native boolean nativeClearContentFrameStats(long nativeObject); private static native boolean nativeGetContentFrameStats(long nativeObject, WindowContentFrameStats outStats); private static native boolean nativeClearAnimationFrameStats(); @@ -3050,6 +3051,17 @@ public final class SurfaceControl implements Parcelable { return this; } + /** + * Sets the input event drop mode on this SurfaceControl and its children. The caller must + * hold the ACCESS_SURFACE_FLINGER permission. See {@code InputEventDropMode}. + * @hide + */ + public Transaction setDropInputMode(SurfaceControl sc, @DropInputMode int mode) { + checkPreconditions(sc); + nativeSetDropInputMode(mNativeObject, sc.mNativeObject, mode); + return this; + } + /** * Merge the other transaction into this transaction, clearing the * other transaction as if it had been applied. diff --git a/core/jni/android_view_SurfaceControl.cpp b/core/jni/android_view_SurfaceControl.cpp index fd2ccbe50b8d..3c704ffb8de7 100644 --- a/core/jni/android_view_SurfaceControl.cpp +++ b/core/jni/android_view_SurfaceControl.cpp @@ -671,6 +671,13 @@ static void nativeSetFixedTransformHint(JNIEnv* env, jclass clazz, jlong transac transaction->setFixedTransformHint(ctrl, transformHint); } +static void nativeSetDropInputMode(JNIEnv* env, jclass clazz, jlong transactionObj, + jlong nativeObject, jint mode) { + auto transaction = reinterpret_cast(transactionObj); + SurfaceControl* const ctrl = reinterpret_cast(nativeObject); + transaction->setDropInputMode(ctrl, static_cast(mode)); +} + static jlongArray nativeGetPhysicalDisplayIds(JNIEnv* env, jclass clazz) { const auto displayIds = SurfaceComposerClient::getPhysicalDisplayIds(); jlongArray array = env->NewLongArray(displayIds.size()); @@ -1495,6 +1502,7 @@ static jlong nativeGetHandle(JNIEnv* env, jclass clazz, jlong nativeObject) { // ---------------------------------------------------------------------------- static const JNINativeMethod sSurfaceControlMethods[] = { + // clang-format off {"nativeCreate", "(Landroid/view/SurfaceSession;Ljava/lang/String;IIIIJLandroid/os/Parcel;)J", (void*)nativeCreate }, {"nativeReadFromParcel", "(Landroid/os/Parcel;)J", @@ -1678,6 +1686,9 @@ static const JNINativeMethod sSurfaceControlMethods[] = { (void*)nativeSetFixedTransformHint}, {"nativeSetTrustedOverlay", "(JJZ)V", (void*)nativeSetTrustedOverlay }, + {"nativeSetDropInputMode", "(JJI)V", + (void*)nativeSetDropInputMode}, + // clang-format on }; int register_android_view_SurfaceControl(JNIEnv* env) -- cgit v1.2.3 From 55c1473bf2fedaacf7bb8ac068e6f9b1a625b5e0 Mon Sep 17 00:00:00 2001 From: Vishnu Nair Date: Wed, 2 Feb 2022 17:13:21 +0000 Subject: Drop input for toast and child surfaces Toasts that do not have the trustedOverlay flag should not receive input. These windows should not have any children, so force this hierarchy of windows to drop all input by setting a flag on the toast window state which will apply the DROP_INPUT flag on all windows with an input channel. This is to prevent malicious apps from parenting surfaces with input channels to the toast window. Test: show toast and check if input feature flag DROP_INPUT id set via dumpsys Bug: b/197296414 Change-Id: I316b76b685ca5030fd8aa91283555efcce4d6994 Merged-In: I316b76b685ca5030fd8aa91283555efcce4d6994 --- .../core/java/com/android/server/wm/DisplayPolicy.java | 15 +++++++++++++++ .../java/com/android/server/wm/WindowManagerService.java | 1 + 2 files changed, 16 insertions(+) diff --git a/services/core/java/com/android/server/wm/DisplayPolicy.java b/services/core/java/com/android/server/wm/DisplayPolicy.java index 05875d971eb5..8a01d90bca29 100644 --- a/services/core/java/com/android/server/wm/DisplayPolicy.java +++ b/services/core/java/com/android/server/wm/DisplayPolicy.java @@ -138,6 +138,7 @@ import android.graphics.Insets; import android.graphics.PixelFormat; import android.graphics.Rect; import android.graphics.Region; +import android.gui.DropInputMode; import android.hardware.input.InputManager; import android.hardware.power.V1_0.PowerHint; import android.os.Handler; @@ -918,6 +919,20 @@ public class DisplayPolicy { } } + /** + * Add additional policy if needed to ensure the window or its children should not receive any + * input. + */ + public void setDropInputModePolicy(WindowState win, LayoutParams attrs) { + if (attrs.type == TYPE_TOAST + && (attrs.privateFlags & PRIVATE_FLAG_TRUSTED_OVERLAY) == 0) { + // Toasts should not receive input. These windows should not have any children, so + // force this hierarchy of windows to drop all input. + mService.mTransactionFactory.get() + .setDropInputMode(win.getSurfaceControl(), DropInputMode.ALL).apply(); + } + } + /** * @return {@code true} if the calling activity initiate toast and is visible with * {@link WindowManager.LayoutParams#FLAG_SHOW_WHEN_LOCKED} flag. diff --git a/services/core/java/com/android/server/wm/WindowManagerService.java b/services/core/java/com/android/server/wm/WindowManagerService.java index aa598d0cfdc6..9cf17e4ece5c 100644 --- a/services/core/java/com/android/server/wm/WindowManagerService.java +++ b/services/core/java/com/android/server/wm/WindowManagerService.java @@ -1650,6 +1650,7 @@ public class WindowManagerService extends IWindowManager.Stub win.mToken.addWindow(win); displayPolicy.addWindowLw(win, attrs); + displayPolicy.setDropInputModePolicy(win, win.mAttrs); if (type == TYPE_INPUT_METHOD) { displayContent.setInputMethodWindowLocked(win); imMayMove = false; -- cgit v1.2.3