blob: 5f5cd3c461170dbeef4a60f1c059664862500db7 [file] [log] [blame]
Adrian Roos82142c22014-03-27 14:56:59 +01001/*
2 * Copyright (C) 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License
15 */
16
17package com.android.server.trust;
18
Adrian Roos82142c22014-03-27 14:56:59 +010019import android.Manifest;
Andrew Scull85a63bc2016-10-24 13:47:47 +010020import android.annotation.UserIdInt;
Adrian Roosbcd07652014-10-22 16:57:16 +020021import android.app.ActivityManager;
Vishwath Mohan15f7dd02018-12-12 11:15:08 -080022import android.app.AlarmManager;
23import android.app.AlarmManager.OnAlarmListener;
Adrian Roosca36b952014-05-16 18:52:29 +020024import android.app.admin.DevicePolicyManager;
Adrian Roos82142c22014-03-27 14:56:59 +010025import android.app.trust.ITrustListener;
26import android.app.trust.ITrustManager;
Adrian Roosca36b952014-05-16 18:52:29 +020027import android.content.BroadcastReceiver;
Adrian Roos82142c22014-03-27 14:56:59 +010028import android.content.ComponentName;
Vishwath Mohan15f7dd02018-12-12 11:15:08 -080029import android.content.ContentResolver;
Adrian Roos82142c22014-03-27 14:56:59 +010030import android.content.Context;
31import android.content.Intent;
Adrian Roosca36b952014-05-16 18:52:29 +020032import android.content.IntentFilter;
Adrian Roos3870d452014-09-05 18:22:28 +020033import android.content.pm.ApplicationInfo;
Adrian Roos82142c22014-03-27 14:56:59 +010034import android.content.pm.PackageManager;
35import android.content.pm.ResolveInfo;
36import android.content.pm.UserInfo;
37import android.content.res.Resources;
38import android.content.res.TypedArray;
39import android.content.res.XmlResourceParser;
Vishwath Mohan15f7dd02018-12-12 11:15:08 -080040import android.database.ContentObserver;
Adrian Roos82142c22014-03-27 14:56:59 +010041import android.graphics.drawable.Drawable;
Dmitry Dementyev38579682019-01-22 13:41:34 -080042import android.hardware.biometrics.BiometricSourceType;
Vishwath Mohan15f7dd02018-12-12 11:15:08 -080043import android.net.Uri;
Adrian Roosbcd07652014-10-22 16:57:16 +020044import android.os.Binder;
Adrian Roos5d639782016-07-21 11:43:02 -070045import android.os.Build;
Adrian Roosa4ba56b2014-05-20 12:56:25 +020046import android.os.DeadObjectException;
Adrian Roos82142c22014-03-27 14:56:59 +010047import android.os.Handler;
48import android.os.IBinder;
49import android.os.Message;
Jim Millere303bf42014-08-26 17:12:29 -070050import android.os.PersistableBundle;
Adrian Roos82142c22014-03-27 14:56:59 +010051import android.os.RemoteException;
Adrian Roosc5f95ce2014-07-24 16:00:46 +020052import android.os.SystemClock;
Adrian Roos82142c22014-03-27 14:56:59 +010053import android.os.UserHandle;
54import android.os.UserManager;
Adrian Roos3870d452014-09-05 18:22:28 +020055import android.provider.Settings;
Rubin Xuc3986272019-11-05 10:15:36 +000056import android.security.KeyStore;
Adrian Roos82142c22014-03-27 14:56:59 +010057import android.service.trust.TrustAgentService;
Zachary Iqbal666484d2017-03-31 19:10:09 -070058import android.text.TextUtils;
Vishwath Mohan15f7dd02018-12-12 11:15:08 -080059import android.util.ArrayMap;
Adrian Roos82142c22014-03-27 14:56:59 +010060import android.util.ArraySet;
61import android.util.AttributeSet;
Adrian Roos18ea8932014-05-28 14:53:06 +020062import android.util.Log;
Adrian Roos82142c22014-03-27 14:56:59 +010063import android.util.Slog;
Adrian Roos7046bfd2014-05-16 21:20:54 +020064import android.util.SparseBooleanArray;
Adrian Roos82142c22014-03-27 14:56:59 +010065import android.util.Xml;
Adrian Roos481a6df2014-11-20 19:48:56 +010066import android.view.IWindowManager;
Adrian Roos50bfeec2014-11-20 16:21:11 +010067import android.view.WindowManagerGlobal;
Vishwath Mohan15f7dd02018-12-12 11:15:08 -080068
Lingjun Li93a145f2017-01-23 17:13:35 -080069import com.android.internal.annotations.GuardedBy;
70import com.android.internal.content.PackageMonitor;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -060071import com.android.internal.util.DumpUtils;
Lingjun Li93a145f2017-01-23 17:13:35 -080072import com.android.internal.widget.LockPatternUtils;
73import com.android.server.SystemService;
Vishwath Mohan15f7dd02018-12-12 11:15:08 -080074
Dmitry Dementyev38579682019-01-22 13:41:34 -080075import org.xmlpull.v1.XmlPullParser;
76import org.xmlpull.v1.XmlPullParserException;
77
Adrian Roos7a4f3d42014-05-02 12:12:20 +020078import java.io.FileDescriptor;
Adrian Roos82142c22014-03-27 14:56:59 +010079import java.io.IOException;
Adrian Roos7a4f3d42014-05-02 12:12:20 +020080import java.io.PrintWriter;
Adrian Roos82142c22014-03-27 14:56:59 +010081import java.util.ArrayList;
82import java.util.List;
Dmitry Dementyev38579682019-01-22 13:41:34 -080083
Adrian Roos82142c22014-03-27 14:56:59 +010084
85/**
86 * Manages trust agents and trust listeners.
87 *
88 * It is responsible for binding to the enabled {@link android.service.trust.TrustAgentService}s
89 * of each user and notifies them about events that are relevant to them.
90 * It start and stops them based on the value of
91 * {@link com.android.internal.widget.LockPatternUtils#getEnabledTrustAgents(int)}.
92 *
93 * It also keeps a set of {@link android.app.trust.ITrustListener}s that are notified whenever the
94 * trust state changes for any user.
95 *
96 * Trust state and the setting of enabled agents is kept per user and each user has its own
97 * instance of a {@link android.service.trust.TrustAgentService}.
98 */
99public class TrustManagerService extends SystemService {
Adrian Roos82142c22014-03-27 14:56:59 +0100100 private static final String TAG = "TrustManagerService";
Adrian Roos5d639782016-07-21 11:43:02 -0700101 static final boolean DEBUG = Build.IS_DEBUGGABLE && Log.isLoggable(TAG, Log.VERBOSE);
Adrian Roos82142c22014-03-27 14:56:59 +0100102
103 private static final Intent TRUST_AGENT_INTENT =
104 new Intent(TrustAgentService.SERVICE_INTERFACE);
Adrian Roos18ea8932014-05-28 14:53:06 +0200105 private static final String PERMISSION_PROVIDE_AGENT = Manifest.permission.PROVIDE_TRUST_AGENT;
Adrian Roos82142c22014-03-27 14:56:59 +0100106
107 private static final int MSG_REGISTER_LISTENER = 1;
108 private static final int MSG_UNREGISTER_LISTENER = 2;
109 private static final int MSG_DISPATCH_UNLOCK_ATTEMPT = 3;
110 private static final int MSG_ENABLED_AGENTS_CHANGED = 4;
Adrian Roos481a6df2014-11-20 19:48:56 +0100111 private static final int MSG_KEYGUARD_SHOWING_CHANGED = 6;
112 private static final int MSG_START_USER = 7;
113 private static final int MSG_CLEANUP_USER = 8;
114 private static final int MSG_SWITCH_USER = 9;
Rubin Xu83a15bc2016-08-10 10:53:24 +0100115 private static final int MSG_FLUSH_TRUST_USUALLY_MANAGED = 10;
116 private static final int MSG_UNLOCK_USER = 11;
Andrew Scull85a63bc2016-10-24 13:47:47 +0100117 private static final int MSG_STOP_USER = 12;
Zachary Iqbal327323d2017-01-12 14:41:13 -0800118 private static final int MSG_DISPATCH_UNLOCK_LOCKOUT = 13;
Kevin Chyn3fdbbf82017-05-06 15:11:53 -0700119 private static final int MSG_REFRESH_DEVICE_LOCKED_FOR_USER = 14;
Vishwath Mohan15f7dd02018-12-12 11:15:08 -0800120 private static final int MSG_SCHEDULE_TRUST_TIMEOUT = 15;
Adrian Roosc13723f2016-01-12 20:29:03 +0100121
Adrian Roos517b3a42016-03-03 14:58:33 -0800122 private static final int TRUST_USUALLY_MANAGED_FLUSH_DELAY = 2 * 60 * 1000;
Vishwath Mohan15f7dd02018-12-12 11:15:08 -0800123 private static final String TRUST_TIMEOUT_ALARM_TAG = "TrustManagerService.trustTimeoutForUser";
Dmitry Dementyev38579682019-01-22 13:41:34 -0800124 private static final long TRUST_TIMEOUT_IN_MILLIS = 4 * 60 * 60 * 1000;
Adrian Roos82142c22014-03-27 14:56:59 +0100125
Adrian Roosb5e47222015-08-14 15:53:06 -0700126 private final ArraySet<AgentInfo> mActiveAgents = new ArraySet<>();
127 private final ArrayList<ITrustListener> mTrustListeners = new ArrayList<>();
Adrian Roos9dbe1902014-08-13 18:25:52 +0200128 private final Receiver mReceiver = new Receiver();
Adrian Roosb5e47222015-08-14 15:53:06 -0700129
Adrian Roos7a4f3d42014-05-02 12:12:20 +0200130 /* package */ final TrustArchive mArchive = new TrustArchive();
Adrian Roos82142c22014-03-27 14:56:59 +0100131 private final Context mContext;
Adrian Roos3870d452014-09-05 18:22:28 +0200132 private final LockPatternUtils mLockPatternUtils;
Adrian Roosbcd07652014-10-22 16:57:16 +0200133 private final UserManager mUserManager;
Adrian Rooscbe614f2014-10-28 20:16:12 +0100134 private final ActivityManager mActivityManager;
Adrian Roos82142c22014-03-27 14:56:59 +0100135
Adrian Roosbcd07652014-10-22 16:57:16 +0200136 @GuardedBy("mUserIsTrusted")
137 private final SparseBooleanArray mUserIsTrusted = new SparseBooleanArray();
Adrian Roos82142c22014-03-27 14:56:59 +0100138
Rubin Xuc3986272019-11-05 10:15:36 +0000139 /**
140 * Stores the locked state for users on the device. There are three different type of users
141 * which are handled slightly differently:
142 * <ul>
143 * <li> Users with real keyguard
144 * These are users who can be switched to ({@link UserInfo#supportsSwitchToByUser()}). Their
145 * locked state is derived by a combination of user secure state, keyguard state, trust agent
146 * decision and biometric authentication result. These are updated via
147 * {@link #refreshDeviceLockedForUser(int)} and result stored in {@link #mDeviceLockedForUser}.
148 * <li> Managed profiles with unified challenge
149 * Managed profile with unified challenge always shares the same locked state as their parent,
150 * so their locked state is not recorded in {@link #mDeviceLockedForUser}. Instead,
151 * {@link ITrustManager#isDeviceLocked(int)} always resolves their parent user handle and
152 * queries its locked state instead.
153 * <li> Managed profiles with separate challenge
154 * Locked state for profile with separate challenge is determined by other parts of the
155 * framework (mostly PowerManager) and pushed to TrustManagerService via
156 * {@link ITrustManager#setDeviceLockedForUser(int, boolean)}. Although in a corner case when
157 * the profile has a separate but empty challenge, setting its {@link #mDeviceLockedForUser} to
158 * {@code false} is actually done by {@link #refreshDeviceLockedForUser(int)}.
159 * </ul>
160 * TODO: Rename {@link ITrustManager#setDeviceLockedForUser(int, boolean)} to
161 * {@code setDeviceLockedForProfile} to better reflect its purpose. Unifying
162 * {@code setDeviceLockedForProfile} and {@link #setDeviceLockedForUser} would also be nice.
163 * At the moment they both update {@link #mDeviceLockedForUser} but have slightly different
164 * side-effects: one notifies trust agents while the other sends out a broadcast.
165 */
Adrian Roos481a6df2014-11-20 19:48:56 +0100166 @GuardedBy("mDeviceLockedForUser")
167 private final SparseBooleanArray mDeviceLockedForUser = new SparseBooleanArray();
168
Kevin Chyn3fdbbf82017-05-06 15:11:53 -0700169 @GuardedBy("mTrustUsuallyManagedForUser")
Adrian Roosc13723f2016-01-12 20:29:03 +0100170 private final SparseBooleanArray mTrustUsuallyManagedForUser = new SparseBooleanArray();
171
Kevin Chyn3fdbbf82017-05-06 15:11:53 -0700172 // set to true only if user can skip bouncer
Gilad Brettercb51b8b2018-03-22 17:04:51 +0200173 @GuardedBy("mUsersUnlockedByBiometric")
174 private final SparseBooleanArray mUsersUnlockedByBiometric = new SparseBooleanArray();
Kevin Chyn3fdbbf82017-05-06 15:11:53 -0700175
Vishwath Mohan15f7dd02018-12-12 11:15:08 -0800176 private final ArrayMap<Integer, TrustTimeoutAlarmListener> mTrustTimeoutAlarmListenerForUser =
177 new ArrayMap<>();
178 private AlarmManager mAlarmManager;
179 private final SettingsObserver mSettingsObserver;
180
Rakesh Iyera7aa4d62016-01-19 17:27:23 -0800181 private final StrongAuthTracker mStrongAuthTracker;
182
Adrian Rooscbe614f2014-10-28 20:16:12 +0100183 private boolean mTrustAgentsCanRun = false;
Xiaohui Chen09e02912015-08-05 09:44:56 -0700184 private int mCurrentUser = UserHandle.USER_SYSTEM;
Adrian Rooscbe614f2014-10-28 20:16:12 +0100185
Adrian Roos82142c22014-03-27 14:56:59 +0100186 public TrustManagerService(Context context) {
187 super(context);
188 mContext = context;
189 mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
Adrian Rooscbe614f2014-10-28 20:16:12 +0100190 mActivityManager = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
Adrian Roos3870d452014-09-05 18:22:28 +0200191 mLockPatternUtils = new LockPatternUtils(context);
Adrian Roos517b3a42016-03-03 14:58:33 -0800192 mStrongAuthTracker = new StrongAuthTracker(context);
Vishwath Mohan15f7dd02018-12-12 11:15:08 -0800193 mAlarmManager = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
194 mSettingsObserver = new SettingsObserver(mHandler);
Adrian Roos82142c22014-03-27 14:56:59 +0100195 }
196
197 @Override
198 public void onStart() {
199 publishBinderService(Context.TRUST_SERVICE, mService);
200 }
201
202 @Override
203 public void onBootPhase(int phase) {
Adrian Roos49d53452014-10-24 15:48:39 +0200204 if (isSafeMode()) {
205 // No trust agents in safe mode.
206 return;
207 }
208 if (phase == SystemService.PHASE_SYSTEM_SERVICES_READY) {
Adrian Roos82142c22014-03-27 14:56:59 +0100209 mPackageMonitor.register(mContext, mHandler.getLooper(), UserHandle.ALL, true);
Adrian Roos9dbe1902014-08-13 18:25:52 +0200210 mReceiver.register(mContext);
Adrian Roosb5e47222015-08-14 15:53:06 -0700211 mLockPatternUtils.registerStrongAuthTracker(mStrongAuthTracker);
Adrian Rooscbe614f2014-10-28 20:16:12 +0100212 } else if (phase == SystemService.PHASE_THIRD_PARTY_APPS_CAN_START) {
213 mTrustAgentsCanRun = true;
Marco Fucci4e68f112014-08-29 12:31:48 -0700214 refreshAgentList(UserHandle.USER_ALL);
Xiaohui Chen605733b2016-05-19 16:39:09 -0700215 refreshDeviceLockedForUser(UserHandle.USER_ALL);
Adrian Roos49d53452014-10-24 15:48:39 +0200216 } else if (phase == SystemService.PHASE_BOOT_COMPLETED) {
Xiaohui Chen09e02912015-08-05 09:44:56 -0700217 maybeEnableFactoryTrustAgents(mLockPatternUtils, UserHandle.USER_SYSTEM);
Adrian Roos82142c22014-03-27 14:56:59 +0100218 }
219 }
220
Vishwath Mohan15f7dd02018-12-12 11:15:08 -0800221 // Extend unlock config and logic
222
223 private final class SettingsObserver extends ContentObserver {
224 private final Uri TRUST_AGENTS_EXTEND_UNLOCK =
225 Settings.Secure.getUriFor(Settings.Secure.TRUST_AGENTS_EXTEND_UNLOCK);
226
227 private final Uri LOCK_SCREEN_WHEN_TRUST_LOST =
228 Settings.Secure.getUriFor(Settings.Secure.LOCK_SCREEN_WHEN_TRUST_LOST);
229
Anthony Chen9128a5a2019-06-25 09:50:56 -0700230 private final boolean mIsAutomotive;
Vishwath Mohan15f7dd02018-12-12 11:15:08 -0800231 private final ContentResolver mContentResolver;
232 private boolean mTrustAgentsExtendUnlock;
233 private boolean mLockWhenTrustLost;
234
235 /**
236 * Creates a settings observer
237 *
238 * @param handler The handler to run {@link #onChange} on, or null if none.
239 */
240 SettingsObserver(Handler handler) {
241 super(handler);
Anthony Chen9128a5a2019-06-25 09:50:56 -0700242
243 PackageManager packageManager = getContext().getPackageManager();
244 mIsAutomotive = packageManager.hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE);
245
Vishwath Mohan15f7dd02018-12-12 11:15:08 -0800246 mContentResolver = getContext().getContentResolver();
247 updateContentObserver();
248 }
249
250 void updateContentObserver() {
251 mContentResolver.unregisterContentObserver(this);
252 mContentResolver.registerContentObserver(TRUST_AGENTS_EXTEND_UNLOCK,
253 false /* notifyForDescendents */,
254 this /* observer */,
255 mCurrentUser);
256 mContentResolver.registerContentObserver(LOCK_SCREEN_WHEN_TRUST_LOST,
257 false /* notifyForDescendents */,
258 this /* observer */,
259 mCurrentUser);
260
261 // Update the value immediately
262 onChange(true /* selfChange */, TRUST_AGENTS_EXTEND_UNLOCK);
263 onChange(true /* selfChange */, LOCK_SCREEN_WHEN_TRUST_LOST);
264 }
265
266 @Override
267 public void onChange(boolean selfChange, Uri uri) {
268 if (TRUST_AGENTS_EXTEND_UNLOCK.equals(uri)) {
Anthony Chen9128a5a2019-06-25 09:50:56 -0700269 // Smart lock should only extend unlock. The only exception is for automotive,
270 // where it can actively unlock the head unit.
271 int defaultValue = mIsAutomotive ? 0 : 1;
272
Vishwath Mohan15f7dd02018-12-12 11:15:08 -0800273 mTrustAgentsExtendUnlock =
274 Settings.Secure.getIntForUser(
275 mContentResolver,
276 Settings.Secure.TRUST_AGENTS_EXTEND_UNLOCK,
Anthony Chen9128a5a2019-06-25 09:50:56 -0700277 defaultValue,
Vishwath Mohan15f7dd02018-12-12 11:15:08 -0800278 mCurrentUser) != 0;
279 } else if (LOCK_SCREEN_WHEN_TRUST_LOST.equals(uri)) {
280 mLockWhenTrustLost =
281 Settings.Secure.getIntForUser(
282 mContentResolver,
283 Settings.Secure.LOCK_SCREEN_WHEN_TRUST_LOST,
284 0 /* default */,
285 mCurrentUser) != 0;
286 }
287 }
288
289 boolean getTrustAgentsExtendUnlock() {
290 return mTrustAgentsExtendUnlock;
291 }
292
293 boolean getLockWhenTrustLost() {
294 return mLockWhenTrustLost;
295 }
296 }
297
298 private void maybeLockScreen(int userId) {
299 if (userId != mCurrentUser) {
300 return;
301 }
302
303 if (mSettingsObserver.getLockWhenTrustLost()) {
304 if (DEBUG) Slog.d(TAG, "Locking device because trust was lost");
305 try {
306 WindowManagerGlobal.getWindowManagerService().lockNow(null);
307 } catch (RemoteException e) {
308 Slog.e(TAG, "Error locking screen when trust was lost");
309 }
310
311 // If active unlocking is not allowed, cancel any pending trust timeouts because the
312 // screen is already locked.
313 TrustTimeoutAlarmListener alarm = mTrustTimeoutAlarmListenerForUser.get(userId);
314 if (alarm != null && mSettingsObserver.getTrustAgentsExtendUnlock()) {
315 mAlarmManager.cancel(alarm);
316 alarm.setQueued(false /* isQueued */);
317 }
318 }
319 }
320
321 private void scheduleTrustTimeout(int userId, boolean override) {
322 int shouldOverride = override ? 1 : 0;
323 if (override) {
324 shouldOverride = 1;
325 }
326 mHandler.obtainMessage(MSG_SCHEDULE_TRUST_TIMEOUT, userId, shouldOverride).sendToTarget();
327 }
328
329 private void handleScheduleTrustTimeout(int userId, int shouldOverride) {
330 long when = SystemClock.elapsedRealtime() + TRUST_TIMEOUT_IN_MILLIS;
331 userId = mCurrentUser;
332 TrustTimeoutAlarmListener alarm = mTrustTimeoutAlarmListenerForUser.get(userId);
333
334 // Cancel existing trust timeouts for this user if needed.
335 if (alarm != null) {
336 if (shouldOverride == 0 && alarm.isQueued()) {
337 if (DEBUG) Slog.d(TAG, "Found existing trust timeout alarm. Skipping.");
338 return;
339 }
340 mAlarmManager.cancel(alarm);
341 } else {
342 alarm = new TrustTimeoutAlarmListener(userId);
343 mTrustTimeoutAlarmListenerForUser.put(userId, alarm);
344 }
345
346 if (DEBUG) Slog.d(TAG, "\tSetting up trust timeout alarm");
347 alarm.setQueued(true /* isQueued */);
348 mAlarmManager.setExact(
349 AlarmManager.ELAPSED_REALTIME_WAKEUP, when, TRUST_TIMEOUT_ALARM_TAG, alarm,
350 mHandler);
351 }
352
353 // Agent management
Adrian Roos82142c22014-03-27 14:56:59 +0100354
355 private static final class AgentInfo {
356 CharSequence label;
357 Drawable icon;
358 ComponentName component; // service that implements ITrustAgent
Lingjun Li20914d72016-11-14 15:39:13 -0800359 SettingsAttrs settings; // setting to launch to modify agent.
Adrian Roos82142c22014-03-27 14:56:59 +0100360 TrustAgentWrapper agent;
361 int userId;
362
363 @Override
364 public boolean equals(Object other) {
365 if (!(other instanceof AgentInfo)) {
366 return false;
367 }
368 AgentInfo o = (AgentInfo) other;
369 return component.equals(o.component) && userId == o.userId;
370 }
371
372 @Override
373 public int hashCode() {
374 return component.hashCode() * 31 + userId;
375 }
376 }
377
378 private void updateTrustAll() {
379 List<UserInfo> userInfos = mUserManager.getUsers(true /* excludeDying */);
380 for (UserInfo userInfo : userInfos) {
Adrian Roos94e15a52015-04-16 12:23:18 -0700381 updateTrust(userInfo.id, 0);
Adrian Roos82142c22014-03-27 14:56:59 +0100382 }
383 }
384
Vishwath Mohan15f7dd02018-12-12 11:15:08 -0800385
Adrian Roos94e15a52015-04-16 12:23:18 -0700386 public void updateTrust(int userId, int flags) {
Vishwath Mohan15f7dd02018-12-12 11:15:08 -0800387 updateTrust(userId, flags, false /* isFromUnlock */);
388 }
389
390 private void updateTrust(int userId, int flags, boolean isFromUnlock) {
Adrian Roosc13723f2016-01-12 20:29:03 +0100391 boolean managed = aggregateIsTrustManaged(userId);
392 dispatchOnTrustManagedChanged(managed, userId);
393 if (mStrongAuthTracker.isTrustAllowedForUser(userId)
394 && isTrustUsuallyManagedInternal(userId) != managed) {
395 updateTrustUsuallyManaged(userId, managed);
396 }
Vishwath Mohan15f7dd02018-12-12 11:15:08 -0800397
Adrian Roosbcd07652014-10-22 16:57:16 +0200398 boolean trusted = aggregateIsTrusted(userId);
Vishwath Mohan15f7dd02018-12-12 11:15:08 -0800399 IWindowManager wm = WindowManagerGlobal.getWindowManagerService();
400 boolean showingKeyguard = true;
401 try {
402 showingKeyguard = wm.isKeyguardLocked();
403 } catch (RemoteException e) {
404 }
405
Adrian Roos481a6df2014-11-20 19:48:56 +0100406 boolean changed;
Adrian Roosbcd07652014-10-22 16:57:16 +0200407 synchronized (mUserIsTrusted) {
Chad Brubakerc4c52572019-02-17 13:34:02 -0800408 if (mSettingsObserver.getTrustAgentsExtendUnlock()) {
409 // In extend unlock trust agents can only set the device to trusted if it already
410 // trusted or the device is unlocked. Attempting to set the device as trusted
411 // when the device is locked will be ignored.
412 changed = mUserIsTrusted.get(userId) != trusted;
413 trusted = trusted
414 && (!showingKeyguard || isFromUnlock || !changed)
415 && userId == mCurrentUser;
416 if (DEBUG) {
417 Slog.d(TAG, "Extend unlock setting trusted as " + Boolean.toString(trusted)
418 + " && " + Boolean.toString(!showingKeyguard)
419 + " && " + Boolean.toString(userId == mCurrentUser));
420 }
421 }
Adrian Roos481a6df2014-11-20 19:48:56 +0100422 changed = mUserIsTrusted.get(userId) != trusted;
Adrian Roosbcd07652014-10-22 16:57:16 +0200423 mUserIsTrusted.put(userId, trusted);
424 }
Adrian Roos94e15a52015-04-16 12:23:18 -0700425 dispatchOnTrustChanged(trusted, userId, flags);
Adrian Roos481a6df2014-11-20 19:48:56 +0100426 if (changed) {
427 refreshDeviceLockedForUser(userId);
Vishwath Mohan15f7dd02018-12-12 11:15:08 -0800428 if (!trusted) {
429 maybeLockScreen(userId);
430 } else {
431 scheduleTrustTimeout(userId, false /* override */);
432 }
Adrian Roos481a6df2014-11-20 19:48:56 +0100433 }
Adrian Roos82142c22014-03-27 14:56:59 +0100434 }
435
Adrian Roosc13723f2016-01-12 20:29:03 +0100436 private void updateTrustUsuallyManaged(int userId, boolean managed) {
437 synchronized (mTrustUsuallyManagedForUser) {
438 mTrustUsuallyManagedForUser.put(userId, managed);
439 }
440 // Wait a few minutes before committing to flash, in case the trust agent is transiently not
441 // managing trust (crashed, needs to acknowledge DPM restrictions, etc).
442 mHandler.removeMessages(MSG_FLUSH_TRUST_USUALLY_MANAGED);
443 mHandler.sendMessageDelayed(
444 mHandler.obtainMessage(MSG_FLUSH_TRUST_USUALLY_MANAGED),
445 TRUST_USUALLY_MANAGED_FLUSH_DELAY);
446 }
447
Lingjun Li93a145f2017-01-23 17:13:35 -0800448 public long addEscrowToken(byte[] token, int userId) {
Ram Periathiruvadi32d53552019-02-19 13:25:46 -0800449 return mLockPatternUtils.addEscrowToken(token, userId,
450 (long handle, int userid) -> {
451 dispatchEscrowTokenActivatedLocked(handle, userid);
452 });
Lingjun Li93a145f2017-01-23 17:13:35 -0800453 }
454
455 public boolean removeEscrowToken(long handle, int userId) {
456 return mLockPatternUtils.removeEscrowToken(handle, userId);
457 }
458
459 public boolean isEscrowTokenActive(long handle, int userId) {
460 return mLockPatternUtils.isEscrowTokenActive(handle, userId);
461 }
462
463 public void unlockUserWithToken(long handle, byte[] token, int userId) {
464 mLockPatternUtils.unlockUserWithToken(handle, token, userId);
465 }
466
Lucas Dupinef886542018-01-03 16:03:07 -0800467 void showKeyguardErrorMessage(CharSequence message) {
468 dispatchOnTrustError(message);
469 }
470
Adrian Roos517b3a42016-03-03 14:58:33 -0800471 void refreshAgentList(int userIdOrAll) {
472 if (DEBUG) Slog.d(TAG, "refreshAgentList(" + userIdOrAll + ")");
Adrian Rooscbe614f2014-10-28 20:16:12 +0100473 if (!mTrustAgentsCanRun) {
Adrian Roos49d53452014-10-24 15:48:39 +0200474 return;
475 }
Adrian Roos517b3a42016-03-03 14:58:33 -0800476 if (userIdOrAll != UserHandle.USER_ALL && userIdOrAll < UserHandle.USER_SYSTEM) {
477 Log.e(TAG, "refreshAgentList(userId=" + userIdOrAll + "): Invalid user handle,"
Adrian Roose681c272014-09-08 14:03:47 +0200478 + " must be USER_ALL or a specific user.", new Throwable("here"));
Adrian Roos517b3a42016-03-03 14:58:33 -0800479 userIdOrAll = UserHandle.USER_ALL;
Adrian Roose681c272014-09-08 14:03:47 +0200480 }
Adrian Roos82142c22014-03-27 14:56:59 +0100481 PackageManager pm = mContext.getPackageManager();
482
Marco Fucci4e68f112014-08-29 12:31:48 -0700483 List<UserInfo> userInfos;
Adrian Roos517b3a42016-03-03 14:58:33 -0800484 if (userIdOrAll == UserHandle.USER_ALL) {
Marco Fucci4e68f112014-08-29 12:31:48 -0700485 userInfos = mUserManager.getUsers(true /* excludeDying */);
486 } else {
487 userInfos = new ArrayList<>();
Adrian Roos517b3a42016-03-03 14:58:33 -0800488 userInfos.add(mUserManager.getUserInfo(userIdOrAll));
Marco Fucci4e68f112014-08-29 12:31:48 -0700489 }
Adrian Roos3870d452014-09-05 18:22:28 +0200490 LockPatternUtils lockPatternUtils = mLockPatternUtils;
Adrian Roos82142c22014-03-27 14:56:59 +0100491
Adrian Roosc5f95ce2014-07-24 16:00:46 +0200492 ArraySet<AgentInfo> obsoleteAgents = new ArraySet<>();
493 obsoleteAgents.addAll(mActiveAgents);
Adrian Roos82142c22014-03-27 14:56:59 +0100494
495 for (UserInfo userInfo : userInfos) {
Adrian Roosfc29e0b2014-11-11 12:55:44 +0100496 if (userInfo == null || userInfo.partial || !userInfo.isEnabled()
497 || userInfo.guestToRemove) continue;
Adrian Roos5d639782016-07-21 11:43:02 -0700498 if (!userInfo.supportsSwitchToByUser()) {
499 if (DEBUG) Slog.d(TAG, "refreshAgentList: skipping user " + userInfo.id
500 + ": switchToByUser=false");
501 continue;
502 }
Adrian Roos5d639782016-07-21 11:43:02 -0700503 if (!mActivityManager.isUserRunning(userInfo.id)) {
504 if (DEBUG) Slog.d(TAG, "refreshAgentList: skipping user " + userInfo.id
505 + ": user not started");
506 continue;
507 }
508 if (!lockPatternUtils.isSecure(userInfo.id)) {
509 if (DEBUG) Slog.d(TAG, "refreshAgentList: skipping user " + userInfo.id
510 + ": no secure credential");
511 continue;
512 }
Lingjun Li20914d72016-11-14 15:39:13 -0800513
Adrian Roos8f211582014-07-29 15:09:57 +0200514 DevicePolicyManager dpm = lockPatternUtils.getDevicePolicyManager();
515 int disabledFeatures = dpm.getKeyguardDisabledFeatures(null, userInfo.id);
Jim Miller604e7552014-07-18 19:00:02 -0700516 final boolean disableTrustAgents =
Adrian Roosca36b952014-05-16 18:52:29 +0200517 (disabledFeatures & DevicePolicyManager.KEYGUARD_DISABLE_TRUST_AGENTS) != 0;
518
Adrian Roos82142c22014-03-27 14:56:59 +0100519 List<ComponentName> enabledAgents = lockPatternUtils.getEnabledTrustAgents(userInfo.id);
Adrian Roos8f211582014-07-29 15:09:57 +0200520 if (enabledAgents == null) {
Adrian Roos5d639782016-07-21 11:43:02 -0700521 if (DEBUG) Slog.d(TAG, "refreshAgentList: skipping user " + userInfo.id
522 + ": no agents enabled by user");
Adrian Roos82142c22014-03-27 14:56:59 +0100523 continue;
524 }
Adrian Roos3870d452014-09-05 18:22:28 +0200525 List<ResolveInfo> resolveInfos = resolveAllowedTrustAgents(pm, userInfo.id);
Adrian Roos82142c22014-03-27 14:56:59 +0100526 for (ResolveInfo resolveInfo : resolveInfos) {
Adrian Roos82142c22014-03-27 14:56:59 +0100527 ComponentName name = getComponentName(resolveInfo);
Adrian Roos82142c22014-03-27 14:56:59 +0100528
Adrian Roos5d639782016-07-21 11:43:02 -0700529 if (!enabledAgents.contains(name)) {
530 if (DEBUG) Slog.d(TAG, "refreshAgentList: skipping "
531 + name.flattenToShortString() + " u"+ userInfo.id
532 + ": not enabled by user");
533 continue;
534 }
Adrian Roos8f211582014-07-29 15:09:57 +0200535 if (disableTrustAgents) {
Jim Millere303bf42014-08-26 17:12:29 -0700536 List<PersistableBundle> config =
537 dpm.getTrustAgentConfiguration(null /* admin */, name, userInfo.id);
Adrian Roos8f211582014-07-29 15:09:57 +0200538 // Disable agent if no features are enabled.
Adrian Roos5d639782016-07-21 11:43:02 -0700539 if (config == null || config.isEmpty()) {
540 if (DEBUG) Slog.d(TAG, "refreshAgentList: skipping "
541 + name.flattenToShortString() + " u"+ userInfo.id
542 + ": not allowed by DPM");
543 continue;
544 }
Adrian Roos8f211582014-07-29 15:09:57 +0200545 }
Adrian Roos82142c22014-03-27 14:56:59 +0100546 AgentInfo agentInfo = new AgentInfo();
547 agentInfo.component = name;
548 agentInfo.userId = userInfo.id;
549 if (!mActiveAgents.contains(agentInfo)) {
550 agentInfo.label = resolveInfo.loadLabel(pm);
551 agentInfo.icon = resolveInfo.loadIcon(pm);
Lingjun Li20914d72016-11-14 15:39:13 -0800552 agentInfo.settings = getSettingsAttrs(pm, resolveInfo);
Lingjun Li20914d72016-11-14 15:39:13 -0800553 } else {
554 int index = mActiveAgents.indexOf(agentInfo);
555 agentInfo = mActiveAgents.valueAt(index);
556 }
557
Vishwath Mohan60ea5532019-05-25 12:23:02 -0700558 boolean directUnlock = false;
559 if (agentInfo.settings != null) {
560 directUnlock = resolveInfo.serviceInfo.directBootAware
561 && agentInfo.settings.canUnlockProfile;
562 }
Lingjun Li20914d72016-11-14 15:39:13 -0800563
564 if (directUnlock) {
565 if (DEBUG) Slog.d(TAG, "refreshAgentList: trustagent " + name
566 + "of user " + userInfo.id + "can unlock user profile.");
567 }
568
Jeff Sharkeya65e6492017-06-21 13:45:11 -0600569 if (!mUserManager.isUserUnlockingOrUnlocked(userInfo.id)
Lingjun Li20914d72016-11-14 15:39:13 -0800570 && !directUnlock) {
571 if (DEBUG) Slog.d(TAG, "refreshAgentList: skipping user " + userInfo.id
Lingjun Li93a145f2017-01-23 17:13:35 -0800572 + "'s trust agent " + name + ": FBE still locked and "
Lingjun Li20914d72016-11-14 15:39:13 -0800573 + " the agent cannot unlock user profile.");
574 continue;
575 }
576
577 if (!mStrongAuthTracker.canAgentsRunForUser(userInfo.id)) {
578 int flag = mStrongAuthTracker.getStrongAuthForUser(userInfo.id);
Zachary Iqbal327323d2017-01-12 14:41:13 -0800579 if (flag != StrongAuthTracker.STRONG_AUTH_REQUIRED_AFTER_LOCKOUT) {
580 if (flag != StrongAuthTracker.STRONG_AUTH_REQUIRED_AFTER_BOOT
581 || !directUnlock) {
582 if (DEBUG)
583 Slog.d(TAG, "refreshAgentList: skipping user " + userInfo.id
584 + ": prevented by StrongAuthTracker = 0x"
585 + Integer.toHexString(mStrongAuthTracker.getStrongAuthForUser(
586 userInfo.id)));
587 continue;
588 }
Lingjun Li20914d72016-11-14 15:39:13 -0800589 }
590 }
591
Adrian Roosb884bb22017-05-03 11:33:51 -0700592 if (agentInfo.agent == null) {
593 agentInfo.agent = new TrustAgentWrapper(mContext, this,
594 new Intent().setComponent(name), userInfo.getUserHandle());
595 }
596
Lingjun Li20914d72016-11-14 15:39:13 -0800597 if (!mActiveAgents.contains(agentInfo)) {
Adrian Roos82142c22014-03-27 14:56:59 +0100598 mActiveAgents.add(agentInfo);
599 } else {
Adrian Roosc5f95ce2014-07-24 16:00:46 +0200600 obsoleteAgents.remove(agentInfo);
Adrian Roos82142c22014-03-27 14:56:59 +0100601 }
602 }
603 }
604
605 boolean trustMayHaveChanged = false;
Adrian Roosc5f95ce2014-07-24 16:00:46 +0200606 for (int i = 0; i < obsoleteAgents.size(); i++) {
607 AgentInfo info = obsoleteAgents.valueAt(i);
Adrian Roos517b3a42016-03-03 14:58:33 -0800608 if (userIdOrAll == UserHandle.USER_ALL || userIdOrAll == info.userId) {
Adrian Roose681c272014-09-08 14:03:47 +0200609 if (info.agent.isManagingTrust()) {
610 trustMayHaveChanged = true;
611 }
Adrian Roosfc29e0b2014-11-11 12:55:44 +0100612 info.agent.destroy();
Adrian Roose681c272014-09-08 14:03:47 +0200613 mActiveAgents.remove(info);
Adrian Roos82142c22014-03-27 14:56:59 +0100614 }
Adrian Roos82142c22014-03-27 14:56:59 +0100615 }
616
617 if (trustMayHaveChanged) {
Adrian Roos517b3a42016-03-03 14:58:33 -0800618 if (userIdOrAll == UserHandle.USER_ALL) {
Adrian Rooscbe614f2014-10-28 20:16:12 +0100619 updateTrustAll();
620 } else {
Adrian Roos517b3a42016-03-03 14:58:33 -0800621 updateTrust(userIdOrAll, 0);
Adrian Rooscbe614f2014-10-28 20:16:12 +0100622 }
Adrian Roos82142c22014-03-27 14:56:59 +0100623 }
624 }
625
Adrian Roos481a6df2014-11-20 19:48:56 +0100626 boolean isDeviceLockedInner(int userId) {
627 synchronized (mDeviceLockedForUser) {
628 return mDeviceLockedForUser.get(userId, true);
629 }
630 }
631
Rubin Xuc3986272019-11-05 10:15:36 +0000632 /**
633 * Update the user's locked state. Only applicable to users with a real keyguard
634 * ({@link UserInfo#supportsSwitchToByUser}) and unsecured managed profiles.
635 */
Adrian Roos481a6df2014-11-20 19:48:56 +0100636 private void refreshDeviceLockedForUser(int userId) {
Xiaohui Chen09e02912015-08-05 09:44:56 -0700637 if (userId != UserHandle.USER_ALL && userId < UserHandle.USER_SYSTEM) {
Adrian Roos7e2e40e2014-11-21 15:27:12 +0100638 Log.e(TAG, "refreshDeviceLockedForUser(userId=" + userId + "): Invalid user handle,"
Adrian Roos481a6df2014-11-20 19:48:56 +0100639 + " must be USER_ALL or a specific user.", new Throwable("here"));
640 userId = UserHandle.USER_ALL;
641 }
Adrian Roos481a6df2014-11-20 19:48:56 +0100642 List<UserInfo> userInfos;
643 if (userId == UserHandle.USER_ALL) {
644 userInfos = mUserManager.getUsers(true /* excludeDying */);
645 } else {
646 userInfos = new ArrayList<>();
647 userInfos.add(mUserManager.getUserInfo(userId));
648 }
649
650 IWindowManager wm = WindowManagerGlobal.getWindowManagerService();
651
652 for (int i = 0; i < userInfos.size(); i++) {
653 UserInfo info = userInfos.get(i);
654
Pavel Grafov259ca362018-07-27 14:04:57 +0100655 if (info == null || info.partial || !info.isEnabled() || info.guestToRemove) {
Adrian Roos481a6df2014-11-20 19:48:56 +0100656 continue;
657 }
658
659 int id = info.id;
660 boolean secure = mLockPatternUtils.isSecure(id);
Pavel Grafov259ca362018-07-27 14:04:57 +0100661
662 if (!info.supportsSwitchToByUser()) {
663 if (info.isManagedProfile() && !secure) {
664 setDeviceLockedForUser(id, false);
665 }
666 continue;
667 }
668
Adrian Roos481a6df2014-11-20 19:48:56 +0100669 boolean trusted = aggregateIsTrusted(id);
670 boolean showingKeyguard = true;
Gilad Brettercb51b8b2018-03-22 17:04:51 +0200671 boolean biometricAuthenticated = false;
Kevin Chyn3fdbbf82017-05-06 15:11:53 -0700672
Adrian Roos481a6df2014-11-20 19:48:56 +0100673 if (mCurrentUser == id) {
Gilad Brettercb51b8b2018-03-22 17:04:51 +0200674 synchronized(mUsersUnlockedByBiometric) {
675 biometricAuthenticated = mUsersUnlockedByBiometric.get(id, false);
Kevin Chyn3fdbbf82017-05-06 15:11:53 -0700676 }
Adrian Roos481a6df2014-11-20 19:48:56 +0100677 try {
678 showingKeyguard = wm.isKeyguardLocked();
679 } catch (RemoteException e) {
680 }
681 }
Kevin Chyn3fdbbf82017-05-06 15:11:53 -0700682 boolean deviceLocked = secure && showingKeyguard && !trusted &&
Gilad Brettercb51b8b2018-03-22 17:04:51 +0200683 !biometricAuthenticated;
Andrew Scull85a63bc2016-10-24 13:47:47 +0100684 setDeviceLockedForUser(id, deviceLocked);
685 }
686 }
Adrian Roos481a6df2014-11-20 19:48:56 +0100687
Andrew Scull85a63bc2016-10-24 13:47:47 +0100688 private void setDeviceLockedForUser(@UserIdInt int userId, boolean locked) {
689 final boolean changed;
690 synchronized (mDeviceLockedForUser) {
691 changed = isDeviceLockedInner(userId) != locked;
692 mDeviceLockedForUser.put(userId, locked);
693 }
694 if (changed) {
695 dispatchDeviceLocked(userId, locked);
Rubin Xuc3986272019-11-05 10:15:36 +0000696
697 KeyStore.getInstance().onUserLockedStateChanged(userId, locked);
698 // Also update the user's profiles who have unified challenge, since they
699 // share the same unlocked state (see {@link #isDeviceLocked(int)})
700 for (int profileHandle : mUserManager.getEnabledProfileIds(userId)) {
701 if (mLockPatternUtils.isManagedProfileWithUnifiedChallenge(profileHandle)) {
702 KeyStore.getInstance().onUserLockedStateChanged(profileHandle, locked);
703 }
704 }
Adrian Roos481a6df2014-11-20 19:48:56 +0100705 }
706 }
707
708 private void dispatchDeviceLocked(int userId, boolean isLocked) {
709 for (int i = 0; i < mActiveAgents.size(); i++) {
710 AgentInfo agent = mActiveAgents.valueAt(i);
711 if (agent.userId == userId) {
712 if (isLocked) {
713 agent.agent.onDeviceLocked();
714 } else{
715 agent.agent.onDeviceUnlocked();
716 }
717 }
718 }
719 }
720
Ram Periathiruvadi32d53552019-02-19 13:25:46 -0800721 private void dispatchEscrowTokenActivatedLocked(long handle, int userId) {
722 for (int i = 0; i < mActiveAgents.size(); i++) {
723 AgentInfo agent = mActiveAgents.valueAt(i);
724 if (agent.userId == userId) {
725 agent.agent.onEscrowTokenActivated(handle, userId);
726 }
727 }
728 }
729
Marco Fucci4e68f112014-08-29 12:31:48 -0700730 void updateDevicePolicyFeatures() {
Adrian Roos9d6fc922016-08-10 17:09:55 -0700731 boolean changed = false;
Adrian Roos8f211582014-07-29 15:09:57 +0200732 for (int i = 0; i < mActiveAgents.size(); i++) {
733 AgentInfo info = mActiveAgents.valueAt(i);
734 if (info.agent.isConnected()) {
735 info.agent.updateDevicePolicyFeatures();
Adrian Roos9d6fc922016-08-10 17:09:55 -0700736 changed = true;
Adrian Roos8f211582014-07-29 15:09:57 +0200737 }
738 }
Adrian Roos9d6fc922016-08-10 17:09:55 -0700739 if (changed) {
740 mArchive.logDevicePolicyChanged();
741 }
Adrian Roos8f211582014-07-29 15:09:57 +0200742 }
743
Adrian Roosc5f95ce2014-07-24 16:00:46 +0200744 private void removeAgentsOfPackage(String packageName) {
745 boolean trustMayHaveChanged = false;
746 for (int i = mActiveAgents.size() - 1; i >= 0; i--) {
747 AgentInfo info = mActiveAgents.valueAt(i);
748 if (packageName.equals(info.component.getPackageName())) {
749 Log.i(TAG, "Resetting agent " + info.component.flattenToShortString());
Adrian Roos7861c662014-07-25 15:37:28 +0200750 if (info.agent.isManagingTrust()) {
Adrian Roosc5f95ce2014-07-24 16:00:46 +0200751 trustMayHaveChanged = true;
752 }
Adrian Roosfc29e0b2014-11-11 12:55:44 +0100753 info.agent.destroy();
Adrian Roosc5f95ce2014-07-24 16:00:46 +0200754 mActiveAgents.removeAt(i);
755 }
756 }
757 if (trustMayHaveChanged) {
758 updateTrustAll();
759 }
760 }
761
762 public void resetAgent(ComponentName name, int userId) {
763 boolean trustMayHaveChanged = false;
764 for (int i = mActiveAgents.size() - 1; i >= 0; i--) {
765 AgentInfo info = mActiveAgents.valueAt(i);
766 if (name.equals(info.component) && userId == info.userId) {
767 Log.i(TAG, "Resetting agent " + info.component.flattenToShortString());
Adrian Roos7861c662014-07-25 15:37:28 +0200768 if (info.agent.isManagingTrust()) {
Adrian Roosc5f95ce2014-07-24 16:00:46 +0200769 trustMayHaveChanged = true;
770 }
Adrian Roosfc29e0b2014-11-11 12:55:44 +0100771 info.agent.destroy();
Adrian Roosc5f95ce2014-07-24 16:00:46 +0200772 mActiveAgents.removeAt(i);
773 }
774 }
775 if (trustMayHaveChanged) {
Adrian Roos94e15a52015-04-16 12:23:18 -0700776 updateTrust(userId, 0);
Adrian Roosc5f95ce2014-07-24 16:00:46 +0200777 }
Marco Fucci4e68f112014-08-29 12:31:48 -0700778 refreshAgentList(userId);
Adrian Roosc5f95ce2014-07-24 16:00:46 +0200779 }
780
Lingjun Li20914d72016-11-14 15:39:13 -0800781 private SettingsAttrs getSettingsAttrs(PackageManager pm, ResolveInfo resolveInfo) {
Adrian Roos82142c22014-03-27 14:56:59 +0100782 if (resolveInfo == null || resolveInfo.serviceInfo == null
783 || resolveInfo.serviceInfo.metaData == null) return null;
784 String cn = null;
Lingjun Li20914d72016-11-14 15:39:13 -0800785 boolean canUnlockProfile = false;
786
Adrian Roos82142c22014-03-27 14:56:59 +0100787 XmlResourceParser parser = null;
788 Exception caughtException = null;
789 try {
790 parser = resolveInfo.serviceInfo.loadXmlMetaData(pm,
791 TrustAgentService.TRUST_AGENT_META_DATA);
792 if (parser == null) {
793 Slog.w(TAG, "Can't find " + TrustAgentService.TRUST_AGENT_META_DATA + " meta-data");
794 return null;
795 }
796 Resources res = pm.getResourcesForApplication(resolveInfo.serviceInfo.applicationInfo);
797 AttributeSet attrs = Xml.asAttributeSet(parser);
798 int type;
799 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
800 && type != XmlPullParser.START_TAG) {
801 // Drain preamble.
802 }
803 String nodeName = parser.getName();
Adrian Roos7e03dfc2014-05-16 16:06:28 +0200804 if (!"trust-agent".equals(nodeName)) {
805 Slog.w(TAG, "Meta-data does not start with trust-agent tag");
Adrian Roos82142c22014-03-27 14:56:59 +0100806 return null;
807 }
808 TypedArray sa = res
809 .obtainAttributes(attrs, com.android.internal.R.styleable.TrustAgent);
810 cn = sa.getString(com.android.internal.R.styleable.TrustAgent_settingsActivity);
Lingjun Li20914d72016-11-14 15:39:13 -0800811 canUnlockProfile = sa.getBoolean(
812 com.android.internal.R.styleable.TrustAgent_unlockProfile, false);
Adrian Roos82142c22014-03-27 14:56:59 +0100813 sa.recycle();
814 } catch (PackageManager.NameNotFoundException e) {
815 caughtException = e;
816 } catch (IOException e) {
817 caughtException = e;
818 } catch (XmlPullParserException e) {
819 caughtException = e;
820 } finally {
821 if (parser != null) parser.close();
822 }
823 if (caughtException != null) {
824 Slog.w(TAG, "Error parsing : " + resolveInfo.serviceInfo.packageName, caughtException);
825 return null;
826 }
827 if (cn == null) {
828 return null;
829 }
830 if (cn.indexOf('/') < 0) {
831 cn = resolveInfo.serviceInfo.packageName + "/" + cn;
832 }
Lingjun Li20914d72016-11-14 15:39:13 -0800833 return new SettingsAttrs(ComponentName.unflattenFromString(cn), canUnlockProfile);
Adrian Roos82142c22014-03-27 14:56:59 +0100834 }
835
836 private ComponentName getComponentName(ResolveInfo resolveInfo) {
837 if (resolveInfo == null || resolveInfo.serviceInfo == null) return null;
838 return new ComponentName(resolveInfo.serviceInfo.packageName, resolveInfo.serviceInfo.name);
839 }
840
Adrian Roos3870d452014-09-05 18:22:28 +0200841 private void maybeEnableFactoryTrustAgents(LockPatternUtils utils, int userId) {
Adrian Roos2f19ad42017-07-05 16:09:22 +0200842 if (0 != Settings.Secure.getIntForUser(mContext.getContentResolver(),
843 Settings.Secure.TRUST_AGENTS_INITIALIZED, 0, userId)) {
844 return;
845 }
846 PackageManager pm = mContext.getPackageManager();
847 List<ResolveInfo> resolveInfos = resolveAllowedTrustAgents(pm, userId);
Zachary Iqbal666484d2017-03-31 19:10:09 -0700848 ComponentName defaultAgent = getDefaultFactoryTrustAgent(mContext);
849 boolean shouldUseDefaultAgent = defaultAgent != null;
Adrian Roos2f19ad42017-07-05 16:09:22 +0200850 ArraySet<ComponentName> discoveredAgents = new ArraySet<>();
Zachary Iqbal666484d2017-03-31 19:10:09 -0700851
852 if (shouldUseDefaultAgent) {
Adrian Roos2f19ad42017-07-05 16:09:22 +0200853 discoveredAgents.add(defaultAgent);
Zachary Iqbal666484d2017-03-31 19:10:09 -0700854 Log.i(TAG, "Enabling " + defaultAgent + " because it is a default agent.");
855 } else { // A default agent is not set; perform regular trust agent discovery
856 for (ResolveInfo resolveInfo : resolveInfos) {
857 ComponentName componentName = getComponentName(resolveInfo);
858 int applicationInfoFlags = resolveInfo.serviceInfo.applicationInfo.flags;
859 if ((applicationInfoFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
860 Log.i(TAG, "Leaving agent " + componentName + " disabled because package "
861 + "is not a system package.");
862 continue;
863 }
864 discoveredAgents.add(componentName);
Adrian Roos3870d452014-09-05 18:22:28 +0200865 }
Adrian Roos3870d452014-09-05 18:22:28 +0200866 }
Adrian Roos2f19ad42017-07-05 16:09:22 +0200867
868 List<ComponentName> previouslyEnabledAgents = utils.getEnabledTrustAgents(userId);
869 if (previouslyEnabledAgents != null) {
870 discoveredAgents.addAll(previouslyEnabledAgents);
871 }
872 utils.setEnabledTrustAgents(discoveredAgents, userId);
Adrian Roos3870d452014-09-05 18:22:28 +0200873 Settings.Secure.putIntForUser(mContext.getContentResolver(),
874 Settings.Secure.TRUST_AGENTS_INITIALIZED, 1, userId);
875 }
876
Zachary Iqbal666484d2017-03-31 19:10:09 -0700877 /**
878 * Returns the {@link ComponentName} for the default trust agent, or {@code null} if there
879 * is no trust agent set.
880 */
881 private static ComponentName getDefaultFactoryTrustAgent(Context context) {
882 String defaultTrustAgent = context.getResources()
883 .getString(com.android.internal.R.string.config_defaultTrustAgent);
884 if (TextUtils.isEmpty(defaultTrustAgent)) {
885 return null;
886 }
887 return ComponentName.unflattenFromString(defaultTrustAgent);
888 }
889
Adrian Roos3870d452014-09-05 18:22:28 +0200890 private List<ResolveInfo> resolveAllowedTrustAgents(PackageManager pm, int userId) {
891 List<ResolveInfo> resolveInfos = pm.queryIntentServicesAsUser(TRUST_AGENT_INTENT,
Lingjun Li20914d72016-11-14 15:39:13 -0800892 PackageManager.GET_META_DATA |
Adrian Roos68771eb2016-05-03 14:02:36 -0700893 PackageManager.MATCH_DIRECT_BOOT_AWARE | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
894 userId);
Adrian Roos3870d452014-09-05 18:22:28 +0200895 ArrayList<ResolveInfo> allowedAgents = new ArrayList<>(resolveInfos.size());
896 for (ResolveInfo resolveInfo : resolveInfos) {
897 if (resolveInfo.serviceInfo == null) continue;
898 if (resolveInfo.serviceInfo.applicationInfo == null) continue;
899 String packageName = resolveInfo.serviceInfo.packageName;
900 if (pm.checkPermission(PERMISSION_PROVIDE_AGENT, packageName)
901 != PackageManager.PERMISSION_GRANTED) {
902 ComponentName name = getComponentName(resolveInfo);
903 Log.w(TAG, "Skipping agent " + name + " because package does not have"
904 + " permission " + PERMISSION_PROVIDE_AGENT + ".");
905 continue;
906 }
907 allowedAgents.add(resolveInfo);
908 }
909 return allowedAgents;
910 }
911
Adrian Roos82142c22014-03-27 14:56:59 +0100912 // Agent dispatch and aggregation
913
914 private boolean aggregateIsTrusted(int userId) {
Adrian Roosb5e47222015-08-14 15:53:06 -0700915 if (!mStrongAuthTracker.isTrustAllowedForUser(userId)) {
Adrian Roos7046bfd2014-05-16 21:20:54 +0200916 return false;
917 }
Adrian Roos82142c22014-03-27 14:56:59 +0100918 for (int i = 0; i < mActiveAgents.size(); i++) {
919 AgentInfo info = mActiveAgents.valueAt(i);
920 if (info.userId == userId) {
921 if (info.agent.isTrusted()) {
922 return true;
923 }
924 }
925 }
926 return false;
927 }
928
Adrian Roos7861c662014-07-25 15:37:28 +0200929 private boolean aggregateIsTrustManaged(int userId) {
Adrian Roosb5e47222015-08-14 15:53:06 -0700930 if (!mStrongAuthTracker.isTrustAllowedForUser(userId)) {
Adrian Roos7861c662014-07-25 15:37:28 +0200931 return false;
932 }
933 for (int i = 0; i < mActiveAgents.size(); i++) {
934 AgentInfo info = mActiveAgents.valueAt(i);
935 if (info.userId == userId) {
936 if (info.agent.isManagingTrust()) {
937 return true;
938 }
939 }
940 }
941 return false;
942 }
943
Adrian Roos82142c22014-03-27 14:56:59 +0100944 private void dispatchUnlockAttempt(boolean successful, int userId) {
Adrian Roos517b3a42016-03-03 14:58:33 -0800945 if (successful) {
946 mStrongAuthTracker.allowTrustFromUnlock(userId);
Vishwath Mohan15f7dd02018-12-12 11:15:08 -0800947 // Allow the presence of trust on a successful unlock attempt to extend unlock.
948 updateTrust(userId, 0 /* flags */, true);
Adrian Roos517b3a42016-03-03 14:58:33 -0800949 }
950
Adrian Roos82142c22014-03-27 14:56:59 +0100951 for (int i = 0; i < mActiveAgents.size(); i++) {
952 AgentInfo info = mActiveAgents.valueAt(i);
953 if (info.userId == userId) {
954 info.agent.onUnlockAttempt(successful);
955 }
956 }
Adrian Roos2c12cfa2014-06-25 23:28:53 +0200957 }
958
Zachary Iqbal327323d2017-01-12 14:41:13 -0800959 private void dispatchUnlockLockout(int timeoutMs, int userId) {
960 for (int i = 0; i < mActiveAgents.size(); i++) {
961 AgentInfo info = mActiveAgents.valueAt(i);
962 if (info.userId == userId) {
963 info.agent.onUnlockLockout(timeoutMs);
964 }
965 }
966 }
967
Adrian Roos82142c22014-03-27 14:56:59 +0100968 // Listeners
969
970 private void addListener(ITrustListener listener) {
971 for (int i = 0; i < mTrustListeners.size(); i++) {
972 if (mTrustListeners.get(i).asBinder() == listener.asBinder()) {
973 return;
974 }
975 }
976 mTrustListeners.add(listener);
Adrian Roos3870d452014-09-05 18:22:28 +0200977 updateTrustAll();
Adrian Roos82142c22014-03-27 14:56:59 +0100978 }
979
980 private void removeListener(ITrustListener listener) {
981 for (int i = 0; i < mTrustListeners.size(); i++) {
982 if (mTrustListeners.get(i).asBinder() == listener.asBinder()) {
Jay Civelli979a32e2014-07-18 16:47:36 -0700983 mTrustListeners.remove(i);
Adrian Roos82142c22014-03-27 14:56:59 +0100984 return;
985 }
986 }
987 }
988
Adrian Roos94e15a52015-04-16 12:23:18 -0700989 private void dispatchOnTrustChanged(boolean enabled, int userId, int flags) {
Adrian Roos517b3a42016-03-03 14:58:33 -0800990 if (DEBUG) {
991 Log.i(TAG, "onTrustChanged(" + enabled + ", " + userId + ", 0x"
992 + Integer.toHexString(flags) + ")");
993 }
Adrian Roos94e15a52015-04-16 12:23:18 -0700994 if (!enabled) flags = 0;
Adrian Roos82142c22014-03-27 14:56:59 +0100995 for (int i = 0; i < mTrustListeners.size(); i++) {
996 try {
Adrian Roos94e15a52015-04-16 12:23:18 -0700997 mTrustListeners.get(i).onTrustChanged(enabled, userId, flags);
Adrian Roosa4ba56b2014-05-20 12:56:25 +0200998 } catch (DeadObjectException e) {
Adrian Roos7861c662014-07-25 15:37:28 +0200999 Slog.d(TAG, "Removing dead TrustListener.");
1000 mTrustListeners.remove(i);
1001 i--;
1002 } catch (RemoteException e) {
1003 Slog.e(TAG, "Exception while notifying TrustListener.", e);
1004 }
1005 }
1006 }
1007
1008 private void dispatchOnTrustManagedChanged(boolean managed, int userId) {
Adrian Roos517b3a42016-03-03 14:58:33 -08001009 if (DEBUG) {
1010 Log.i(TAG, "onTrustManagedChanged(" + managed + ", " + userId + ")");
1011 }
Adrian Roos7861c662014-07-25 15:37:28 +02001012 for (int i = 0; i < mTrustListeners.size(); i++) {
1013 try {
1014 mTrustListeners.get(i).onTrustManagedChanged(managed, userId);
1015 } catch (DeadObjectException e) {
1016 Slog.d(TAG, "Removing dead TrustListener.");
Adrian Roosa4ba56b2014-05-20 12:56:25 +02001017 mTrustListeners.remove(i);
1018 i--;
Adrian Roos82142c22014-03-27 14:56:59 +01001019 } catch (RemoteException e) {
Adrian Roosa4ba56b2014-05-20 12:56:25 +02001020 Slog.e(TAG, "Exception while notifying TrustListener.", e);
Adrian Roos82142c22014-03-27 14:56:59 +01001021 }
1022 }
1023 }
1024
Lucas Dupinef886542018-01-03 16:03:07 -08001025 private void dispatchOnTrustError(CharSequence message) {
1026 if (DEBUG) {
1027 Log.i(TAG, "onTrustError(" + message + ")");
1028 }
1029 for (int i = 0; i < mTrustListeners.size(); i++) {
1030 try {
1031 mTrustListeners.get(i).onTrustError(message);
1032 } catch (DeadObjectException e) {
1033 Slog.d(TAG, "Removing dead TrustListener.");
1034 mTrustListeners.remove(i);
1035 i--;
1036 } catch (RemoteException e) {
1037 Slog.e(TAG, "Exception while notifying TrustListener.", e);
1038 }
1039 }
1040 }
1041
Adrian Rooscbe614f2014-10-28 20:16:12 +01001042 // User lifecycle
1043
1044 @Override
1045 public void onStartUser(int userId) {
Adrian Roos481a6df2014-11-20 19:48:56 +01001046 mHandler.obtainMessage(MSG_START_USER, userId, 0, null).sendToTarget();
Adrian Rooscbe614f2014-10-28 20:16:12 +01001047 }
1048
1049 @Override
1050 public void onCleanupUser(int userId) {
Adrian Roos481a6df2014-11-20 19:48:56 +01001051 mHandler.obtainMessage(MSG_CLEANUP_USER, userId, 0, null).sendToTarget();
1052 }
1053
1054 @Override
1055 public void onSwitchUser(int userId) {
1056 mHandler.obtainMessage(MSG_SWITCH_USER, userId, 0, null).sendToTarget();
Adrian Rooscbe614f2014-10-28 20:16:12 +01001057 }
1058
Adrian Roos68771eb2016-05-03 14:02:36 -07001059 @Override
1060 public void onUnlockUser(int userId) {
1061 mHandler.obtainMessage(MSG_UNLOCK_USER, userId, 0, null).sendToTarget();
1062 }
1063
Andrew Scull85a63bc2016-10-24 13:47:47 +01001064 @Override
1065 public void onStopUser(@UserIdInt int userId) {
1066 mHandler.obtainMessage(MSG_STOP_USER, userId, 0, null).sendToTarget();
1067 }
1068
Adrian Roos82142c22014-03-27 14:56:59 +01001069 // Plumbing
1070
1071 private final IBinder mService = new ITrustManager.Stub() {
1072 @Override
1073 public void reportUnlockAttempt(boolean authenticated, int userId) throws RemoteException {
1074 enforceReportPermission();
1075 mHandler.obtainMessage(MSG_DISPATCH_UNLOCK_ATTEMPT, authenticated ? 1 : 0, userId)
1076 .sendToTarget();
1077 }
1078
1079 @Override
Zachary Iqbal327323d2017-01-12 14:41:13 -08001080 public void reportUnlockLockout(int timeoutMs, int userId) throws RemoteException {
1081 enforceReportPermission();
1082 mHandler.obtainMessage(MSG_DISPATCH_UNLOCK_LOCKOUT, timeoutMs, userId)
1083 .sendToTarget();
1084 }
1085
1086 @Override
Adrian Roos82142c22014-03-27 14:56:59 +01001087 public void reportEnabledTrustAgentsChanged(int userId) throws RemoteException {
1088 enforceReportPermission();
1089 // coalesce refresh messages.
1090 mHandler.removeMessages(MSG_ENABLED_AGENTS_CHANGED);
1091 mHandler.sendEmptyMessage(MSG_ENABLED_AGENTS_CHANGED);
1092 }
1093
1094 @Override
Adrian Roos481a6df2014-11-20 19:48:56 +01001095 public void reportKeyguardShowingChanged() throws RemoteException {
1096 enforceReportPermission();
1097 // coalesce refresh messages.
1098 mHandler.removeMessages(MSG_KEYGUARD_SHOWING_CHANGED);
1099 mHandler.sendEmptyMessage(MSG_KEYGUARD_SHOWING_CHANGED);
Jorim Jaggi5277dea2017-05-18 02:05:29 +02001100
1101 // Make sure handler processes the message before returning, such that isDeviceLocked
1102 // after this call will retrieve the correct value.
1103 mHandler.runWithScissors(() -> {}, 0);
Adrian Roos481a6df2014-11-20 19:48:56 +01001104 }
1105
1106 @Override
Adrian Roos82142c22014-03-27 14:56:59 +01001107 public void registerTrustListener(ITrustListener trustListener) throws RemoteException {
1108 enforceListenerPermission();
1109 mHandler.obtainMessage(MSG_REGISTER_LISTENER, trustListener).sendToTarget();
1110 }
1111
1112 @Override
1113 public void unregisterTrustListener(ITrustListener trustListener) throws RemoteException {
1114 enforceListenerPermission();
1115 mHandler.obtainMessage(MSG_UNREGISTER_LISTENER, trustListener).sendToTarget();
1116 }
1117
Adrian Roosbcd07652014-10-22 16:57:16 +02001118 @Override
Adrian Roos50bfeec2014-11-20 16:21:11 +01001119 public boolean isDeviceLocked(int userId) throws RemoteException {
Adrian Roosbcd07652014-10-22 16:57:16 +02001120 userId = ActivityManager.handleIncomingUser(getCallingPid(), getCallingUid(), userId,
Adrian Roos50bfeec2014-11-20 16:21:11 +01001121 false /* allowAll */, true /* requireFull */, "isDeviceLocked", null);
Adrian Roos50bfeec2014-11-20 16:21:11 +01001122
Clara Bayarri078e91b2016-01-15 16:57:35 +00001123 long token = Binder.clearCallingIdentity();
1124 try {
1125 if (!mLockPatternUtils.isSeparateProfileChallengeEnabled(userId)) {
1126 userId = resolveProfileParent(userId);
1127 }
1128 return isDeviceLockedInner(userId);
1129 } finally {
1130 Binder.restoreCallingIdentity(token);
1131 }
Adrian Roosbcd07652014-10-22 16:57:16 +02001132 }
1133
Adrian Roos82893682015-04-02 16:17:46 +02001134 @Override
1135 public boolean isDeviceSecure(int userId) throws RemoteException {
1136 userId = ActivityManager.handleIncomingUser(getCallingPid(), getCallingUid(), userId,
1137 false /* allowAll */, true /* requireFull */, "isDeviceSecure", null);
Adrian Roos82893682015-04-02 16:17:46 +02001138
1139 long token = Binder.clearCallingIdentity();
1140 try {
Clara Bayarri8d35de82016-01-12 17:29:29 +00001141 if (!mLockPatternUtils.isSeparateProfileChallengeEnabled(userId)) {
1142 userId = resolveProfileParent(userId);
1143 }
Clara Bayarria1771112015-12-18 16:29:18 +00001144 return mLockPatternUtils.isSecure(userId);
Adrian Roos82893682015-04-02 16:17:46 +02001145 } finally {
1146 Binder.restoreCallingIdentity(token);
1147 }
1148 }
1149
Adrian Roos82142c22014-03-27 14:56:59 +01001150 private void enforceReportPermission() {
Adrian Roos2c12cfa2014-06-25 23:28:53 +02001151 mContext.enforceCallingOrSelfPermission(
1152 Manifest.permission.ACCESS_KEYGUARD_SECURE_STORAGE, "reporting trust events");
Adrian Roos82142c22014-03-27 14:56:59 +01001153 }
1154
1155 private void enforceListenerPermission() {
1156 mContext.enforceCallingPermission(Manifest.permission.TRUST_LISTENER,
1157 "register trust listener");
1158 }
Adrian Roos7a4f3d42014-05-02 12:12:20 +02001159
1160 @Override
1161 protected void dump(FileDescriptor fd, final PrintWriter fout, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06001162 if (!DumpUtils.checkDumpPermission(mContext, TAG, fout)) return;
Adrian Roos49d53452014-10-24 15:48:39 +02001163 if (isSafeMode()) {
1164 fout.println("disabled because the system is in safe mode.");
1165 return;
1166 }
Adrian Rooscbe614f2014-10-28 20:16:12 +01001167 if (!mTrustAgentsCanRun) {
1168 fout.println("disabled because the third-party apps can't run yet.");
1169 return;
1170 }
Adrian Roos7a4f3d42014-05-02 12:12:20 +02001171 final List<UserInfo> userInfos = mUserManager.getUsers(true /* excludeDying */);
Adrian Roos7a4f3d42014-05-02 12:12:20 +02001172 mHandler.runWithScissors(new Runnable() {
1173 @Override
1174 public void run() {
1175 fout.println("Trust manager state:");
1176 for (UserInfo user : userInfos) {
Adrian Roos481a6df2014-11-20 19:48:56 +01001177 dumpUser(fout, user, user.id == mCurrentUser);
Adrian Roos7a4f3d42014-05-02 12:12:20 +02001178 }
1179 }
1180 }, 1500);
1181 }
1182
1183 private void dumpUser(PrintWriter fout, UserInfo user, boolean isCurrent) {
1184 fout.printf(" User \"%s\" (id=%d, flags=%#x)",
1185 user.name, user.id, user.flags);
Xiaohui Chen7cb69df2015-07-13 16:01:01 -07001186 if (!user.supportsSwitchToByUser()) {
Adrian Roos481a6df2014-11-20 19:48:56 +01001187 fout.println("(managed profile)");
1188 fout.println(" disabled because switching to this user is not possible.");
1189 return;
1190 }
Adrian Roos7a4f3d42014-05-02 12:12:20 +02001191 if (isCurrent) {
1192 fout.print(" (current)");
1193 }
1194 fout.print(": trusted=" + dumpBool(aggregateIsTrusted(user.id)));
Adrian Roos7861c662014-07-25 15:37:28 +02001195 fout.print(", trustManaged=" + dumpBool(aggregateIsTrustManaged(user.id)));
Adrian Roos481a6df2014-11-20 19:48:56 +01001196 fout.print(", deviceLocked=" + dumpBool(isDeviceLockedInner(user.id)));
Adrian Roosb5e47222015-08-14 15:53:06 -07001197 fout.print(", strongAuthRequired=" + dumpHex(
1198 mStrongAuthTracker.getStrongAuthForUser(user.id)));
Adrian Roos7a4f3d42014-05-02 12:12:20 +02001199 fout.println();
1200 fout.println(" Enabled agents:");
1201 boolean duplicateSimpleNames = false;
1202 ArraySet<String> simpleNames = new ArraySet<String>();
1203 for (AgentInfo info : mActiveAgents) {
1204 if (info.userId != user.id) { continue; }
1205 boolean trusted = info.agent.isTrusted();
1206 fout.print(" "); fout.println(info.component.flattenToShortString());
Adrian Roosc5f95ce2014-07-24 16:00:46 +02001207 fout.print(" bound=" + dumpBool(info.agent.isBound()));
1208 fout.print(", connected=" + dumpBool(info.agent.isConnected()));
Adrian Roos7861c662014-07-25 15:37:28 +02001209 fout.print(", managingTrust=" + dumpBool(info.agent.isManagingTrust()));
1210 fout.print(", trusted=" + dumpBool(trusted));
1211 fout.println();
Adrian Roos7a4f3d42014-05-02 12:12:20 +02001212 if (trusted) {
1213 fout.println(" message=\"" + info.agent.getMessage() + "\"");
1214 }
Adrian Roosc5f95ce2014-07-24 16:00:46 +02001215 if (!info.agent.isConnected()) {
1216 String restartTime = TrustArchive.formatDuration(
1217 info.agent.getScheduledRestartUptimeMillis()
1218 - SystemClock.uptimeMillis());
1219 fout.println(" restartScheduledAt=" + restartTime);
1220 }
Adrian Roos7a4f3d42014-05-02 12:12:20 +02001221 if (!simpleNames.add(TrustArchive.getSimpleName(info.component))) {
1222 duplicateSimpleNames = true;
1223 }
1224 }
1225 fout.println(" Events:");
1226 mArchive.dump(fout, 50, user.id, " " /* linePrefix */, duplicateSimpleNames);
1227 fout.println();
1228 }
1229
1230 private String dumpBool(boolean b) {
1231 return b ? "1" : "0";
1232 }
Adrian Roosb5e47222015-08-14 15:53:06 -07001233
1234 private String dumpHex(int i) {
1235 return "0x" + Integer.toHexString(i);
1236 }
Clara Bayarri56878a92015-10-29 15:43:55 +00001237
Rubin Xuc3986272019-11-05 10:15:36 +00001238 /**
1239 * Changes the lock status for the given user. This is only applicable to managed profiles,
1240 * other users should be handled by Keyguard.
1241 */
Clara Bayarri56878a92015-10-29 15:43:55 +00001242 @Override
Rubin Xu83a15bc2016-08-10 10:53:24 +01001243 public void setDeviceLockedForUser(int userId, boolean locked) {
Clara Bayarri00a9b892016-01-13 16:17:09 +00001244 enforceReportPermission();
Rubin Xue0781332016-08-19 11:20:34 +01001245 final long identity = Binder.clearCallingIdentity();
1246 try {
Pavel Grafov259ca362018-07-27 14:04:57 +01001247 if (mLockPatternUtils.isSeparateProfileChallengeEnabled(userId)
1248 && mLockPatternUtils.isSecure(userId)) {
Rubin Xue0781332016-08-19 11:20:34 +01001249 synchronized (mDeviceLockedForUser) {
1250 mDeviceLockedForUser.put(userId, locked);
1251 }
Rubin Xuc3986272019-11-05 10:15:36 +00001252
1253 KeyStore.getInstance().onUserLockedStateChanged(userId, locked);
1254
Rubin Xue0781332016-08-19 11:20:34 +01001255 if (locked) {
1256 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001257 ActivityManager.getService().notifyLockedProfile(userId);
Rubin Xue0781332016-08-19 11:20:34 +01001258 } catch (RemoteException e) {
1259 }
Rubin Xu83a15bc2016-08-10 10:53:24 +01001260 }
Robin Lee92b83c62016-08-31 13:27:51 +01001261 final Intent lockIntent = new Intent(Intent.ACTION_DEVICE_LOCKED_CHANGED);
1262 lockIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1263 lockIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
1264 mContext.sendBroadcastAsUser(lockIntent, UserHandle.SYSTEM,
1265 Manifest.permission.TRUST_LISTENER, /* options */ null);
Rubin Xu83a15bc2016-08-10 10:53:24 +01001266 }
Rubin Xue0781332016-08-19 11:20:34 +01001267 } finally {
1268 Binder.restoreCallingIdentity(identity);
Rubin Xu83a15bc2016-08-10 10:53:24 +01001269 }
Clara Bayarri56878a92015-10-29 15:43:55 +00001270 }
Adrian Roosc13723f2016-01-12 20:29:03 +01001271
1272 @Override
1273 public boolean isTrustUsuallyManaged(int userId) {
1274 mContext.enforceCallingPermission(Manifest.permission.TRUST_LISTENER,
1275 "query trust state");
1276 return isTrustUsuallyManagedInternal(userId);
1277 }
Kevin Chyn3fdbbf82017-05-06 15:11:53 -07001278
1279 @Override
Gilad Brettercb51b8b2018-03-22 17:04:51 +02001280 public void unlockedByBiometricForUser(int userId, BiometricSourceType biometricSource) {
Kevin Chyn3fdbbf82017-05-06 15:11:53 -07001281 enforceReportPermission();
Gilad Brettercb51b8b2018-03-22 17:04:51 +02001282 synchronized(mUsersUnlockedByBiometric) {
1283 mUsersUnlockedByBiometric.put(userId, true);
Kevin Chyn3fdbbf82017-05-06 15:11:53 -07001284 }
Vishwath Mohan15f7dd02018-12-12 11:15:08 -08001285 // In extend unlock mode we need to refresh trust state here, which will call
1286 // refreshDeviceLockedForUser()
1287 int updateTrustOnUnlock = mSettingsObserver.getTrustAgentsExtendUnlock() ? 1 : 0;
Kevin Chyn3fdbbf82017-05-06 15:11:53 -07001288 mHandler.obtainMessage(MSG_REFRESH_DEVICE_LOCKED_FOR_USER, userId,
Vishwath Mohan15f7dd02018-12-12 11:15:08 -08001289 updateTrustOnUnlock).sendToTarget();
Kevin Chyn3fdbbf82017-05-06 15:11:53 -07001290 }
1291
1292 @Override
Gilad Brettercb51b8b2018-03-22 17:04:51 +02001293 public void clearAllBiometricRecognized(BiometricSourceType biometricSource) {
Kevin Chyn3fdbbf82017-05-06 15:11:53 -07001294 enforceReportPermission();
Gilad Brettercb51b8b2018-03-22 17:04:51 +02001295 synchronized(mUsersUnlockedByBiometric) {
1296 mUsersUnlockedByBiometric.clear();
Kevin Chyn3fdbbf82017-05-06 15:11:53 -07001297 }
1298 mHandler.obtainMessage(MSG_REFRESH_DEVICE_LOCKED_FOR_USER, UserHandle.USER_ALL,
1299 0 /* arg2 */).sendToTarget();
1300 }
Adrian Roos82142c22014-03-27 14:56:59 +01001301 };
1302
Adrian Roosc13723f2016-01-12 20:29:03 +01001303 private boolean isTrustUsuallyManagedInternal(int userId) {
1304 synchronized (mTrustUsuallyManagedForUser) {
1305 int i = mTrustUsuallyManagedForUser.indexOfKey(userId);
1306 if (i >= 0) {
1307 return mTrustUsuallyManagedForUser.valueAt(i);
1308 }
1309 }
1310 // It's not in memory yet, get the value from persisted storage instead
1311 boolean persistedValue = mLockPatternUtils.isTrustUsuallyManaged(userId);
1312 synchronized (mTrustUsuallyManagedForUser) {
1313 int i = mTrustUsuallyManagedForUser.indexOfKey(userId);
1314 if (i >= 0) {
1315 // Someone set the trust usually managed in the mean time. Better use that.
1316 return mTrustUsuallyManagedForUser.valueAt(i);
1317 } else {
1318 // .. otherwise it's safe to cache the fetched value now.
1319 mTrustUsuallyManagedForUser.put(userId, persistedValue);
1320 return persistedValue;
1321 }
1322 }
1323 }
1324
Adrian Roosbcd07652014-10-22 16:57:16 +02001325 private int resolveProfileParent(int userId) {
1326 long identity = Binder.clearCallingIdentity();
1327 try {
1328 UserInfo parent = mUserManager.getProfileParent(userId);
1329 if (parent != null) {
1330 return parent.getUserHandle().getIdentifier();
1331 }
1332 return userId;
1333 } finally {
1334 Binder.restoreCallingIdentity(identity);
1335 }
1336 }
1337
Adrian Roos82142c22014-03-27 14:56:59 +01001338 private final Handler mHandler = new Handler() {
1339 @Override
1340 public void handleMessage(Message msg) {
1341 switch (msg.what) {
1342 case MSG_REGISTER_LISTENER:
1343 addListener((ITrustListener) msg.obj);
1344 break;
1345 case MSG_UNREGISTER_LISTENER:
1346 removeListener((ITrustListener) msg.obj);
1347 break;
1348 case MSG_DISPATCH_UNLOCK_ATTEMPT:
1349 dispatchUnlockAttempt(msg.arg1 != 0, msg.arg2);
1350 break;
Zachary Iqbal327323d2017-01-12 14:41:13 -08001351 case MSG_DISPATCH_UNLOCK_LOCKOUT:
1352 dispatchUnlockLockout(msg.arg1, msg.arg2);
1353 break;
Adrian Roos82142c22014-03-27 14:56:59 +01001354 case MSG_ENABLED_AGENTS_CHANGED:
Marco Fucci4e68f112014-08-29 12:31:48 -07001355 refreshAgentList(UserHandle.USER_ALL);
Adrian Roos481a6df2014-11-20 19:48:56 +01001356 // This is also called when the security mode of a user changes.
1357 refreshDeviceLockedForUser(UserHandle.USER_ALL);
Adrian Roos82142c22014-03-27 14:56:59 +01001358 break;
Adrian Roos481a6df2014-11-20 19:48:56 +01001359 case MSG_KEYGUARD_SHOWING_CHANGED:
Adrian Roos7e2e40e2014-11-21 15:27:12 +01001360 refreshDeviceLockedForUser(mCurrentUser);
Adrian Roos481a6df2014-11-20 19:48:56 +01001361 break;
1362 case MSG_START_USER:
1363 case MSG_CLEANUP_USER:
Adrian Roos68771eb2016-05-03 14:02:36 -07001364 case MSG_UNLOCK_USER:
Adrian Roos481a6df2014-11-20 19:48:56 +01001365 refreshAgentList(msg.arg1);
1366 break;
1367 case MSG_SWITCH_USER:
1368 mCurrentUser = msg.arg1;
Vishwath Mohan15f7dd02018-12-12 11:15:08 -08001369 mSettingsObserver.updateContentObserver();
Adrian Roos481a6df2014-11-20 19:48:56 +01001370 refreshDeviceLockedForUser(UserHandle.USER_ALL);
1371 break;
Andrew Scull85a63bc2016-10-24 13:47:47 +01001372 case MSG_STOP_USER:
1373 setDeviceLockedForUser(msg.arg1, true);
1374 break;
Adrian Roosc13723f2016-01-12 20:29:03 +01001375 case MSG_FLUSH_TRUST_USUALLY_MANAGED:
1376 SparseBooleanArray usuallyManaged;
1377 synchronized (mTrustUsuallyManagedForUser) {
1378 usuallyManaged = mTrustUsuallyManagedForUser.clone();
1379 }
1380
1381 for (int i = 0; i < usuallyManaged.size(); i++) {
1382 int userId = usuallyManaged.keyAt(i);
1383 boolean value = usuallyManaged.valueAt(i);
1384 if (value != mLockPatternUtils.isTrustUsuallyManaged(userId)) {
1385 mLockPatternUtils.setTrustUsuallyManaged(value, userId);
1386 }
1387 }
Adrian Roos68771eb2016-05-03 14:02:36 -07001388 break;
Kevin Chyn3fdbbf82017-05-06 15:11:53 -07001389 case MSG_REFRESH_DEVICE_LOCKED_FOR_USER:
Vishwath Mohan15f7dd02018-12-12 11:15:08 -08001390 if (msg.arg2 == 1) {
1391 updateTrust(msg.arg1, 0 /* flags */, true);
1392 }
Kevin Chyn3fdbbf82017-05-06 15:11:53 -07001393 refreshDeviceLockedForUser(msg.arg1);
1394 break;
Vishwath Mohan15f7dd02018-12-12 11:15:08 -08001395 case MSG_SCHEDULE_TRUST_TIMEOUT:
1396 handleScheduleTrustTimeout(msg.arg1, msg.arg2);
1397 break;
Adrian Roos82142c22014-03-27 14:56:59 +01001398 }
1399 }
1400 };
1401
1402 private final PackageMonitor mPackageMonitor = new PackageMonitor() {
1403 @Override
1404 public void onSomePackagesChanged() {
Marco Fucci4e68f112014-08-29 12:31:48 -07001405 refreshAgentList(UserHandle.USER_ALL);
Adrian Roos82142c22014-03-27 14:56:59 +01001406 }
1407
1408 @Override
1409 public boolean onPackageChanged(String packageName, int uid, String[] components) {
1410 // We're interested in all changes, even if just some components get enabled / disabled.
1411 return true;
1412 }
Adrian Roosc5f95ce2014-07-24 16:00:46 +02001413
1414 @Override
1415 public void onPackageDisappeared(String packageName, int reason) {
1416 removeAgentsOfPackage(packageName);
1417 }
Adrian Roos82142c22014-03-27 14:56:59 +01001418 };
Adrian Roosca36b952014-05-16 18:52:29 +02001419
Lingjun Li20914d72016-11-14 15:39:13 -08001420 private static class SettingsAttrs {
1421 public ComponentName componentName;
1422 public boolean canUnlockProfile;
1423
1424 public SettingsAttrs(
1425 ComponentName componentName,
1426 boolean canUnlockProfile) {
1427 this.componentName = componentName;
1428 this.canUnlockProfile = canUnlockProfile;
1429 }
1430 };
1431
Adrian Roos9dbe1902014-08-13 18:25:52 +02001432 private class Receiver extends BroadcastReceiver {
Adrian Roosca36b952014-05-16 18:52:29 +02001433
1434 @Override
1435 public void onReceive(Context context, Intent intent) {
Adrian Roos3870d452014-09-05 18:22:28 +02001436 String action = intent.getAction();
1437 if (DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED.equals(action)) {
Marco Fucci4e68f112014-08-29 12:31:48 -07001438 refreshAgentList(getSendingUserId());
1439 updateDevicePolicyFeatures();
Adrian Roos3870d452014-09-05 18:22:28 +02001440 } else if (Intent.ACTION_USER_ADDED.equals(action)) {
Adrian Rooscbe614f2014-10-28 20:16:12 +01001441 int userId = getUserId(intent);
Adrian Roos3870d452014-09-05 18:22:28 +02001442 if (userId > 0) {
1443 maybeEnableFactoryTrustAgents(mLockPatternUtils, userId);
Adrian Roos3870d452014-09-05 18:22:28 +02001444 }
Adrian Rooscbe614f2014-10-28 20:16:12 +01001445 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
1446 int userId = getUserId(intent);
1447 if (userId > 0) {
Adrian Roos481a6df2014-11-20 19:48:56 +01001448 synchronized (mUserIsTrusted) {
1449 mUserIsTrusted.delete(userId);
1450 }
1451 synchronized (mDeviceLockedForUser) {
1452 mDeviceLockedForUser.delete(userId);
1453 }
Adrian Roosae025822016-11-03 14:46:13 -07001454 synchronized (mTrustUsuallyManagedForUser) {
1455 mTrustUsuallyManagedForUser.delete(userId);
1456 }
Gilad Brettercb51b8b2018-03-22 17:04:51 +02001457 synchronized (mUsersUnlockedByBiometric) {
1458 mUsersUnlockedByBiometric.delete(userId);
Kevin Chyn3fdbbf82017-05-06 15:11:53 -07001459 }
Adrian Rooscbe614f2014-10-28 20:16:12 +01001460 refreshAgentList(userId);
Adrian Roos481a6df2014-11-20 19:48:56 +01001461 refreshDeviceLockedForUser(userId);
Adrian Rooscbe614f2014-10-28 20:16:12 +01001462 }
1463 }
1464 }
1465
1466 private int getUserId(Intent intent) {
1467 int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -100);
1468 if (userId > 0) {
1469 return userId;
1470 } else {
1471 Slog.wtf(TAG, "EXTRA_USER_HANDLE missing or invalid, value=" + userId);
1472 return -100;
Adrian Roosca36b952014-05-16 18:52:29 +02001473 }
1474 }
1475
1476 public void register(Context context) {
Adrian Roos9dbe1902014-08-13 18:25:52 +02001477 IntentFilter filter = new IntentFilter();
1478 filter.addAction(DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED);
Adrian Roos3870d452014-09-05 18:22:28 +02001479 filter.addAction(Intent.ACTION_USER_ADDED);
Adrian Rooscbe614f2014-10-28 20:16:12 +01001480 filter.addAction(Intent.ACTION_USER_REMOVED);
Adrian Roosca36b952014-05-16 18:52:29 +02001481 context.registerReceiverAsUser(this,
1482 UserHandle.ALL,
Adrian Roos9dbe1902014-08-13 18:25:52 +02001483 filter,
Adrian Roosca36b952014-05-16 18:52:29 +02001484 null /* permission */,
1485 null /* scheduler */);
1486 }
1487 }
Adrian Roos517b3a42016-03-03 14:58:33 -08001488
1489 private class StrongAuthTracker extends LockPatternUtils.StrongAuthTracker {
1490
1491 SparseBooleanArray mStartFromSuccessfulUnlock = new SparseBooleanArray();
1492
1493 public StrongAuthTracker(Context context) {
1494 super(context);
1495 }
1496
1497 @Override
1498 public void onStrongAuthRequiredChanged(int userId) {
1499 mStartFromSuccessfulUnlock.delete(userId);
1500
1501 if (DEBUG) {
1502 Log.i(TAG, "onStrongAuthRequiredChanged(" + userId + ") ->"
1503 + " trustAllowed=" + isTrustAllowedForUser(userId)
1504 + " agentsCanRun=" + canAgentsRunForUser(userId));
1505 }
1506
Vishwath Mohan15f7dd02018-12-12 11:15:08 -08001507 // Cancel pending alarms if we require some auth anyway.
1508 if (!isTrustAllowedForUser(userId)) {
1509 TrustTimeoutAlarmListener alarm = mTrustTimeoutAlarmListenerForUser.get(userId);
1510 if (alarm != null && alarm.isQueued()) {
1511 alarm.setQueued(false /* isQueued */);
1512 mAlarmManager.cancel(alarm);
1513 }
1514 }
1515
Adrian Roos517b3a42016-03-03 14:58:33 -08001516 refreshAgentList(userId);
1517
1518 // The list of active trust agents may not have changed, if there was a previous call
1519 // to allowTrustFromUnlock, so we update the trust here too.
1520 updateTrust(userId, 0 /* flags */);
1521 }
1522
1523 boolean canAgentsRunForUser(int userId) {
1524 return mStartFromSuccessfulUnlock.get(userId)
1525 || super.isTrustAllowedForUser(userId);
1526 }
1527
1528 /**
1529 * Temporarily suppress strong auth requirements for {@param userId} until strong auth
1530 * changes again. Must only be called when we know about a successful unlock already
1531 * before the underlying StrongAuthTracker.
1532 *
1533 * Note that this only changes whether trust agents can be started, not the actual trusted
1534 * value.
1535 */
1536 void allowTrustFromUnlock(int userId) {
1537 if (userId < UserHandle.USER_SYSTEM) {
1538 throw new IllegalArgumentException("userId must be a valid user: " + userId);
1539 }
1540 boolean previous = canAgentsRunForUser(userId);
1541 mStartFromSuccessfulUnlock.put(userId, true);
1542
1543 if (DEBUG) {
1544 Log.i(TAG, "allowTrustFromUnlock(" + userId + ") ->"
1545 + " trustAllowed=" + isTrustAllowedForUser(userId)
1546 + " agentsCanRun=" + canAgentsRunForUser(userId));
1547 }
1548
1549 if (canAgentsRunForUser(userId) != previous) {
1550 refreshAgentList(userId);
1551 }
1552 }
1553 }
Vishwath Mohan15f7dd02018-12-12 11:15:08 -08001554
1555 private class TrustTimeoutAlarmListener implements OnAlarmListener {
1556 private final int mUserId;
1557 private boolean mIsQueued = false;
1558
1559 TrustTimeoutAlarmListener(int userId) {
1560 mUserId = userId;
1561 }
1562
1563 @Override
1564 public void onAlarm() {
1565 mIsQueued = false;
1566 int strongAuthState = mStrongAuthTracker.getStrongAuthForUser(mUserId);
1567
1568 // Only fire if trust can unlock.
1569 if (mStrongAuthTracker.isTrustAllowedForUser(mUserId)) {
1570 if (DEBUG) Slog.d(TAG, "Revoking all trust because of trust timeout");
1571 mLockPatternUtils.requireStrongAuth(
1572 mStrongAuthTracker.SOME_AUTH_REQUIRED_AFTER_USER_REQUEST, mUserId);
1573 }
1574 maybeLockScreen(mUserId);
1575 }
1576
1577 public void setQueued(boolean isQueued) {
1578 mIsQueued = isQueued;
1579 }
1580
1581 public boolean isQueued() {
1582 return mIsQueued;
1583 }
1584 }
Adrian Roos82142c22014-03-27 14:56:59 +01001585}