blob: 1a8de977145129e27b882d97585b68ed63078fc4 [file] [log] [blame]
Amith Yamasani52c489c2012-03-28 11:42:42 -07001/*
2 * Copyright (C) 2012 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
Andrew Scull507d11c2017-05-03 17:19:01 +010017package com.android.server.locksettings;
Amith Yamasani52c489c2012-03-28 11:42:42 -070018
Rubin Xu1de89b32016-11-30 20:03:13 +000019import static android.Manifest.permission.ACCESS_KEYGUARD_SECURE_STORAGE;
Haining Chenc06c4812020-01-13 20:38:53 -080020import static android.Manifest.permission.MANAGE_BIOMETRIC;
Rubin Xu1de89b32016-11-30 20:03:13 +000021import static android.Manifest.permission.READ_CONTACTS;
22import static android.content.Context.KEYGUARD_SERVICE;
Adrian Roosb953e182017-08-17 17:58:26 +020023import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Kenny Rootf76cfc32019-11-08 14:36:03 -080024import static android.os.UserHandle.USER_ALL;
Adrian Roos7374d3a2017-03-31 14:14:53 -070025
Pavel Grafov19a4fb32019-03-15 12:55:12 +000026import static com.android.internal.widget.LockPatternUtils.CREDENTIAL_TYPE_NONE;
27import static com.android.internal.widget.LockPatternUtils.CREDENTIAL_TYPE_PASSWORD;
Rubin Xu5e891bc2019-10-14 10:22:23 +010028import static com.android.internal.widget.LockPatternUtils.CREDENTIAL_TYPE_PASSWORD_OR_PIN;
Pavel Grafov19a4fb32019-03-15 12:55:12 +000029import static com.android.internal.widget.LockPatternUtils.CREDENTIAL_TYPE_PATTERN;
Rubin Xu5e891bc2019-10-14 10:22:23 +010030import static com.android.internal.widget.LockPatternUtils.CREDENTIAL_TYPE_PIN;
Ram Periathiruvadi32d53552019-02-19 13:25:46 -080031import static com.android.internal.widget.LockPatternUtils.EscrowTokenStateChangeCallback;
Rubin Xu3bf722a2016-12-15 16:07:38 +000032import static com.android.internal.widget.LockPatternUtils.SYNTHETIC_PASSWORD_HANDLE_KEY;
Bo Zhuc7048342019-01-03 14:04:58 -080033import static com.android.internal.widget.LockPatternUtils.StrongAuthTracker.STRONG_AUTH_REQUIRED_AFTER_LOCKOUT;
Kenny Rootf76cfc32019-11-08 14:36:03 -080034import static com.android.internal.widget.LockPatternUtils.StrongAuthTracker.STRONG_AUTH_REQUIRED_FOR_UNATTENDED_UPDATE;
Adrian Roos7374d3a2017-03-31 14:14:53 -070035import static com.android.internal.widget.LockPatternUtils.USER_FRP;
36import static com.android.internal.widget.LockPatternUtils.frpCredentialEnabled;
Adrian Roos454f53f2017-08-08 14:56:42 +020037import static com.android.internal.widget.LockPatternUtils.userOwnsFrpCredential;
Rubin Xu1de89b32016-11-30 20:03:13 +000038
Kevin Chynbc29dd72019-06-13 11:47:54 -070039import android.annotation.IntDef;
Dmitry Dementyev1aa96132017-12-11 11:33:12 -080040import android.annotation.NonNull;
41import android.annotation.Nullable;
Andrew Scull5daf2732016-11-14 15:02:45 +000042import android.annotation.UserIdInt;
Sudheer Shankadc589ac2016-11-10 15:30:17 -080043import android.app.ActivityManager;
Rubin Xu0cbc19e2016-12-09 14:00:21 +000044import android.app.IActivityManager;
Kenny Guyb1b30262016-02-09 16:02:35 +000045import android.app.KeyguardManager;
Jim Miller4f93c582016-01-27 19:05:43 -080046import android.app.Notification;
47import android.app.NotificationManager;
48import android.app.PendingIntent;
Adrian Roos230635e2015-01-07 20:50:29 +010049import android.app.admin.DevicePolicyManager;
Pavel Grafov28939982017-10-03 15:11:52 +010050import android.app.admin.DevicePolicyManagerInternal;
Rubin Xu0f1e56d2019-08-23 13:34:25 +010051import android.app.admin.DeviceStateCache;
Andrew Scull5daf2732016-11-14 15:02:45 +000052import android.app.admin.PasswordMetrics;
Adrian Roosb5e47222015-08-14 15:53:06 -070053import android.app.trust.IStrongAuthTracker;
Clara Bayarri56878a92015-10-29 15:43:55 +000054import android.app.trust.TrustManager;
Robin Leef0246a82014-08-13 09:50:25 +010055import android.content.BroadcastReceiver;
Amith Yamasani52c489c2012-03-28 11:42:42 -070056import android.content.ContentResolver;
Amith Yamasani52c489c2012-03-28 11:42:42 -070057import android.content.Context;
Robin Leef0246a82014-08-13 09:50:25 +010058import android.content.Intent;
59import android.content.IntentFilter;
Jim Miller158fe192013-04-17 15:23:55 -070060import android.content.pm.PackageManager;
Jim Miller187ec582013-04-15 18:27:54 -070061import android.content.pm.UserInfo;
Jim Miller4f93c582016-01-27 19:05:43 -080062import android.content.res.Resources;
Adrian Roos7374d3a2017-03-31 14:14:53 -070063import android.database.ContentObserver;
Amith Yamasani52c489c2012-03-28 11:42:42 -070064import android.database.sqlite.SQLiteDatabase;
Andrew Sculle6527c12018-01-05 18:33:58 +000065import android.hardware.authsecret.V1_0.IAuthSecret;
Kevin Chyna38653c2019-02-11 17:46:21 -080066import android.hardware.biometrics.BiometricManager;
Alex Johnston6183cf92019-10-03 15:59:03 +010067import android.hardware.face.Face;
Kevin Chyna38653c2019-02-11 17:46:21 -080068import android.hardware.face.FaceManager;
Alex Johnston6183cf92019-10-03 15:59:03 +010069import android.hardware.fingerprint.Fingerprint;
70import android.hardware.fingerprint.FingerprintManager;
Adrian Roos7374d3a2017-03-31 14:14:53 -070071import android.net.Uri;
Amith Yamasani52c489c2012-03-28 11:42:42 -070072import android.os.Binder;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -060073import android.os.Bundle;
Ricky Waib0cdf382016-05-16 17:28:04 +010074import android.os.Handler;
Paul Lawrence945490c2014-03-27 16:37:28 +000075import android.os.IBinder;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -060076import android.os.IProgressListener;
Ricky Wai4613fe42016-05-24 11:11:42 +010077import android.os.Process;
Amith Yamasani52c489c2012-03-28 11:42:42 -070078import android.os.RemoteException;
Jorim Jaggi2fef6f72016-11-01 19:06:25 -070079import android.os.ResultReceiver;
Paul Lawrence945490c2014-03-27 16:37:28 +000080import android.os.ServiceManager;
Rubin Xu1de89b32016-11-30 20:03:13 +000081import android.os.ShellCallback;
Jeff Sharkeyeddf5182016-08-09 16:36:08 -060082import android.os.StrictMode;
Amith Yamasanid1645f82012-06-12 11:53:26 -070083import android.os.SystemProperties;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070084import android.os.UserHandle;
Jim Miller187ec582013-04-15 18:27:54 -070085import android.os.UserManager;
Rubin Xu0f1e56d2019-08-23 13:34:25 +010086import android.os.UserManagerInternal;
Rubin Xu1de89b32016-11-30 20:03:13 +000087import android.os.storage.IStorageManager;
88import android.os.storage.StorageManager;
Amith Yamasani52c489c2012-03-28 11:42:42 -070089import android.provider.Settings;
90import android.provider.Settings.Secure;
Jim Miller187ec582013-04-15 18:27:54 -070091import android.provider.Settings.SettingNotFoundException;
Jim Millerde1af082013-09-11 14:58:26 -070092import android.security.KeyStore;
Ricky Waidc283a82016-03-24 19:55:08 +000093import android.security.keystore.AndroidKeyStoreProvider;
94import android.security.keystore.KeyProperties;
95import android.security.keystore.KeyProtection;
Pavel Grafov0acc4bf2017-08-23 12:20:54 +010096import android.security.keystore.UserNotAuthenticatedException;
Dmitry Dementyev0916e7c2018-01-23 13:02:08 -080097import android.security.keystore.recovery.KeyChainProtectionParams;
Bo Zhuc7048342019-01-03 14:04:58 -080098import android.security.keystore.recovery.KeyChainSnapshot;
Bo Zhu7c1972f2018-02-22 21:43:52 -080099import android.security.keystore.recovery.RecoveryCertPath;
Robert Berry81ee34b2018-01-23 11:59:59 +0000100import android.security.keystore.recovery.WrappedApplicationKey;
Andres Morales23974272015-05-14 22:42:26 -0700101import android.service.gatekeeper.GateKeeperResponse;
Andres Morales8fa56652015-03-31 09:19:50 -0700102import android.service.gatekeeper.IGateKeeperService;
Amith Yamasani52c489c2012-03-28 11:42:42 -0700103import android.text.TextUtils;
Rubin Xua55b1682017-01-31 10:06:56 +0000104import android.util.ArrayMap;
Annie Meng086ddc82019-03-29 17:43:35 +0000105import android.util.ArraySet;
Adrian Roosb953e182017-08-17 17:58:26 +0200106import android.util.EventLog;
Amith Yamasani52c489c2012-03-28 11:42:42 -0700107import android.util.Slog;
Andrew Scull1416bd02018-01-05 18:33:58 +0000108import android.util.SparseArray;
Amith Yamasani52c489c2012-03-28 11:42:42 -0700109
Pavel Grafov28939982017-10-03 15:11:52 +0100110import com.android.internal.annotations.GuardedBy;
Rubin Xu0cbc19e2016-12-09 14:00:21 +0000111import com.android.internal.annotations.VisibleForTesting;
Chris Wren282cfef2017-03-27 15:01:44 -0400112import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
Geoffrey Pitschaf759c52017-02-15 09:35:38 -0500113import com.android.internal.notification.SystemNotificationChannels;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -0600114import com.android.internal.util.DumpUtils;
Rubin Xue2f925f2019-08-14 16:53:55 +0100115import com.android.internal.util.IndentingPrintWriter;
Jorim Jaggie8fde5d2016-06-30 23:41:37 -0700116import com.android.internal.widget.ICheckCredentialProgressCallback;
Jeff Sharkey7a96c392012-11-15 14:01:46 -0800117import com.android.internal.widget.ILockSettings;
118import com.android.internal.widget.LockPatternUtils;
Rubin Xufcd49f92017-08-24 18:21:52 +0100119import com.android.internal.widget.LockSettingsInternal;
Rubin Xua58125d2019-09-06 20:11:48 +0100120import com.android.internal.widget.LockscreenCredential;
Kenny Rootf76cfc32019-11-08 14:36:03 -0800121import com.android.internal.widget.RebootEscrowListener;
Andres Morales23974272015-05-14 22:42:26 -0700122import com.android.internal.widget.VerifyCredentialResponse;
Pavel Grafov28939982017-10-03 15:11:52 +0100123import com.android.server.LocalServices;
Alex Johnston6183cf92019-10-03 15:59:03 +0100124import com.android.server.ServiceThread;
Andrew Scull507d11c2017-05-03 17:19:01 +0100125import com.android.server.SystemService;
126import com.android.server.locksettings.LockSettingsStorage.CredentialHash;
Dmitry Dementyev1aa96132017-12-11 11:33:12 -0800127import com.android.server.locksettings.LockSettingsStorage.PersistentData;
Andrew Scull507d11c2017-05-03 17:19:01 +0100128import com.android.server.locksettings.SyntheticPasswordManager.AuthenticationResult;
129import com.android.server.locksettings.SyntheticPasswordManager.AuthenticationToken;
Bo Zhuc7048342019-01-03 14:04:58 -0800130import com.android.server.locksettings.recoverablekeystore.RecoverableKeyStoreManager;
Adrian Roos1c8e3c02018-11-20 20:07:55 +0100131import com.android.server.wm.WindowManagerInternal;
Jeff Sharkey7a96c392012-11-15 14:01:46 -0800132
Ricky Waidc283a82016-03-24 19:55:08 +0000133import libcore.util.HexEncoding;
134
135import java.io.ByteArrayOutputStream;
Jorim Jaggi2fef6f72016-11-01 19:06:25 -0700136import java.io.FileDescriptor;
Ricky Waidc283a82016-03-24 19:55:08 +0000137import java.io.FileNotFoundException;
138import java.io.IOException;
Rubin Xu3bf722a2016-12-15 16:07:38 +0000139import java.io.PrintWriter;
Rubin Xua3c71a12019-12-04 15:25:02 +0000140import java.security.GeneralSecurityException;
Ricky Waidc283a82016-03-24 19:55:08 +0000141import java.security.InvalidAlgorithmParameterException;
142import java.security.InvalidKeyException;
143import java.security.KeyStoreException;
Paul Crowleyfaeb3eb2016-02-08 15:58:29 +0000144import java.security.MessageDigest;
145import java.security.NoSuchAlgorithmException;
Ricky Waidc283a82016-03-24 19:55:08 +0000146import java.security.SecureRandom;
147import java.security.UnrecoverableKeyException;
148import java.security.cert.CertificateException;
Rubin Xue2f925f2019-08-14 16:53:55 +0100149import java.text.SimpleDateFormat;
Andrew Sculle6527c12018-01-05 18:33:58 +0000150import java.util.ArrayList;
Bo Zhuc7048342019-01-03 14:04:58 -0800151import java.util.Arrays;
Rubin Xue2f925f2019-08-14 16:53:55 +0100152import java.util.Date;
Jim Miller187ec582013-04-15 18:27:54 -0700153import java.util.List;
Rubin Xua55b1682017-01-31 10:06:56 +0000154import java.util.Map;
Andrew Sculle6527c12018-01-05 18:33:58 +0000155import java.util.NoSuchElementException;
Daulet Zhanguzin8ea0a622020-01-02 17:36:31 +0000156import java.util.Objects;
Annie Meng086ddc82019-03-29 17:43:35 +0000157import java.util.Set;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -0600158import java.util.concurrent.CountDownLatch;
159import java.util.concurrent.TimeUnit;
Amith Yamasani52c489c2012-03-28 11:42:42 -0700160
Ricky Waidc283a82016-03-24 19:55:08 +0000161import javax.crypto.BadPaddingException;
162import javax.crypto.Cipher;
163import javax.crypto.IllegalBlockSizeException;
164import javax.crypto.KeyGenerator;
165import javax.crypto.NoSuchPaddingException;
166import javax.crypto.SecretKey;
167import javax.crypto.spec.GCMParameterSpec;
168
Amith Yamasani52c489c2012-03-28 11:42:42 -0700169/**
Rubin Xu1de89b32016-11-30 20:03:13 +0000170 * Keeps the lock pattern/password data and related settings for each user. Used by
171 * LockPatternUtils. Needs to be a service because Settings app also needs to be able to save
172 * lockscreen information for secondary users.
173 *
Amith Yamasani52c489c2012-03-28 11:42:42 -0700174 * @hide
175 */
176public class LockSettingsService extends ILockSettings.Stub {
Amith Yamasani52c489c2012-03-28 11:42:42 -0700177 private static final String TAG = "LockSettingsService";
Jim Miller4f93c582016-01-27 19:05:43 -0800178 private static final String PERMISSION = ACCESS_KEYGUARD_SECURE_STORAGE;
Haining Chenc06c4812020-01-13 20:38:53 -0800179 private static final String BIOMETRIC_PERMISSION = MANAGE_BIOMETRIC;
Jim Miller4f93c582016-01-27 19:05:43 -0800180 private static final boolean DEBUG = false;
Amith Yamasani52c489c2012-03-28 11:42:42 -0700181
Ricky Waidc283a82016-03-24 19:55:08 +0000182 private static final int PROFILE_KEY_IV_SIZE = 12;
183 private static final String SEPARATE_PROFILE_CHALLENGE_KEY = "lockscreen.profilechallenge";
Rubin Xue2f925f2019-08-14 16:53:55 +0100184 private static final String PREV_SYNTHETIC_PASSWORD_HANDLE_KEY = "prev-sp-handle";
185 private static final String SYNTHETIC_PASSWORD_UPDATE_TIME_KEY = "sp-handle-ts";
Rubin Xu066ce2f2019-11-29 17:17:46 +0000186 private static final String USER_SERIAL_NUMBER_KEY = "serial-number";
Rubin Xu1de89b32016-11-30 20:03:13 +0000187
Kevin Chynbc29dd72019-06-13 11:47:54 -0700188 // No challenge provided
189 private static final int CHALLENGE_NONE = 0;
190 // Challenge was provided from the external caller (non-LockSettingsService)
191 private static final int CHALLENGE_FROM_CALLER = 1;
192 // Challenge was generated from within LockSettingsService, for resetLockout. When challenge
193 // type is set to internal, LSS will revokeChallenge after all profiles for that user are
194 // unlocked.
195 private static final int CHALLENGE_INTERNAL = 2;
196
197 @IntDef({CHALLENGE_NONE,
198 CHALLENGE_FROM_CALLER,
199 CHALLENGE_INTERNAL})
Rubin Xua7587272019-07-30 17:14:28 +0100200 @interface ChallengeType {}
Kevin Chynbc29dd72019-06-13 11:47:54 -0700201
Rubin Xua0a0d352017-05-15 16:18:01 +0000202 // Order of holding lock: mSeparateChallengeLock -> mSpManager -> this
Rubin Xue94a7702017-06-20 17:29:57 +0100203 // Do not call into ActivityManager while holding mSpManager lock.
Ricky Waidc283a82016-03-24 19:55:08 +0000204 private final Object mSeparateChallengeLock = new Object();
205
Adrian Roos7374d3a2017-03-31 14:14:53 -0700206 private final DeviceProvisionedObserver mDeviceProvisionedObserver =
207 new DeviceProvisionedObserver();
208
Rubin Xu0cbc19e2016-12-09 14:00:21 +0000209 private final Injector mInjector;
Amith Yamasani52c489c2012-03-28 11:42:42 -0700210 private final Context mContext;
Rubin Xu7cf45092017-08-28 11:47:35 +0100211 @VisibleForTesting
212 protected final Handler mHandler;
Rubin Xu0cbc19e2016-12-09 14:00:21 +0000213 @VisibleForTesting
214 protected final LockSettingsStorage mStorage;
Rakesh Iyera7aa4d62016-01-19 17:27:23 -0800215 private final LockSettingsStrongAuth mStrongAuth;
Victor Changa0940d32016-05-16 19:36:08 +0100216 private final SynchronizedStrongAuthTracker mStrongAuthTracker;
Adrian Roos261d5ab2014-10-29 14:42:38 +0100217
Rubin Xu0cbc19e2016-12-09 14:00:21 +0000218 private final NotificationManager mNotificationManager;
219 private final UserManager mUserManager;
Rubin Xuca7007b2019-03-25 11:44:41 +0000220 private final IStorageManager mStorageManager;
Rubin Xu0cbc19e2016-12-09 14:00:21 +0000221 private final IActivityManager mActivityManager;
Andrew Scull8fc2ec82017-05-19 10:50:36 +0100222 private final SyntheticPasswordManager mSpManager;
Rubin Xu0cbc19e2016-12-09 14:00:21 +0000223
224 private final KeyStore mKeyStore;
225
Dmitry Dementyev1aa96132017-12-11 11:33:12 -0800226 private final RecoverableKeyStoreManager mRecoverableKeyStoreManager;
Rubin Xua3c71a12019-12-04 15:25:02 +0000227 private ManagedProfilePasswordCache mManagedProfilePasswordCache;
Dmitry Dementyev1aa96132017-12-11 11:33:12 -0800228
Kenny Rootf76cfc32019-11-08 14:36:03 -0800229 private final RebootEscrowManager mRebootEscrowManager;
230
Paul Lawrence945490c2014-03-27 16:37:28 +0000231 private boolean mFirstCallToVold;
Kenny Rootf76cfc32019-11-08 14:36:03 -0800232
Rubin Xu19854862019-08-15 16:37:23 +0100233 // Current password metric for all users on the device. Updated when user unlocks
234 // the device or changes password. Removed when user is stopped.
235 @GuardedBy("this")
236 final SparseArray<PasswordMetrics> mUserPasswordMetrics = new SparseArray<>();
Rubin Xu3744acf2020-01-02 16:39:50 +0000237 @VisibleForTesting
238 protected boolean mHasSecureLockScreen;
Rubin Xu19854862019-08-15 16:37:23 +0100239
Rubin Xu0cbc19e2016-12-09 14:00:21 +0000240 protected IGateKeeperService mGateKeeperService;
Andrew Sculle6527c12018-01-05 18:33:58 +0000241 protected IAuthSecret mAuthSecretService;
Rubin Xu3bf722a2016-12-15 16:07:38 +0000242
David Anderson6ebc25b2019-02-12 16:25:56 -0800243 private static final String GSI_RUNNING_PROP = "ro.gsid.image_running";
244
Ricky Wai4613fe42016-05-24 11:11:42 +0100245 /**
246 * The UIDs that are used for system credential storage in keystore.
247 */
Rubin Xu1de89b32016-11-30 20:03:13 +0000248 private static final int[] SYSTEM_CREDENTIAL_UIDS = {
249 Process.WIFI_UID, Process.VPN_UID,
Rubin Xu24b89b12017-04-26 19:44:16 +0100250 Process.ROOT_UID, Process.SYSTEM_UID };
Andres Morales23974272015-05-14 22:42:26 -0700251
Jim Miller4f93c582016-01-27 19:05:43 -0800252 // This class manages life cycle events for encrypted users on File Based Encryption (FBE)
253 // devices. The most basic of these is to show/hide notifications about missing features until
254 // the user unlocks the account and credential-encrypted storage is available.
255 public static final class Lifecycle extends SystemService {
256 private LockSettingsService mLockSettingsService;
257
258 public Lifecycle(Context context) {
259 super(context);
260 }
261
262 @Override
263 public void onStart() {
Ricky Waidc283a82016-03-24 19:55:08 +0000264 AndroidKeyStoreProvider.install();
Jim Miller4f93c582016-01-27 19:05:43 -0800265 mLockSettingsService = new LockSettingsService(getContext());
266 publishBinderService("lock_settings", mLockSettingsService);
267 }
268
269 @Override
Adrian Roos60dcbbf2017-08-08 16:19:33 +0200270 public void onBootPhase(int phase) {
271 super.onBootPhase(phase);
272 if (phase == PHASE_ACTIVITY_MANAGER_READY) {
273 mLockSettingsService.migrateOldDataAfterSystemReady();
274 }
275 }
276
277 @Override
Andrew Scull85a63bc2016-10-24 13:47:47 +0100278 public void onStartUser(int userHandle) {
279 mLockSettingsService.onStartUser(userHandle);
Jim Miller4f93c582016-01-27 19:05:43 -0800280 }
281
282 @Override
283 public void onUnlockUser(int userHandle) {
284 mLockSettingsService.onUnlockUser(userHandle);
285 }
286
287 @Override
288 public void onCleanupUser(int userHandle) {
289 mLockSettingsService.onCleanupUser(userHandle);
290 }
291 }
292
Rubin Xu0cbc19e2016-12-09 14:00:21 +0000293 @VisibleForTesting
294 protected static class SynchronizedStrongAuthTracker
295 extends LockPatternUtils.StrongAuthTracker {
Victor Changa0940d32016-05-16 19:36:08 +0100296 public SynchronizedStrongAuthTracker(Context context) {
297 super(context);
298 }
299
300 @Override
301 protected void handleStrongAuthRequiredChanged(int strongAuthFlags, int userId) {
302 synchronized (this) {
303 super.handleStrongAuthRequiredChanged(strongAuthFlags, userId);
304 }
305 }
306
307 @Override
308 public int getStrongAuthForUser(int userId) {
309 synchronized (this) {
310 return super.getStrongAuthForUser(userId);
311 }
312 }
313
Rubin Xu0cbc19e2016-12-09 14:00:21 +0000314 void register(LockSettingsStrongAuth strongAuth) {
Beverlyf882ee22020-05-11 16:12:09 -0400315 strongAuth.registerStrongAuthTracker(getStub());
Victor Changa0940d32016-05-16 19:36:08 +0100316 }
317 }
318
Kevin Chynbc29dd72019-06-13 11:47:54 -0700319 private class PendingResetLockout {
320 final int mUserId;
321 final byte[] mHAT;
322 PendingResetLockout(int userId, byte[] hat) {
323 mUserId = userId;
324 mHAT = hat;
325 }
326 }
327
Rubin Xubb883202019-10-09 11:22:53 +0100328 private LockscreenCredential generateRandomProfilePassword() {
329 byte[] randomLockSeed = new byte[] {};
330 try {
331 randomLockSeed = SecureRandom.getInstance("SHA1PRNG").generateSeed(40);
332 char[] newPasswordChars = HexEncoding.encode(randomLockSeed);
333 byte[] newPassword = new byte[newPasswordChars.length];
334 for (int i = 0; i < newPasswordChars.length; i++) {
335 newPassword[i] = (byte) newPasswordChars[i];
336 }
337 LockscreenCredential credential =
338 LockscreenCredential.createManagedPassword(newPassword);
339 Arrays.fill(newPasswordChars, '\u0000');
340 Arrays.fill(newPassword, (byte) 0);
341 Arrays.fill(randomLockSeed, (byte) 0);
342 return credential;
343 } catch (NoSuchAlgorithmException e) {
Rubin Xu5e891bc2019-10-14 10:22:23 +0100344 throw new IllegalStateException("Fail to generate profile password", e);
Rubin Xubb883202019-10-09 11:22:53 +0100345 }
346 }
347
Ricky Waidc283a82016-03-24 19:55:08 +0000348 /**
349 * Tie managed profile to primary profile if it is in unified mode and not tied before.
350 *
351 * @param managedUserId Managed profile user Id
352 * @param managedUserPassword Managed profile original password (when it has separated lock).
Ricky Waidc283a82016-03-24 19:55:08 +0000353 */
Rubin Xubb883202019-10-09 11:22:53 +0100354 public void tieManagedProfileLockIfNecessary(int managedUserId,
355 LockscreenCredential managedUserPassword) {
Ricky Waidc283a82016-03-24 19:55:08 +0000356 if (DEBUG) Slog.v(TAG, "Check child profile lock for user: " + managedUserId);
357 // Only for managed profile
Rubin Xu0cbc19e2016-12-09 14:00:21 +0000358 if (!mUserManager.getUserInfo(managedUserId).isManagedProfile()) {
Ricky Waidc283a82016-03-24 19:55:08 +0000359 return;
360 }
361 // Do not tie managed profile when work challenge is enabled
Rubin Xu3744acf2020-01-02 16:39:50 +0000362 if (getSeparateProfileChallengeEnabledInternal(managedUserId)) {
Ricky Waidc283a82016-03-24 19:55:08 +0000363 return;
364 }
365 // Do not tie managed profile to parent when it's done already
366 if (mStorage.hasChildProfileLock(managedUserId)) {
367 return;
368 }
Rubin Xude633f32020-04-02 16:37:32 +0100369 // If parent does not have a screen lock, simply clear credential from the managed profile,
370 // to maintain the invariant that unified profile should always have the same secure state
371 // as its parent.
Ricky Waidc283a82016-03-24 19:55:08 +0000372 final int parentId = mUserManager.getProfileParent(managedUserId).id;
Rubin Xude633f32020-04-02 16:37:32 +0100373 if (!isUserSecure(parentId) && !managedUserPassword.isNone()) {
374 if (DEBUG) Slog.v(TAG, "Parent does not have a screen lock but profile has one");
375
376 setLockCredentialInternal(LockscreenCredential.createNone(), managedUserPassword,
377 managedUserId, /* isLockTiedToParent= */ true);
Ricky Waidc283a82016-03-24 19:55:08 +0000378 return;
379 }
Rubin Xubfc7faaf2016-11-22 15:18:32 +0000380 // Do not tie when the parent has no SID (but does have a screen lock).
381 // This can only happen during an upgrade path where SID is yet to be
382 // generated when the user unlocks for the first time.
383 try {
384 if (getGateKeeperService().getSecureUserId(parentId) == 0) {
385 return;
386 }
387 } catch (RemoteException e) {
388 Slog.e(TAG, "Failed to talk to GateKeeper service", e);
389 return;
390 }
Ricky Waidc283a82016-03-24 19:55:08 +0000391 if (DEBUG) Slog.v(TAG, "Tie managed profile to parent now!");
Rubin Xubb883202019-10-09 11:22:53 +0100392 try (LockscreenCredential unifiedProfilePassword = generateRandomProfilePassword()) {
Rubin Xubb883202019-10-09 11:22:53 +0100393 setLockCredentialInternal(unifiedProfilePassword, managedUserPassword, managedUserId,
Rubin Xud9522402019-11-06 13:54:27 +0000394 /* isLockTiedToParent= */ true);
Rubin Xubb883202019-10-09 11:22:53 +0100395 tieProfileLockToParent(managedUserId, unifiedProfilePassword);
Rubin Xua3c71a12019-12-04 15:25:02 +0000396 mManagedProfilePasswordCache.storePassword(managedUserId, unifiedProfilePassword);
Ricky Waidc283a82016-03-24 19:55:08 +0000397 }
398 }
399
Rubin Xu0cbc19e2016-12-09 14:00:21 +0000400 static class Injector {
Jim Millerde1af082013-09-11 14:58:26 -0700401
Rubin Xu0cbc19e2016-12-09 14:00:21 +0000402 protected Context mContext;
403
404 public Injector(Context context) {
405 mContext = context;
406 }
407
408 public Context getContext() {
409 return mContext;
410 }
411
Alex Johnston6183cf92019-10-03 15:59:03 +0100412 public ServiceThread getServiceThread() {
413 ServiceThread handlerThread = new ServiceThread(TAG, Process.THREAD_PRIORITY_BACKGROUND,
414 true /*allowIo*/);
415 handlerThread.start();
416 return handlerThread;
417 }
418
419 public Handler getHandler(ServiceThread handlerThread) {
420 return new Handler(handlerThread.getLooper());
Rubin Xu0cbc19e2016-12-09 14:00:21 +0000421 }
422
423 public LockSettingsStorage getStorage() {
424 final LockSettingsStorage storage = new LockSettingsStorage(mContext);
425 storage.setDatabaseOnCreateCallback(new LockSettingsStorage.Callback() {
426 @Override
427 public void initialize(SQLiteDatabase db) {
428 // Get the lockscreen default from a system property, if available
429 boolean lockScreenDisable = SystemProperties.getBoolean(
430 "ro.lockscreen.disable.default", false);
431 if (lockScreenDisable) {
432 storage.writeKeyValue(db, LockPatternUtils.DISABLE_LOCKSCREEN_KEY, "1", 0);
433 }
434 }
435 });
436 return storage;
437 }
438
439 public LockSettingsStrongAuth getStrongAuth() {
440 return new LockSettingsStrongAuth(mContext);
441 }
442
443 public SynchronizedStrongAuthTracker getStrongAuthTracker() {
444 return new SynchronizedStrongAuthTracker(mContext);
445 }
446
447 public IActivityManager getActivityManager() {
448 return ActivityManager.getService();
449 }
450
Rubin Xu0cbc19e2016-12-09 14:00:21 +0000451 public NotificationManager getNotificationManager() {
452 return (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
453 }
454
455 public UserManager getUserManager() {
456 return (UserManager) mContext.getSystemService(Context.USER_SERVICE);
457 }
458
Rubin Xu0f1e56d2019-08-23 13:34:25 +0100459 public UserManagerInternal getUserManagerInternal() {
460 return LocalServices.getService(UserManagerInternal.class);
461 }
462
Rubin Xu19854862019-08-15 16:37:23 +0100463 /**
464 * Return the {@link DevicePolicyManager} object.
465 *
466 * Since LockSettingsService is considered a lower-level component than DevicePolicyManager,
467 * do NOT hold any lock in this class while calling into DevicePolicyManager to prevent
468 * the risk of deadlock.
469 */
Rubin Xu8b30ec32017-03-05 00:47:09 +0000470 public DevicePolicyManager getDevicePolicyManager() {
471 return (DevicePolicyManager) mContext.getSystemService(Context.DEVICE_POLICY_SERVICE);
472 }
473
Rubin Xu0f1e56d2019-08-23 13:34:25 +0100474 public DeviceStateCache getDeviceStateCache() {
475 return DeviceStateCache.getInstance();
476 }
477
Rubin Xu0cbc19e2016-12-09 14:00:21 +0000478 public KeyStore getKeyStore() {
479 return KeyStore.getInstance();
480 }
481
Dmitry Dementyev29b9de52018-01-31 16:09:32 -0800482 public RecoverableKeyStoreManager getRecoverableKeyStoreManager(KeyStore keyStore) {
483 return RecoverableKeyStoreManager.getInstance(mContext, keyStore);
Dmitry Dementyev1aa96132017-12-11 11:33:12 -0800484 }
485
Rubin Xu0cbc19e2016-12-09 14:00:21 +0000486 public IStorageManager getStorageManager() {
487 final IBinder service = ServiceManager.getService("mount");
488 if (service != null) {
489 return IStorageManager.Stub.asInterface(service);
490 }
491 return null;
492 }
Rubin Xu3bf722a2016-12-15 16:07:38 +0000493
494 public SyntheticPasswordManager getSyntheticPasswordManager(LockSettingsStorage storage) {
David Anderson28dea682019-02-20 13:37:51 -0800495 return new SyntheticPasswordManager(getContext(), storage, getUserManager(),
496 new PasswordSlotManager());
Rubin Xu3bf722a2016-12-15 16:07:38 +0000497 }
498
Kenny Rootf76cfc32019-11-08 14:36:03 -0800499 public RebootEscrowManager getRebootEscrowManager(RebootEscrowManager.Callbacks callbacks,
500 LockSettingsStorage storage) {
501 return new RebootEscrowManager(mContext, callbacks, storage);
502 }
503
Kevin Chyn28623b62019-06-11 11:43:33 -0700504 public boolean hasEnrolledBiometrics(int userId) {
Kevin Chyn71db85f2019-05-14 15:32:47 -0700505 BiometricManager bm = mContext.getSystemService(BiometricManager.class);
Kevin Chyn27f92312019-07-26 12:41:33 -0700506 return bm.hasEnrolledBiometrics(userId);
Kevin Chyncf1a62e2019-02-21 11:11:59 -0800507 }
508
Rubin Xu3bf722a2016-12-15 16:07:38 +0000509 public int binderGetCallingUid() {
510 return Binder.getCallingUid();
511 }
David Anderson6ebc25b2019-02-12 16:25:56 -0800512
513 public boolean isGsiRunning() {
514 return SystemProperties.getInt(GSI_RUNNING_PROP, 0) > 0;
515 }
Alex Johnston6183cf92019-10-03 15:59:03 +0100516
517 public FingerprintManager getFingerprintManager() {
518 if (mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_FINGERPRINT)) {
519 return (FingerprintManager) mContext.getSystemService(Context.FINGERPRINT_SERVICE);
520 } else {
521 return null;
522 }
523 }
524
525 public FaceManager getFaceManager() {
526 if (mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_FACE)) {
527 return (FaceManager) mContext.getSystemService(Context.FACE_SERVICE);
528 } else {
529 return null;
530 }
531 }
532
Rubin Xu5e891bc2019-10-14 10:22:23 +0100533 public int settingsGlobalGetInt(ContentResolver contentResolver, String keyName,
534 int defaultValue) {
535 return Settings.Global.getInt(contentResolver, keyName, defaultValue);
536 }
Rubin Xua3c71a12019-12-04 15:25:02 +0000537
Rubin Xu6cd87c22020-02-20 16:44:27 +0000538 public int settingsSecureGetInt(ContentResolver contentResolver, String keyName,
539 int defaultValue, int userId) {
540 return Settings.Secure.getIntForUser(contentResolver, keyName, defaultValue, userId);
541 }
542
Rubin Xua3c71a12019-12-04 15:25:02 +0000543 public @NonNull ManagedProfilePasswordCache getManagedProfilePasswordCache() {
544 try {
545 java.security.KeyStore ks = java.security.KeyStore.getInstance("AndroidKeyStore");
546 ks.load(null);
547 return new ManagedProfilePasswordCache(ks, getUserManager());
548 } catch (Exception e) {
549 throw new IllegalStateException("Cannot load keystore", e);
550 }
551 }
Rubin Xu0cbc19e2016-12-09 14:00:21 +0000552 }
553
554 public LockSettingsService(Context context) {
555 this(new Injector(context));
556 }
557
558 @VisibleForTesting
559 protected LockSettingsService(Injector injector) {
560 mInjector = injector;
561 mContext = injector.getContext();
562 mKeyStore = injector.getKeyStore();
Dmitry Dementyev29b9de52018-01-31 16:09:32 -0800563 mRecoverableKeyStoreManager = injector.getRecoverableKeyStoreManager(mKeyStore);
Alex Johnston6183cf92019-10-03 15:59:03 +0100564 mHandler = injector.getHandler(injector.getServiceThread());
Rubin Xu0cbc19e2016-12-09 14:00:21 +0000565 mStrongAuth = injector.getStrongAuth();
566 mActivityManager = injector.getActivityManager();
567
Paul Lawrence945490c2014-03-27 16:37:28 +0000568 mFirstCallToVold = true;
Robin Leef0246a82014-08-13 09:50:25 +0100569
570 IntentFilter filter = new IntentFilter();
571 filter.addAction(Intent.ACTION_USER_ADDED);
Adrian Roos3dcae682014-10-29 14:43:56 +0100572 filter.addAction(Intent.ACTION_USER_STARTING);
Adrian Roosdb0f76e2015-01-07 22:19:38 +0100573 filter.addAction(Intent.ACTION_USER_REMOVED);
Rubin Xu0cbc19e2016-12-09 14:00:21 +0000574 injector.getContext().registerReceiverAsUser(mBroadcastReceiver, UserHandle.ALL, filter,
575 null, null);
Adrian Roos261d5ab2014-10-29 14:42:38 +0100576
Rubin Xu0cbc19e2016-12-09 14:00:21 +0000577 mStorage = injector.getStorage();
578 mNotificationManager = injector.getNotificationManager();
579 mUserManager = injector.getUserManager();
Rubin Xuca7007b2019-03-25 11:44:41 +0000580 mStorageManager = injector.getStorageManager();
Rubin Xu0cbc19e2016-12-09 14:00:21 +0000581 mStrongAuthTracker = injector.getStrongAuthTracker();
582 mStrongAuthTracker.register(mStrongAuth);
Rubin Xu3bf722a2016-12-15 16:07:38 +0000583
584 mSpManager = injector.getSyntheticPasswordManager(mStorage);
Rubin Xua3c71a12019-12-04 15:25:02 +0000585 mManagedProfilePasswordCache = injector.getManagedProfilePasswordCache();
Rubin Xufcd49f92017-08-24 18:21:52 +0100586
Kenny Rootf76cfc32019-11-08 14:36:03 -0800587 mRebootEscrowManager = injector.getRebootEscrowManager(new RebootEscrowCallbacks(),
588 mStorage);
589
Rubin Xufcd49f92017-08-24 18:21:52 +0100590 LocalServices.addService(LockSettingsInternal.class, new LocalService());
Jim Miller4f93c582016-01-27 19:05:43 -0800591 }
592
593 /**
Rubin Xu1de89b32016-11-30 20:03:13 +0000594 * If the account is credential-encrypted, show notification requesting the user to unlock the
595 * device.
Jim Miller4f93c582016-01-27 19:05:43 -0800596 */
Andrew Scull85a63bc2016-10-24 13:47:47 +0100597 private void maybeShowEncryptionNotificationForUser(@UserIdInt int userId) {
598 final UserInfo user = mUserManager.getUserInfo(userId);
599 if (!user.isManagedProfile()) {
600 // When the user is locked, we communicate it loud-and-clear
601 // on the lockscreen; we only show a notification below for
602 // locked managed profiles.
603 return;
604 }
605
Irina Dumitrescue13ce662019-05-09 17:50:50 +0100606 if (isUserKeyUnlocked(userId)) {
607 // If storage is not locked, the user will be automatically unlocked so there is
608 // no need to show the notification.
609 return;
610 }
611
Andrew Scull85a63bc2016-10-24 13:47:47 +0100612 final UserHandle userHandle = user.getUserHandle();
Rubin Xua55b1682017-01-31 10:06:56 +0000613 final boolean isSecure = isUserSecure(userId);
Andrew Scull85a63bc2016-10-24 13:47:47 +0100614 if (isSecure && !mUserManager.isUserUnlockingOrUnlocked(userHandle)) {
615 UserInfo parent = mUserManager.getProfileParent(userId);
616 if (parent != null &&
617 mUserManager.isUserUnlockingOrUnlocked(parent.getUserHandle()) &&
618 !mUserManager.isQuietModeEnabled(userHandle)) {
619 // Only show notifications for managed profiles once their parent
620 // user is unlocked.
621 showEncryptionNotificationForProfile(userHandle);
Jim Miller4f93c582016-01-27 19:05:43 -0800622 }
Jim Miller4f93c582016-01-27 19:05:43 -0800623 }
624 }
625
Kenny Guyb1b30262016-02-09 16:02:35 +0000626 private void showEncryptionNotificationForProfile(UserHandle user) {
627 Resources r = mContext.getResources();
628 CharSequence title = r.getText(
Rubin Xu897750a2019-04-30 17:15:03 +0100629 com.android.internal.R.string.profile_encrypted_title);
Kenny Guyb1b30262016-02-09 16:02:35 +0000630 CharSequence message = r.getText(
631 com.android.internal.R.string.profile_encrypted_message);
632 CharSequence detail = r.getText(
633 com.android.internal.R.string.profile_encrypted_detail);
634
635 final KeyguardManager km = (KeyguardManager) mContext.getSystemService(KEYGUARD_SERVICE);
Rubin Xu1de89b32016-11-30 20:03:13 +0000636 final Intent unlockIntent = km.createConfirmDeviceCredentialIntent(null, null,
637 user.getIdentifier());
Kenny Guyb1b30262016-02-09 16:02:35 +0000638 if (unlockIntent == null) {
639 return;
640 }
Rubin Xu1de89b32016-11-30 20:03:13 +0000641 unlockIntent.setFlags(
642 Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
Kenny Guyb1b30262016-02-09 16:02:35 +0000643 PendingIntent intent = PendingIntent.getActivity(mContext, 0, unlockIntent,
644 PendingIntent.FLAG_UPDATE_CURRENT);
645
646 showEncryptionNotification(user, title, message, detail, intent);
647 }
648
Rubin Xu1de89b32016-11-30 20:03:13 +0000649 private void showEncryptionNotification(UserHandle user, CharSequence title,
650 CharSequence message, CharSequence detail, PendingIntent intent) {
Kenny Guyb1b30262016-02-09 16:02:35 +0000651 if (DEBUG) Slog.v(TAG, "showing encryption notification, user: " + user.getIdentifier());
Jeff Sharkey4a399362016-05-26 09:47:43 -0600652
653 // Suppress all notifications on non-FBE devices for now
654 if (!StorageManager.isFileEncryptedNativeOrEmulated()) return;
655
Geoffrey Pitschaf759c52017-02-15 09:35:38 -0500656 Notification notification =
Rubin Xu897750a2019-04-30 17:15:03 +0100657 new Notification.Builder(mContext, SystemNotificationChannels.DEVICE_ADMIN)
Geoffrey Pitschaf759c52017-02-15 09:35:38 -0500658 .setSmallIcon(com.android.internal.R.drawable.ic_user_secure)
659 .setWhen(0)
660 .setOngoing(true)
661 .setTicker(title)
662 .setColor(mContext.getColor(
663 com.android.internal.R.color.system_notification_accent_color))
664 .setContentTitle(title)
665 .setContentText(message)
666 .setSubText(detail)
667 .setVisibility(Notification.VISIBILITY_PUBLIC)
668 .setContentIntent(intent)
669 .build();
Chris Wren282cfef2017-03-27 15:01:44 -0400670 mNotificationManager.notifyAsUser(null, SystemMessage.NOTE_FBE_ENCRYPTED_NOTIFICATION,
671 notification, user);
Jim Miller4f93c582016-01-27 19:05:43 -0800672 }
673
Andrew Scull85a63bc2016-10-24 13:47:47 +0100674 private void hideEncryptionNotification(UserHandle userHandle) {
Rubin Xu1de89b32016-11-30 20:03:13 +0000675 if (DEBUG) Slog.v(TAG, "hide encryption notification, user: " + userHandle.getIdentifier());
Chris Wren282cfef2017-03-27 15:01:44 -0400676 mNotificationManager.cancelAsUser(null, SystemMessage.NOTE_FBE_ENCRYPTED_NOTIFICATION,
677 userHandle);
Jim Miller4f93c582016-01-27 19:05:43 -0800678 }
679
680 public void onCleanupUser(int userId) {
681 hideEncryptionNotification(new UserHandle(userId));
Erin Yan324d75e2019-05-16 17:22:21 -0700682 // User is stopped with its CE key evicted. Restore strong auth requirement to the default
683 // flags after boot since stopping and restarting a user later is equivalent to rebooting
684 // the device.
685 int strongAuthRequired = LockPatternUtils.StrongAuthTracker.getDefaultFlags(mContext);
686 requireStrongAuth(strongAuthRequired, userId);
Rubin Xu19854862019-08-15 16:37:23 +0100687 synchronized (this) {
688 mUserPasswordMetrics.remove(userId);
689 }
Jim Miller4f93c582016-01-27 19:05:43 -0800690 }
691
Andrew Scull85a63bc2016-10-24 13:47:47 +0100692 public void onStartUser(final int userId) {
693 maybeShowEncryptionNotificationForUser(userId);
694 }
695
Pavel Grafov0acc4bf2017-08-23 12:20:54 +0100696 /**
Rubin Xu066ce2f2019-11-29 17:17:46 +0000697 * Clean up states associated with the given user, in case the userId is reused but LSS didn't
698 * get a chance to do cleanup previously during ACTION_USER_REMOVED.
699 *
700 * Internally, LSS stores serial number for each user and check it against the current user's
701 * serial number to determine if the userId is reused and invoke cleanup code.
702 */
703 private void cleanupDataForReusedUserIdIfNecessary(int userId) {
704 if (userId == UserHandle.USER_SYSTEM) {
705 // Short circuit as we never clean up user 0.
706 return;
707 }
708 // Serial number is never reusued, so we can use it as a distinguisher for user Id reuse.
709 int serialNumber = mUserManager.getUserSerialNumber(userId);
710
Kenny Roota486e2d2020-02-24 08:58:46 -0800711 int storedSerialNumber = mStorage.getInt(USER_SERIAL_NUMBER_KEY, -1, userId);
Rubin Xu066ce2f2019-11-29 17:17:46 +0000712 if (storedSerialNumber != serialNumber) {
713 // If LockSettingsStorage does not have a copy of the serial number, it could be either
714 // this is a user created before the serial number recording logic is introduced, or
715 // the user does not exist or was removed and cleaned up properly. In either case, don't
716 // invoke removeUser().
717 if (storedSerialNumber != -1) {
718 removeUser(userId, /* unknownUser */ true);
719 }
Kenny Roota486e2d2020-02-24 08:58:46 -0800720 mStorage.setInt(USER_SERIAL_NUMBER_KEY, serialNumber, userId);
Rubin Xu066ce2f2019-11-29 17:17:46 +0000721 }
722 }
723
724 /**
Pavel Grafov0acc4bf2017-08-23 12:20:54 +0100725 * Check if profile got unlocked but the keystore is still locked. This happens on full disk
726 * encryption devices since the profile may not yet be running when we consider unlocking it
727 * during the normal flow. In this case unlock the keystore for the profile.
728 */
729 private void ensureProfileKeystoreUnlocked(int userId) {
730 final KeyStore ks = KeyStore.getInstance();
731 if (ks.state(userId) == KeyStore.State.LOCKED
Rubin Xua3c71a12019-12-04 15:25:02 +0000732 && mUserManager.getUserInfo(userId).isManagedProfile()
733 && hasUnifiedChallenge(userId)) {
Pavel Grafov0acc4bf2017-08-23 12:20:54 +0100734 Slog.i(TAG, "Managed profile got unlocked, will unlock its keystore");
Rubin Xuca6ece52019-07-31 15:02:13 +0100735 // If boot took too long and the password in vold got expired, parent keystore will
736 // be still locked, we ignore this case since the user will be prompted to unlock
737 // the device after boot.
738 unlockChildProfile(userId, true /* ignoreUserNotAuthenticated */,
739 CHALLENGE_NONE, 0 /* challenge */, null /* resetLockouts */);
Pavel Grafov0acc4bf2017-08-23 12:20:54 +0100740 }
741 }
742
Ricky Waib0cdf382016-05-16 17:28:04 +0100743 public void onUnlockUser(final int userId) {
Rubin Xua55b1682017-01-31 10:06:56 +0000744 // Perform tasks which require locks in LSS on a handler, as we are callbacks from
745 // ActivityManager.unlockUser()
746 mHandler.post(new Runnable() {
747 @Override
748 public void run() {
Rubin Xu066ce2f2019-11-29 17:17:46 +0000749 cleanupDataForReusedUserIdIfNecessary(userId);
Pavel Grafov0acc4bf2017-08-23 12:20:54 +0100750 ensureProfileKeystoreUnlocked(userId);
Rubin Xua55b1682017-01-31 10:06:56 +0000751 // Hide notification first, as tie managed profile lock takes time
752 hideEncryptionNotification(new UserHandle(userId));
Ricky Waib0cdf382016-05-16 17:28:04 +0100753
Rubin Xua55b1682017-01-31 10:06:56 +0000754 if (mUserManager.getUserInfo(userId).isManagedProfile()) {
Rubin Xubb883202019-10-09 11:22:53 +0100755 tieManagedProfileLockIfNecessary(userId, LockscreenCredential.createNone());
Ricky Waib0cdf382016-05-16 17:28:04 +0100756 }
Andrew Scullf49794b2018-04-13 12:01:25 +0100757
758 // If the user doesn't have a credential, try and derive their secret for the
759 // AuthSecret HAL. The secret will have been enrolled if the user previously set a
760 // credential and still needs to be passed to the HAL once that credential is
761 // removed.
762 if (mUserManager.getUserInfo(userId).isPrimary() && !isUserSecure(userId)) {
763 tryDeriveAuthTokenForUnsecuredPrimaryUser(userId);
764 }
Kenny Guyb1b30262016-02-09 16:02:35 +0000765 }
Rubin Xua55b1682017-01-31 10:06:56 +0000766 });
Amith Yamasani52c489c2012-03-28 11:42:42 -0700767 }
768
Andrew Scullf49794b2018-04-13 12:01:25 +0100769 private void tryDeriveAuthTokenForUnsecuredPrimaryUser(@UserIdInt int userId) {
770 synchronized (mSpManager) {
771 // Make sure the user has a synthetic password to derive
772 if (!isSyntheticPasswordBasedCredentialLocked(userId)) {
773 return;
774 }
775
Rubin Xuca6ece52019-07-31 15:02:13 +0100776 final long handle = getSyntheticPasswordHandleLocked(userId);
Rubin Xuca6ece52019-07-31 15:02:13 +0100777 AuthenticationResult result =
Rubin Xubb883202019-10-09 11:22:53 +0100778 mSpManager.unwrapPasswordBasedSyntheticPassword(getGateKeeperService(),
779 handle, LockscreenCredential.createNone(), userId, null);
Rubin Xuca6ece52019-07-31 15:02:13 +0100780 if (result.authToken != null) {
781 Slog.i(TAG, "Retrieved auth token for user " + userId);
782 onAuthTokenKnownForUser(userId, result.authToken);
783 } else {
784 Slog.e(TAG, "Auth token not available for user " + userId);
Andrew Scullf49794b2018-04-13 12:01:25 +0100785 }
786 }
787 }
788
Robin Leef0246a82014-08-13 09:50:25 +0100789 private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
790 @Override
791 public void onReceive(Context context, Intent intent) {
Robin Lee1096cf82014-09-01 16:52:47 +0100792 if (Intent.ACTION_USER_ADDED.equals(intent.getAction())) {
Chad Brubaker83ce0952015-05-12 13:00:02 -0700793 // Notify keystore that a new user was added.
Robin Leef0246a82014-08-13 09:50:25 +0100794 final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, 0);
Robin Lee49d810c2014-09-23 13:50:22 +0100795 final KeyStore ks = KeyStore.getInstance();
Ricky Waidc283a82016-03-24 19:55:08 +0000796 final UserInfo parentInfo = mUserManager.getProfileParent(userHandle);
Chad Brubaker83ce0952015-05-12 13:00:02 -0700797 final int parentHandle = parentInfo != null ? parentInfo.id : -1;
798 ks.onUserAdded(userHandle, parentHandle);
Adrian Roos3dcae682014-10-29 14:43:56 +0100799 } else if (Intent.ACTION_USER_STARTING.equals(intent.getAction())) {
800 final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, 0);
801 mStorage.prefetchUser(userHandle);
Adrian Roosdb0f76e2015-01-07 22:19:38 +0100802 } else if (Intent.ACTION_USER_REMOVED.equals(intent.getAction())) {
803 final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, 0);
804 if (userHandle > 0) {
Amith Yamasanif11a5742016-06-16 08:20:07 -0700805 removeUser(userHandle, /* unknownUser= */ false);
Adrian Roosdb0f76e2015-01-07 22:19:38 +0100806 }
Robin Leef0246a82014-08-13 09:50:25 +0100807 }
808 }
809 };
810
Jim Miller4f93c582016-01-27 19:05:43 -0800811 @Override // binder interface
Amith Yamasani52c489c2012-03-28 11:42:42 -0700812 public void systemReady() {
Adrian Roosb953e182017-08-17 17:58:26 +0200813 if (mContext.checkCallingOrSelfPermission(PERMISSION) != PERMISSION_GRANTED) {
814 EventLog.writeEvent(0x534e4554, "28251513", getCallingUid(), ""); // SafetyNet
815 }
816 checkWritePermission(UserHandle.USER_SYSTEM);
Rubin Xu3744acf2020-01-02 16:39:50 +0000817
818 mHasSecureLockScreen = mContext.getPackageManager()
819 .hasSystemFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN);
Amith Yamasani52c489c2012-03-28 11:42:42 -0700820 migrateOldData();
Rubin Xuca6ece52019-07-31 15:02:13 +0100821 getGateKeeperService();
822 mSpManager.initWeaverService();
Kenny Rootf76cfc32019-11-08 14:36:03 -0800823 getAuthSecretHal();
824 mDeviceProvisionedObserver.onSystemReady();
825 mRebootEscrowManager.loadRebootEscrowDataIfAvailable();
826 // TODO: maybe skip this for split system user mode.
827 mStorage.prefetchUser(UserHandle.USER_SYSTEM);
828 }
829
830 private void getAuthSecretHal() {
Andrew Sculle6527c12018-01-05 18:33:58 +0000831 try {
Rubin Xucf7dd092020-03-27 15:30:06 +0000832 mAuthSecretService = IAuthSecret.getService(/* retry */ true);
Andrew Sculle6527c12018-01-05 18:33:58 +0000833 } catch (NoSuchElementException e) {
834 Slog.i(TAG, "Device doesn't implement AuthSecret HAL");
835 } catch (RemoteException e) {
836 Slog.w(TAG, "Failed to get AuthSecret HAL", e);
837 }
Amith Yamasani52c489c2012-03-28 11:42:42 -0700838 }
839
840 private void migrateOldData() {
Rubin Xufe354472017-11-21 12:05:06 +0000841 // These Settings moved before multi-user was enabled, so we only have to do it for the
842 // root user.
843 if (getString("migrated", null, 0) == null) {
844 final ContentResolver cr = mContext.getContentResolver();
845 for (String validSetting : VALID_SETTINGS) {
846 String value = Settings.Secure.getString(cr, validSetting);
847 if (value != null) {
848 setString(validSetting, value, 0);
Jim Miller187ec582013-04-15 18:27:54 -0700849 }
Amith Yamasani52c489c2012-03-28 11:42:42 -0700850 }
Rubin Xufe354472017-11-21 12:05:06 +0000851 // No need to move the password / pattern files. They're already in the right place.
852 setString("migrated", "true", 0);
853 Slog.i(TAG, "Migrated lock settings to new location");
854 }
Amith Yamasani52c489c2012-03-28 11:42:42 -0700855
Rubin Xufe354472017-11-21 12:05:06 +0000856 // These Settings changed after multi-user was enabled, hence need to be moved per user.
857 if (getString("migrated_user_specific", null, 0) == null) {
858 final ContentResolver cr = mContext.getContentResolver();
859 List<UserInfo> users = mUserManager.getUsers();
860 for (int user = 0; user < users.size(); user++) {
861 // Migrate owner info
862 final int userId = users.get(user).id;
863 final String OWNER_INFO = Secure.LOCK_SCREEN_OWNER_INFO;
864 String ownerInfo = Settings.Secure.getStringForUser(cr, OWNER_INFO, userId);
865 if (!TextUtils.isEmpty(ownerInfo)) {
866 setString(OWNER_INFO, ownerInfo, userId);
867 Settings.Secure.putStringForUser(cr, OWNER_INFO, "", userId);
Adrian Roos43830582015-04-21 16:04:43 -0700868 }
869
Rubin Xufe354472017-11-21 12:05:06 +0000870 // Migrate owner info enabled. Note there was a bug where older platforms only
871 // stored this value if the checkbox was toggled at least once. The code detects
872 // this case by handling the exception.
873 final String OWNER_INFO_ENABLED = Secure.LOCK_SCREEN_OWNER_INFO_ENABLED;
874 boolean enabled;
Ricky Wai97c8f8d2016-07-13 17:57:45 +0100875 try {
Rubin Xufe354472017-11-21 12:05:06 +0000876 int ivalue = Settings.Secure.getIntForUser(cr, OWNER_INFO_ENABLED, userId);
877 enabled = ivalue != 0;
878 setLong(OWNER_INFO_ENABLED, enabled ? 1 : 0, userId);
879 } catch (SettingNotFoundException e) {
880 // Setting was never stored. Store it if the string is not empty.
881 if (!TextUtils.isEmpty(ownerInfo)) {
882 setLong(OWNER_INFO_ENABLED, 1, userId);
Ricky Wai97c8f8d2016-07-13 17:57:45 +0100883 }
Rubin Xufe354472017-11-21 12:05:06 +0000884 }
885 Settings.Secure.putIntForUser(cr, OWNER_INFO_ENABLED, 0, userId);
886 }
887 // No need to move the password / pattern files. They're already in the right place.
888 setString("migrated_user_specific", "true", 0);
889 Slog.i(TAG, "Migrated per-user lock settings to new location");
890 }
891
892 // Migrates biometric weak such that the fallback mechanism becomes the primary.
893 if (getString("migrated_biometric_weak", null, 0) == null) {
894 List<UserInfo> users = mUserManager.getUsers();
895 for (int i = 0; i < users.size(); i++) {
896 int userId = users.get(i).id;
897 long type = getLong(LockPatternUtils.PASSWORD_TYPE_KEY,
898 DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED,
899 userId);
900 long alternateType = getLong(LockPatternUtils.PASSWORD_TYPE_ALTERNATE_KEY,
901 DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED,
902 userId);
903 if (type == DevicePolicyManager.PASSWORD_QUALITY_BIOMETRIC_WEAK) {
904 setLong(LockPatternUtils.PASSWORD_TYPE_KEY,
905 alternateType,
906 userId);
907 }
908 setLong(LockPatternUtils.PASSWORD_TYPE_ALTERNATE_KEY,
909 DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED,
910 userId);
911 }
912 setString("migrated_biometric_weak", "true", 0);
913 Slog.i(TAG, "Migrated biometric weak to use the fallback instead");
914 }
915
916 // Migrates lockscreen.disabled. Prior to M, the flag was ignored when more than one
917 // user was present on the system, so if we're upgrading to M and there is more than one
918 // user we disable the flag to remain consistent.
919 if (getString("migrated_lockscreen_disabled", null, 0) == null) {
920 final List<UserInfo> users = mUserManager.getUsers();
921 final int userCount = users.size();
922 int switchableUsers = 0;
923 for (int i = 0; i < userCount; i++) {
924 if (users.get(i).supportsSwitchTo()) {
925 switchableUsers++;
Ricky Wai97c8f8d2016-07-13 17:57:45 +0100926 }
Ricky Wai7b9eb412016-05-12 17:29:12 +0100927 }
Greg Plesureb2e4532016-11-02 17:10:27 -0400928
Rubin Xufe354472017-11-21 12:05:06 +0000929 if (switchableUsers > 1) {
Greg Plesureb2e4532016-11-02 17:10:27 -0400930 for (int i = 0; i < userCount; i++) {
931 int id = users.get(i).id;
Rubin Xufe354472017-11-21 12:05:06 +0000932
933 if (getBoolean(LockPatternUtils.DISABLE_LOCKSCREEN_KEY, false, id)) {
934 setBoolean(LockPatternUtils.DISABLE_LOCKSCREEN_KEY, false, id);
935 }
Greg Plesureb2e4532016-11-02 17:10:27 -0400936 }
Greg Plesureb2e4532016-11-02 17:10:27 -0400937 }
Rubin Xufe354472017-11-21 12:05:06 +0000938
939 setString("migrated_lockscreen_disabled", "true", 0);
940 Slog.i(TAG, "Migrated lockscreen disabled flag");
941 }
942
Rubin Xufe354472017-11-21 12:05:06 +0000943 boolean isWatch = mContext.getPackageManager().hasSystemFeature(
944 PackageManager.FEATURE_WATCH);
945 // Wear used to set DISABLE_LOCKSCREEN to 'true', but because Wear now allows accounts
946 // and device management the lockscreen must be re-enabled now for users that upgrade.
947 if (isWatch && getString("migrated_wear_lockscreen_disabled", null, 0) == null) {
Rubin Xu7b76f332019-11-08 12:10:12 +0000948 final List<UserInfo> users = mUserManager.getUsers();
Rubin Xufe354472017-11-21 12:05:06 +0000949 final int userCount = users.size();
950 for (int i = 0; i < userCount; i++) {
951 int id = users.get(i).id;
952 setBoolean(LockPatternUtils.DISABLE_LOCKSCREEN_KEY, false, id);
953 }
954 setString("migrated_wear_lockscreen_disabled", "true", 0);
955 Slog.i(TAG, "Migrated lockscreen_disabled for Wear devices");
Amith Yamasani52c489c2012-03-28 11:42:42 -0700956 }
957 }
958
Adrian Roos60dcbbf2017-08-08 16:19:33 +0200959 private void migrateOldDataAfterSystemReady() {
Rubin Xuca6ece52019-07-31 15:02:13 +0100960 // Migrate the FRP credential to the persistent data block
961 if (LockPatternUtils.frpCredentialEnabled(mContext)
962 && !getBoolean("migrated_frp", false, 0)) {
963 migrateFrpCredential();
964 setBoolean("migrated_frp", true, 0);
965 Slog.i(TAG, "Migrated migrated_frp.");
Adrian Roos60dcbbf2017-08-08 16:19:33 +0200966 }
967 }
968
969 /**
970 * Migrate the credential for the FRP credential owner user if the following are satisfied:
971 * - the user has a secure credential
972 * - the FRP credential is not set up
973 * - the credential is based on a synthetic password.
974 */
Rubin Xuca6ece52019-07-31 15:02:13 +0100975 private void migrateFrpCredential() {
Adrian Roos60dcbbf2017-08-08 16:19:33 +0200976 if (mStorage.readPersistentDataBlock() != PersistentData.NONE) {
977 return;
978 }
979 for (UserInfo userInfo : mUserManager.getUsers()) {
Adrian Roos2adc2632017-09-05 17:01:42 +0200980 if (userOwnsFrpCredential(mContext, userInfo) && isUserSecure(userInfo.id)) {
Adrian Roos60dcbbf2017-08-08 16:19:33 +0200981 synchronized (mSpManager) {
982 if (isSyntheticPasswordBasedCredentialLocked(userInfo.id)) {
983 int actualQuality = (int) getLong(LockPatternUtils.PASSWORD_TYPE_KEY,
984 DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED, userInfo.id);
985
986 mSpManager.migrateFrpPasswordLocked(
987 getSyntheticPasswordHandleLocked(userInfo.id),
988 userInfo,
989 redactActualQualityToMostLenientEquivalentQuality(actualQuality));
990 }
991 }
992 return;
993 }
994 }
995 }
996
997 /**
998 * Returns the lowest password quality that still presents the same UI for entering it.
999 *
1000 * For the FRP credential, we do not want to leak the actual quality of the password, only what
1001 * kind of UI it requires. However, when migrating, we only know the actual quality, not the
1002 * originally requested quality; since this is only used to determine what input variant to
1003 * present to the user, we just assume the lowest possible quality was requested.
1004 */
1005 private int redactActualQualityToMostLenientEquivalentQuality(int quality) {
1006 switch (quality) {
1007 case DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC:
1008 case DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC:
1009 case DevicePolicyManager.PASSWORD_QUALITY_COMPLEX:
1010 return DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC;
1011 case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC:
1012 case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC_COMPLEX:
1013 return DevicePolicyManager.PASSWORD_QUALITY_NUMERIC;
1014 case DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED:
1015 case DevicePolicyManager.PASSWORD_QUALITY_SOMETHING:
1016 case DevicePolicyManager.PASSWORD_QUALITY_MANAGED:
1017 case DevicePolicyManager.PASSWORD_QUALITY_BIOMETRIC_WEAK:
1018 default:
1019 return quality;
1020 }
1021 }
1022
Rubin Xu6cd87c22020-02-20 16:44:27 +00001023 private void enforceFrpResolved() {
Rubin Xuc1073632020-03-27 21:03:01 +00001024 final ContentResolver cr = mContext.getContentResolver();
1025 final boolean inSetupWizard = mInjector.settingsSecureGetInt(cr,
1026 Settings.Secure.USER_SETUP_COMPLETE, 0, UserHandle.USER_SYSTEM) == 0;
1027 final boolean secureFrp = mInjector.settingsSecureGetInt(cr,
1028 Settings.Secure.SECURE_FRP_MODE, 0, UserHandle.USER_SYSTEM) == 1;
1029 if (inSetupWizard && secureFrp) {
1030 throw new SecurityException("Cannot change credential in SUW while factory reset"
1031 + " protection is not resolved yet");
Rubin Xu6cd87c22020-02-20 16:44:27 +00001032 }
1033 }
1034
Jim Miller5ecd8112013-01-09 18:50:26 -08001035 private final void checkWritePermission(int userId) {
Jim Miller505329b2013-11-08 13:25:36 -08001036 mContext.enforceCallingOrSelfPermission(PERMISSION, "LockSettingsWrite");
Amith Yamasani52c489c2012-03-28 11:42:42 -07001037 }
1038
Jim Miller5ecd8112013-01-09 18:50:26 -08001039 private final void checkPasswordReadPermission(int userId) {
Jim Miller505329b2013-11-08 13:25:36 -08001040 mContext.enforceCallingOrSelfPermission(PERMISSION, "LockSettingsRead");
Amith Yamasani52c489c2012-03-28 11:42:42 -07001041 }
1042
Adrian Roosb953e182017-08-17 17:58:26 +02001043 private final void checkPasswordHavePermission(int userId) {
1044 if (mContext.checkCallingOrSelfPermission(PERMISSION) != PERMISSION_GRANTED) {
1045 EventLog.writeEvent(0x534e4554, "28251513", getCallingUid(), ""); // SafetyNet
1046 }
1047 mContext.enforceCallingOrSelfPermission(PERMISSION, "LockSettingsHave");
1048 }
1049
Jim Miller158fe192013-04-17 15:23:55 -07001050 private final void checkReadPermission(String requestedKey, int userId) {
Amith Yamasani52c489c2012-03-28 11:42:42 -07001051 final int callingUid = Binder.getCallingUid();
Adrian Roos001b00d2015-02-24 17:08:48 +01001052
Svetoslav Ganov6d2c0e52015-06-23 16:33:36 +00001053 for (int i = 0; i < READ_CONTACTS_PROTECTED_SETTINGS.length; i++) {
1054 String key = READ_CONTACTS_PROTECTED_SETTINGS[i];
1055 if (key.equals(requestedKey) && mContext.checkCallingOrSelfPermission(READ_CONTACTS)
Jim Miller158fe192013-04-17 15:23:55 -07001056 != PackageManager.PERMISSION_GRANTED) {
1057 throw new SecurityException("uid=" + callingUid
Svetoslav Ganov6d2c0e52015-06-23 16:33:36 +00001058 + " needs permission " + READ_CONTACTS + " to read "
Jim Miller158fe192013-04-17 15:23:55 -07001059 + requestedKey + " for user " + userId);
1060 }
Amith Yamasani52c489c2012-03-28 11:42:42 -07001061 }
Adrian Roos001b00d2015-02-24 17:08:48 +01001062
1063 for (int i = 0; i < READ_PASSWORD_PROTECTED_SETTINGS.length; i++) {
1064 String key = READ_PASSWORD_PROTECTED_SETTINGS[i];
1065 if (key.equals(requestedKey) && mContext.checkCallingOrSelfPermission(PERMISSION)
1066 != PackageManager.PERMISSION_GRANTED) {
1067 throw new SecurityException("uid=" + callingUid
1068 + " needs permission " + PERMISSION + " to read "
1069 + requestedKey + " for user " + userId);
1070 }
1071 }
Amith Yamasani52c489c2012-03-28 11:42:42 -07001072 }
1073
Haining Chenc06c4812020-01-13 20:38:53 -08001074 private final void checkBiometricPermission() {
1075 mContext.enforceCallingOrSelfPermission(BIOMETRIC_PERMISSION, "LockSettingsBiometric");
1076 }
1077
Amith Yamasani52c489c2012-03-28 11:42:42 -07001078 @Override
Rubin Xu3744acf2020-01-02 16:39:50 +00001079 public boolean hasSecureLockScreen() {
1080 return mHasSecureLockScreen;
1081 }
1082
1083 @Override
Rubin Xufe354472017-11-21 12:05:06 +00001084 public boolean getSeparateProfileChallengeEnabled(int userId) {
Ricky Wai7f405f12016-05-31 12:05:05 +01001085 checkReadPermission(SEPARATE_PROFILE_CHALLENGE_KEY, userId);
Rubin Xuba6fef52019-10-25 11:10:43 +01001086 return getSeparateProfileChallengeEnabledInternal(userId);
1087 }
1088
1089 private boolean getSeparateProfileChallengeEnabledInternal(int userId) {
Ricky Waidc283a82016-03-24 19:55:08 +00001090 synchronized (mSeparateChallengeLock) {
Kenny Roota486e2d2020-02-24 08:58:46 -08001091 return mStorage.getBoolean(SEPARATE_PROFILE_CHALLENGE_KEY, false, userId);
Ricky Waidc283a82016-03-24 19:55:08 +00001092 }
1093 }
1094
1095 @Override
1096 public void setSeparateProfileChallengeEnabled(int userId, boolean enabled,
Rubin Xubb883202019-10-09 11:22:53 +01001097 LockscreenCredential managedUserPassword) {
Ricky Wai7f405f12016-05-31 12:05:05 +01001098 checkWritePermission(userId);
Rubin Xu3744acf2020-01-02 16:39:50 +00001099 if (!mHasSecureLockScreen) {
Lenka Trochtova66c492a2018-12-06 11:29:21 +01001100 throw new UnsupportedOperationException(
1101 "This operation requires secure lock screen feature.");
1102 }
Ricky Waidc283a82016-03-24 19:55:08 +00001103 synchronized (mSeparateChallengeLock) {
Rubin Xubb883202019-10-09 11:22:53 +01001104 setSeparateProfileChallengeEnabledLocked(userId, enabled, managedUserPassword != null
1105 ? managedUserPassword : LockscreenCredential.createNone());
Ricky Waidc283a82016-03-24 19:55:08 +00001106 }
Pavel Grafov28939982017-10-03 15:11:52 +01001107 notifySeparateProfileChallengeChanged(userId);
1108 }
1109
1110 @GuardedBy("mSeparateChallengeLock")
Rich Canningsf64ec632019-02-21 12:40:36 -08001111 private void setSeparateProfileChallengeEnabledLocked(@UserIdInt int userId,
Rubin Xubb883202019-10-09 11:22:53 +01001112 boolean enabled, LockscreenCredential managedUserPassword) {
Pavel Grafovf10ae7e2018-06-25 12:13:38 +01001113 final boolean old = getBoolean(SEPARATE_PROFILE_CHALLENGE_KEY, false, userId);
Pavel Grafov28939982017-10-03 15:11:52 +01001114 setBoolean(SEPARATE_PROFILE_CHALLENGE_KEY, enabled, userId);
Pavel Grafovf10ae7e2018-06-25 12:13:38 +01001115 try {
1116 if (enabled) {
1117 mStorage.removeChildProfileLock(userId);
1118 removeKeystoreProfileKey(userId);
1119 } else {
1120 tieManagedProfileLockIfNecessary(userId, managedUserPassword);
1121 }
1122 } catch (IllegalStateException e) {
1123 setBoolean(SEPARATE_PROFILE_CHALLENGE_KEY, old, userId);
1124 throw e;
Pavel Grafov28939982017-10-03 15:11:52 +01001125 }
1126 }
1127
1128 private void notifySeparateProfileChallengeChanged(int userId) {
Rubin Xu0f1e56d2019-08-23 13:34:25 +01001129 // LSS cannot call into DPM directly, otherwise it will cause deadlock.
1130 // In this case, calling DPM on a handler thread is OK since DPM doesn't
1131 // expect reportSeparateProfileChallengeChanged() to happen synchronously.
1132 mHandler.post(() -> {
1133 final DevicePolicyManagerInternal dpmi = LocalServices.getService(
1134 DevicePolicyManagerInternal.class);
1135 if (dpmi != null) {
1136 dpmi.reportSeparateProfileChallengeChanged(userId);
1137 }
1138 });
Ricky Waidc283a82016-03-24 19:55:08 +00001139 }
1140
1141 @Override
Rubin Xufe354472017-11-21 12:05:06 +00001142 public void setBoolean(String key, boolean value, int userId) {
Amith Yamasani52c489c2012-03-28 11:42:42 -07001143 checkWritePermission(userId);
Kenny Roota486e2d2020-02-24 08:58:46 -08001144 mStorage.setBoolean(key, value, userId);
Amith Yamasani52c489c2012-03-28 11:42:42 -07001145 }
1146
1147 @Override
Rubin Xufe354472017-11-21 12:05:06 +00001148 public void setLong(String key, long value, int userId) {
Amith Yamasani52c489c2012-03-28 11:42:42 -07001149 checkWritePermission(userId);
Kenny Roota486e2d2020-02-24 08:58:46 -08001150 mStorage.setLong(key, value, userId);
Rubin Xu066ce2f2019-11-29 17:17:46 +00001151 }
1152
Amith Yamasani52c489c2012-03-28 11:42:42 -07001153 @Override
Rubin Xufe354472017-11-21 12:05:06 +00001154 public void setString(String key, String value, int userId) {
Amith Yamasani52c489c2012-03-28 11:42:42 -07001155 checkWritePermission(userId);
Kenny Roota486e2d2020-02-24 08:58:46 -08001156 mStorage.setString(key, value, userId);
Amith Yamasani52c489c2012-03-28 11:42:42 -07001157 }
1158
1159 @Override
Adrian Roos60dcbbf2017-08-08 16:19:33 +02001160 public boolean getBoolean(String key, boolean defaultValue, int userId) {
Jim Miller158fe192013-04-17 15:23:55 -07001161 checkReadPermission(key, userId);
Kenny Roota486e2d2020-02-24 08:58:46 -08001162 if (Settings.Secure.LOCK_PATTERN_ENABLED.equals(key)) {
1163 return getCredentialTypeInternal(userId) == CREDENTIAL_TYPE_PATTERN;
1164 }
1165 return mStorage.getBoolean(key, defaultValue, userId);
Amith Yamasani52c489c2012-03-28 11:42:42 -07001166 }
1167
1168 @Override
Adrian Roos60dcbbf2017-08-08 16:19:33 +02001169 public long getLong(String key, long defaultValue, int userId) {
Jim Miller158fe192013-04-17 15:23:55 -07001170 checkReadPermission(key, userId);
Kenny Roota486e2d2020-02-24 08:58:46 -08001171 return mStorage.getLong(key, defaultValue, userId);
Rubin Xu066ce2f2019-11-29 17:17:46 +00001172 }
1173
Amith Yamasani52c489c2012-03-28 11:42:42 -07001174 @Override
Adrian Roos60dcbbf2017-08-08 16:19:33 +02001175 public String getString(String key, String defaultValue, int userId) {
Jim Miller158fe192013-04-17 15:23:55 -07001176 checkReadPermission(key, userId);
Kenny Roota486e2d2020-02-24 08:58:46 -08001177 return mStorage.getString(key, defaultValue, userId);
Amith Yamasani52c489c2012-03-28 11:42:42 -07001178 }
1179
Rubin Xu5e891bc2019-10-14 10:22:23 +01001180 private void setKeyguardStoredQuality(int quality, int userId) {
1181 if (DEBUG) Slog.d(TAG, "setKeyguardStoredQuality: user=" + userId + " quality=" + quality);
Kenny Roota486e2d2020-02-24 08:58:46 -08001182 mStorage.setLong(LockPatternUtils.PASSWORD_TYPE_KEY, quality, userId);
Adrian Roos7374d3a2017-03-31 14:14:53 -07001183 }
1184
Rubin Xu5e891bc2019-10-14 10:22:23 +01001185 private int getKeyguardStoredQuality(int userId) {
Kenny Roota486e2d2020-02-24 08:58:46 -08001186 return (int) mStorage.getLong(LockPatternUtils.PASSWORD_TYPE_KEY,
Rubin Xu5e891bc2019-10-14 10:22:23 +01001187 DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED, userId);
Adrian Roos7374d3a2017-03-31 14:14:53 -07001188 }
1189
Adrian Roos4f788452014-05-22 20:45:59 +02001190 @Override
Rubin Xu5e891bc2019-10-14 10:22:23 +01001191 public int getCredentialType(int userId) {
Adrian Roosb953e182017-08-17 17:58:26 +02001192 checkPasswordHavePermission(userId);
Rubin Xu5e891bc2019-10-14 10:22:23 +01001193 return getCredentialTypeInternal(userId);
Amith Yamasani52c489c2012-03-28 11:42:42 -07001194 }
1195
Rubin Xu5e891bc2019-10-14 10:22:23 +01001196 // TODO: this is a hot path, can we optimize it?
1197 /**
1198 * Returns the credential type of the user, can be one of {@link #CREDENTIAL_TYPE_NONE},
1199 * {@link #CREDENTIAL_TYPE_PATTERN}, {@link #CREDENTIAL_TYPE_PIN} and
1200 * {@link #CREDENTIAL_TYPE_PASSWORD}
1201 */
1202 public int getCredentialTypeInternal(int userId) {
1203 if (userId == USER_FRP) {
1204 return getFrpCredentialType();
1205 }
Rubin Xu3bf722a2016-12-15 16:07:38 +00001206 synchronized (mSpManager) {
1207 if (isSyntheticPasswordBasedCredentialLocked(userId)) {
Pavel Grafov19a4fb32019-03-15 12:55:12 +00001208 final long handle = getSyntheticPasswordHandleLocked(userId);
Rubin Xu5e891bc2019-10-14 10:22:23 +01001209 int rawType = mSpManager.getCredentialType(handle, userId);
1210 if (rawType != CREDENTIAL_TYPE_PASSWORD_OR_PIN) {
1211 return rawType;
1212 }
1213 return pinOrPasswordQualityToCredentialType(getKeyguardStoredQuality(userId));
Rubin Xu3bf722a2016-12-15 16:07:38 +00001214 }
1215 }
Rubin Xu5e891bc2019-10-14 10:22:23 +01001216 // Intentional duplication of the getKeyguardStoredQuality() call above since this is a
1217 // unlikely code path (device with pre-synthetic password credential). We want to skip
1218 // calling getKeyguardStoredQuality whenever possible.
1219 final int savedQuality = getKeyguardStoredQuality(userId);
1220 if (savedQuality == DevicePolicyManager.PASSWORD_QUALITY_SOMETHING
1221 && mStorage.hasPattern(userId)) {
1222 return CREDENTIAL_TYPE_PATTERN;
1223 }
1224 if (savedQuality >= DevicePolicyManager.PASSWORD_QUALITY_NUMERIC
1225 && mStorage.hasPassword(userId)) {
1226 return pinOrPasswordQualityToCredentialType(savedQuality);
1227 }
1228 return CREDENTIAL_TYPE_NONE;
1229 }
1230
1231 private int getFrpCredentialType() {
1232 PersistentData data = mStorage.readPersistentDataBlock();
1233 if (data.type != PersistentData.TYPE_SP && data.type != PersistentData.TYPE_SP_WEAVER) {
1234 return CREDENTIAL_TYPE_NONE;
1235 }
1236 int credentialType = SyntheticPasswordManager.getFrpCredentialType(data.payload);
1237 if (credentialType != CREDENTIAL_TYPE_PASSWORD_OR_PIN) {
1238 return credentialType;
1239 }
1240 return pinOrPasswordQualityToCredentialType(data.qualityForUi);
1241 }
1242
1243 private static int pinOrPasswordQualityToCredentialType(int quality) {
1244 if (LockPatternUtils.isQualityAlphabeticPassword(quality)) {
1245 return CREDENTIAL_TYPE_PASSWORD;
1246 }
1247 if (LockPatternUtils.isQualityNumericPin(quality)) {
1248 return CREDENTIAL_TYPE_PIN;
1249 }
1250 throw new IllegalArgumentException("Quality is neither Pin nor password: " + quality);
Amith Yamasani52c489c2012-03-28 11:42:42 -07001251 }
1252
Rubin Xua55b1682017-01-31 10:06:56 +00001253 private boolean isUserSecure(int userId) {
Rubin Xu5e891bc2019-10-14 10:22:23 +01001254 return getCredentialTypeInternal(userId) != CREDENTIAL_TYPE_NONE;
Rubin Xua55b1682017-01-31 10:06:56 +00001255 }
1256
Rich Canningsf64ec632019-02-21 12:40:36 -08001257 private void setKeystorePassword(byte[] password, int userHandle) {
Robin Leef0246a82014-08-13 09:50:25 +01001258 final KeyStore ks = KeyStore.getInstance();
Rich Canningsf64ec632019-02-21 12:40:36 -08001259 // TODO(b/120484642): Update keystore to accept byte[] passwords
1260 String passwordString = password == null ? null : new String(password);
1261 ks.onUserPasswordChanged(userHandle, passwordString);
Chad Brubakera91a8502015-05-07 10:02:22 -07001262 }
1263
Rich Canningsf64ec632019-02-21 12:40:36 -08001264 private void unlockKeystore(byte[] password, int userHandle) {
Ricky Waidc283a82016-03-24 19:55:08 +00001265 if (DEBUG) Slog.v(TAG, "Unlock keystore for user: " + userHandle);
Rich Canningsf64ec632019-02-21 12:40:36 -08001266 // TODO(b/120484642): Update keystore to accept byte[] passwords
1267 String passwordString = password == null ? null : new String(password);
Chad Brubakera91a8502015-05-07 10:02:22 -07001268 final KeyStore ks = KeyStore.getInstance();
Rich Canningsf64ec632019-02-21 12:40:36 -08001269 ks.unlock(userHandle, passwordString);
Ricky Waidc283a82016-03-24 19:55:08 +00001270 }
Chad Brubakera91a8502015-05-07 10:02:22 -07001271
Rubin Xubb883202019-10-09 11:22:53 +01001272 @VisibleForTesting /** Note: this method is overridden in unit tests */
1273 protected LockscreenCredential getDecryptedPasswordForTiedProfile(int userId)
Ricky Waidc283a82016-03-24 19:55:08 +00001274 throws KeyStoreException, UnrecoverableKeyException,
1275 NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
1276 InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException,
1277 CertificateException, IOException {
Rich Canningsf64ec632019-02-21 12:40:36 -08001278 if (DEBUG) Slog.v(TAG, "Get child profile decrypted key");
Ricky Waidc283a82016-03-24 19:55:08 +00001279 byte[] storedData = mStorage.readChildProfileLock(userId);
1280 if (storedData == null) {
1281 throw new FileNotFoundException("Child profile lock file not found");
1282 }
1283 byte[] iv = Arrays.copyOfRange(storedData, 0, PROFILE_KEY_IV_SIZE);
1284 byte[] encryptedPassword = Arrays.copyOfRange(storedData, PROFILE_KEY_IV_SIZE,
1285 storedData.length);
1286 byte[] decryptionResult;
1287 java.security.KeyStore keyStore = java.security.KeyStore.getInstance("AndroidKeyStore");
1288 keyStore.load(null);
1289 SecretKey decryptionKey = (SecretKey) keyStore.getKey(
Ricky Waid3982442016-05-24 19:27:08 +01001290 LockPatternUtils.PROFILE_KEY_NAME_DECRYPT + userId, null);
Ricky Waidc283a82016-03-24 19:55:08 +00001291
1292 Cipher cipher = Cipher.getInstance(KeyProperties.KEY_ALGORITHM_AES + "/"
1293 + KeyProperties.BLOCK_MODE_GCM + "/" + KeyProperties.ENCRYPTION_PADDING_NONE);
1294
1295 cipher.init(Cipher.DECRYPT_MODE, decryptionKey, new GCMParameterSpec(128, iv));
1296 decryptionResult = cipher.doFinal(encryptedPassword);
Rubin Xubb883202019-10-09 11:22:53 +01001297 LockscreenCredential credential = LockscreenCredential.createManagedPassword(
1298 decryptionResult);
1299 Arrays.fill(decryptionResult, (byte) 0);
Rubin Xua3c71a12019-12-04 15:25:02 +00001300 mManagedProfilePasswordCache.storePassword(userId, credential);
Rubin Xubb883202019-10-09 11:22:53 +01001301 return credential;
Ricky Waidc283a82016-03-24 19:55:08 +00001302 }
1303
Kevin Chyn97d0a5b2019-06-11 12:52:17 -07001304 private void unlockChildProfile(int profileHandle, boolean ignoreUserNotAuthenticated,
Kevin Chynbc29dd72019-06-13 11:47:54 -07001305 @ChallengeType int challengeType, long challenge,
Rubin Xuca6ece52019-07-31 15:02:13 +01001306 @Nullable ArrayList<PendingResetLockout> resetLockouts) {
Ricky Waidc283a82016-03-24 19:55:08 +00001307 try {
Rubin Xu1de89b32016-11-30 20:03:13 +00001308 doVerifyCredential(getDecryptedPasswordForTiedProfile(profileHandle),
Kevin Chynbc29dd72019-06-13 11:47:54 -07001309 challengeType, challenge, profileHandle, null /* progressCallback */,
1310 resetLockouts);
Ricky Waidc283a82016-03-24 19:55:08 +00001311 } catch (UnrecoverableKeyException | InvalidKeyException | KeyStoreException
1312 | NoSuchAlgorithmException | NoSuchPaddingException
1313 | InvalidAlgorithmParameterException | IllegalBlockSizeException
1314 | BadPaddingException | CertificateException | IOException e) {
1315 if (e instanceof FileNotFoundException) {
1316 Slog.i(TAG, "Child profile key not found");
Pavel Grafov0acc4bf2017-08-23 12:20:54 +01001317 } else if (ignoreUserNotAuthenticated && e instanceof UserNotAuthenticatedException) {
1318 Slog.i(TAG, "Parent keystore seems locked, ignoring");
Clara Bayarri0a587d22016-02-23 14:49:41 -08001319 } else {
Ricky Waidc283a82016-03-24 19:55:08 +00001320 Slog.e(TAG, "Failed to decrypt child profile key", e);
Clara Bayarri0a587d22016-02-23 14:49:41 -08001321 }
Jim Millerde1af082013-09-11 14:58:26 -07001322 }
1323 }
1324
Kevin Chyn97d0a5b2019-06-11 12:52:17 -07001325 private void unlockUser(int userId, byte[] token, byte[] secret) {
Kevin Chynbc29dd72019-06-13 11:47:54 -07001326 unlockUser(userId, token, secret, CHALLENGE_NONE, 0 /* challenge */, null);
Kevin Chyn97d0a5b2019-06-11 12:52:17 -07001327 }
1328
Rubin Xuca7007b2019-03-25 11:44:41 +00001329 /**
1330 * Unlock the user (both storage and user state) and its associated managed profiles
1331 * synchronously.
1332 *
1333 * <em>Be very careful about the risk of deadlock here: ActivityManager.unlockUser()
1334 * can end up calling into other system services to process user unlock request (via
1335 * {@link com.android.server.SystemServiceManager#unlockUser} </em>
1336 */
Kevin Chyn97d0a5b2019-06-11 12:52:17 -07001337 private void unlockUser(int userId, byte[] token, byte[] secret,
Kevin Chynbc29dd72019-06-13 11:47:54 -07001338 @ChallengeType int challengeType, long challenge,
1339 @Nullable ArrayList<PendingResetLockout> resetLockouts) {
Rubin Xu8a692732019-12-06 14:13:14 +00001340 Slog.i(TAG, "Unlocking user " + userId + " with secret only, length "
1341 + (secret != null ? secret.length : 0));
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06001342 // TODO: make this method fully async so we can update UI with progress strings
Pavel Grafovb9b2c692019-05-24 14:07:55 +01001343 final boolean alreadyUnlocked = mUserManager.isUserUnlockingOrUnlocked(userId);
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06001344 final CountDownLatch latch = new CountDownLatch(1);
1345 final IProgressListener listener = new IProgressListener.Stub() {
1346 @Override
1347 public void onStarted(int id, Bundle extras) throws RemoteException {
Rubin Xue1beaf02019-10-22 11:36:51 +01001348 Slog.d(TAG, "unlockUser started");
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06001349 }
1350
1351 @Override
1352 public void onProgress(int id, int progress, Bundle extras) throws RemoteException {
Rubin Xue1beaf02019-10-22 11:36:51 +01001353 Slog.d(TAG, "unlockUser progress " + progress);
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06001354 }
1355
1356 @Override
1357 public void onFinished(int id, Bundle extras) throws RemoteException {
Rubin Xue1beaf02019-10-22 11:36:51 +01001358 Slog.d(TAG, "unlockUser finished");
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06001359 latch.countDown();
1360 }
1361 };
1362
Jeff Sharkey8924e872015-11-30 12:52:10 -07001363 try {
Rubin Xu0cbc19e2016-12-09 14:00:21 +00001364 mActivityManager.unlockUser(userId, token, secret, listener);
Jeff Sharkey8924e872015-11-30 12:52:10 -07001365 } catch (RemoteException e) {
1366 throw e.rethrowAsRuntimeException();
1367 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06001368
1369 try {
1370 latch.await(15, TimeUnit.SECONDS);
1371 } catch (InterruptedException e) {
1372 Thread.currentThread().interrupt();
1373 }
Pavel Grafovb9b2c692019-05-24 14:07:55 +01001374
1375 if (mUserManager.getUserInfo(userId).isManagedProfile()) {
1376 return;
1377 }
1378
1379 for (UserInfo profile : mUserManager.getProfiles(userId)) {
Rubin Xua3c71a12019-12-04 15:25:02 +00001380 if (profile.id == userId) continue;
1381 if (!profile.isManagedProfile()) continue;
1382
1383 if (hasUnifiedChallenge(profile.id)) {
1384 if (mUserManager.isUserRunning(profile.id)) {
1385 // Unlock managed profile with unified lock
1386 // Must pass the challenge on for resetLockout, so it's not over-written, which
1387 // causes LockSettingsService to revokeChallenge inappropriately.
1388 unlockChildProfile(profile.id, false /* ignoreUserNotAuthenticated */,
1389 challengeType, challenge, resetLockouts);
1390 } else {
1391 try {
1392 // Profile not ready for unlock yet, but decrypt the unified challenge now
1393 // so it goes into the cache
1394 getDecryptedPasswordForTiedProfile(profile.id);
1395 } catch (GeneralSecurityException | IOException e) {
1396 Slog.d(TAG, "Cache work profile password failed", e);
1397 }
1398 }
Ricky Waidc283a82016-03-24 19:55:08 +00001399 }
Pavel Grafovb9b2c692019-05-24 14:07:55 +01001400 // Now we have unlocked the parent user and attempted to unlock the profile we should
1401 // show notifications if the profile is still locked.
1402 if (!alreadyUnlocked) {
1403 long ident = clearCallingIdentity();
1404 try {
1405 maybeShowEncryptionNotificationForUser(profile.id);
1406 } finally {
1407 restoreCallingIdentity(ident);
1408 }
1409 }
1410
Ricky Waidc283a82016-03-24 19:55:08 +00001411 }
Kevin Chynbc29dd72019-06-13 11:47:54 -07001412
1413 if (resetLockouts != null && !resetLockouts.isEmpty()) {
1414 mHandler.post(() -> {
1415 final BiometricManager bm = mContext.getSystemService(BiometricManager.class);
1416 final PackageManager pm = mContext.getPackageManager();
1417 for (int i = 0; i < resetLockouts.size(); i++) {
Kevin Chyn91c70b62019-06-13 13:20:41 -07001418 bm.setActiveUser(resetLockouts.get(i).mUserId);
Kevin Chynbc29dd72019-06-13 11:47:54 -07001419 bm.resetLockout(resetLockouts.get(i).mHAT);
1420 }
1421 if (challengeType == CHALLENGE_INTERNAL
1422 && pm.hasSystemFeature(PackageManager.FEATURE_FACE)) {
1423 mContext.getSystemService(FaceManager.class).revokeChallenge();
1424 }
1425 });
1426 }
Jeff Sharkey8924e872015-11-30 12:52:10 -07001427 }
Amith Yamasani52c489c2012-03-28 11:42:42 -07001428
Rubin Xua3c71a12019-12-04 15:25:02 +00001429 private boolean hasUnifiedChallenge(int userId) {
1430 return !getSeparateProfileChallengeEnabledInternal(userId)
1431 && mStorage.hasChildProfileLock(userId);
Pavel Grafov0acc4bf2017-08-23 12:20:54 +01001432 }
1433
Rubin Xubb883202019-10-09 11:22:53 +01001434 private Map<Integer, LockscreenCredential> getDecryptedPasswordsForAllTiedProfiles(int userId) {
Rubin Xua55b1682017-01-31 10:06:56 +00001435 if (mUserManager.getUserInfo(userId).isManagedProfile()) {
1436 return null;
Andres Morales8fa56652015-03-31 09:19:50 -07001437 }
Rubin Xubb883202019-10-09 11:22:53 +01001438 Map<Integer, LockscreenCredential> result = new ArrayMap<>();
Rubin Xua55b1682017-01-31 10:06:56 +00001439 final List<UserInfo> profiles = mUserManager.getProfiles(userId);
1440 final int size = profiles.size();
1441 for (int i = 0; i < size; i++) {
1442 final UserInfo profile = profiles.get(i);
1443 if (!profile.isManagedProfile()) {
1444 continue;
1445 }
1446 final int managedUserId = profile.id;
Rubin Xu3744acf2020-01-02 16:39:50 +00001447 if (getSeparateProfileChallengeEnabledInternal(managedUserId)) {
Rubin Xua55b1682017-01-31 10:06:56 +00001448 continue;
1449 }
1450 try {
Rubin Xu4f988c92017-09-12 16:25:26 +01001451 result.put(managedUserId, getDecryptedPasswordForTiedProfile(managedUserId));
Rubin Xua55b1682017-01-31 10:06:56 +00001452 } catch (KeyStoreException | UnrecoverableKeyException | NoSuchAlgorithmException
1453 | NoSuchPaddingException | InvalidKeyException
1454 | InvalidAlgorithmParameterException | IllegalBlockSizeException
1455 | BadPaddingException | CertificateException | IOException e) {
Rubin Xu4f988c92017-09-12 16:25:26 +01001456 Slog.e(TAG, "getDecryptedPasswordsForAllTiedProfiles failed for user " +
1457 managedUserId, e);
Rubin Xua55b1682017-01-31 10:06:56 +00001458 }
1459 }
1460 return result;
Amith Yamasani52c489c2012-03-28 11:42:42 -07001461 }
1462
Rubin Xua55b1682017-01-31 10:06:56 +00001463 /**
1464 * Synchronize all profile's work challenge of the given user if it's unified: tie or clear them
1465 * depending on the parent user's secure state.
1466 *
1467 * When clearing tied work challenges, a pre-computed password table for profiles are required,
1468 * since changing password for profiles requires existing password, and existing passwords can
1469 * only be computed before the parent user's password is cleared.
1470 *
1471 * Strictly this is a recursive function, since setLockCredentialInternal ends up calling this
1472 * method again on profiles. However the recursion is guaranteed to terminate as this method
1473 * terminates when the user is a managed profile.
1474 */
1475 private void synchronizeUnifiedWorkChallengeForProfiles(int userId,
Rubin Xubb883202019-10-09 11:22:53 +01001476 Map<Integer, LockscreenCredential> profilePasswordMap) {
Ricky Waidc283a82016-03-24 19:55:08 +00001477 if (mUserManager.getUserInfo(userId).isManagedProfile()) {
1478 return;
1479 }
Rubin Xua55b1682017-01-31 10:06:56 +00001480 final boolean isSecure = isUserSecure(userId);
Ricky Waidc283a82016-03-24 19:55:08 +00001481 final List<UserInfo> profiles = mUserManager.getProfiles(userId);
1482 final int size = profiles.size();
1483 for (int i = 0; i < size; i++) {
1484 final UserInfo profile = profiles.get(i);
1485 if (profile.isManagedProfile()) {
1486 final int managedUserId = profile.id;
Rubin Xu3744acf2020-01-02 16:39:50 +00001487 if (getSeparateProfileChallengeEnabledInternal(managedUserId)) {
Ricky Waidc283a82016-03-24 19:55:08 +00001488 continue;
1489 }
1490 if (isSecure) {
Rubin Xubb883202019-10-09 11:22:53 +01001491 tieManagedProfileLockIfNecessary(managedUserId,
1492 LockscreenCredential.createNone());
Ricky Waidc283a82016-03-24 19:55:08 +00001493 } else {
Rubin Xua55b1682017-01-31 10:06:56 +00001494 // We use cached work profile password computed before clearing the parent's
1495 // credential, otherwise they get lost
Rubin Xubb883202019-10-09 11:22:53 +01001496 if (profilePasswordMap != null
1497 && profilePasswordMap.containsKey(managedUserId)) {
1498 setLockCredentialInternal(LockscreenCredential.createNone(),
Adrian Roos7374d3a2017-03-31 14:14:53 -07001499 profilePasswordMap.get(managedUserId),
Rubin Xubb883202019-10-09 11:22:53 +01001500 managedUserId,
Rubin Xud9522402019-11-06 13:54:27 +00001501 /* isLockTiedToParent= */ true);
1502 mStorage.removeChildProfileLock(managedUserId);
1503 removeKeystoreProfileKey(managedUserId);
Rubin Xua55b1682017-01-31 10:06:56 +00001504 } else {
Rubin Xud9522402019-11-06 13:54:27 +00001505 Slog.wtf(TAG, "Attempt to clear tied challenge, but no password supplied.");
Rubin Xua55b1682017-01-31 10:06:56 +00001506 }
Ricky Waidc283a82016-03-24 19:55:08 +00001507 }
1508 }
1509 }
1510 }
Andres Morales8fa56652015-03-31 09:19:50 -07001511
Ricky Waidc283a82016-03-24 19:55:08 +00001512 private boolean isManagedProfileWithUnifiedLock(int userId) {
1513 return mUserManager.getUserInfo(userId).isManagedProfile()
Rubin Xu3744acf2020-01-02 16:39:50 +00001514 && !getSeparateProfileChallengeEnabledInternal(userId);
Ricky Waidc283a82016-03-24 19:55:08 +00001515 }
1516
1517 private boolean isManagedProfileWithSeparatedLock(int userId) {
1518 return mUserManager.getUserInfo(userId).isManagedProfile()
Rubin Xu3744acf2020-01-02 16:39:50 +00001519 && getSeparateProfileChallengeEnabledInternal(userId);
Ricky Waidc283a82016-03-24 19:55:08 +00001520 }
1521
Annie Meng086ddc82019-03-29 17:43:35 +00001522 /**
1523 * Send credentials for user {@code userId} to {@link RecoverableKeyStoreManager} during an
1524 * unlock operation.
1525 */
Rubin Xubb883202019-10-09 11:22:53 +01001526 private void sendCredentialsOnUnlockIfRequired(LockscreenCredential credential, int userId) {
Annie Meng086ddc82019-03-29 17:43:35 +00001527 // Don't send credentials during the factory reset protection flow.
1528 if (userId == USER_FRP) {
1529 return;
1530 }
1531
1532 // A profile with a unified lock screen stores a randomly generated credential, so skip it.
1533 // Its parent will send credentials for the profile, as it stores the unified lock
1534 // credential.
1535 if (isManagedProfileWithUnifiedLock(userId)) {
1536 return;
1537 }
1538
Rubin Xubb883202019-10-09 11:22:53 +01001539 // RecoverableKeyStoreManager expects null for empty credential.
1540 final byte[] secret = credential.isNone() ? null : credential.getCredential();
Annie Meng086ddc82019-03-29 17:43:35 +00001541 // Send credentials for the user and any child profiles that share its lock screen.
1542 for (int profileId : getProfilesWithSameLockScreen(userId)) {
1543 mRecoverableKeyStoreManager.lockScreenSecretAvailable(
Rubin Xubb883202019-10-09 11:22:53 +01001544 credential.getType(), secret, profileId);
Annie Meng086ddc82019-03-29 17:43:35 +00001545 }
1546 }
1547
1548 /**
1549 * Send credentials for user {@code userId} to {@link RecoverableKeyStoreManager} when its
1550 * credentials are set/changed.
1551 */
1552 private void sendCredentialsOnChangeIfRequired(
Rubin Xubb883202019-10-09 11:22:53 +01001553 LockscreenCredential credential, int userId, boolean isLockTiedToParent) {
Annie Meng086ddc82019-03-29 17:43:35 +00001554 // A profile whose lock screen is being tied to its parent's will either have a randomly
1555 // generated credential (creation) or null (removal). We rely on the parent to send its
1556 // credentials for the profile in both cases as it stores the unified lock credential.
1557 if (isLockTiedToParent) {
1558 return;
1559 }
1560
Rubin Xubb883202019-10-09 11:22:53 +01001561 // RecoverableKeyStoreManager expects null for empty credential.
1562 final byte[] secret = credential.isNone() ? null : credential.getCredential();
Annie Meng086ddc82019-03-29 17:43:35 +00001563 // Send credentials for the user and any child profiles that share its lock screen.
1564 for (int profileId : getProfilesWithSameLockScreen(userId)) {
1565 mRecoverableKeyStoreManager.lockScreenSecretChanged(
Rubin Xubb883202019-10-09 11:22:53 +01001566 credential.getType(), secret, profileId);
Annie Meng086ddc82019-03-29 17:43:35 +00001567 }
1568 }
1569
1570 /**
1571 * Returns all profiles of {@code userId}, including itself, that have the same lock screen
1572 * challenge.
1573 */
1574 private Set<Integer> getProfilesWithSameLockScreen(int userId) {
1575 Set<Integer> profiles = new ArraySet<>();
1576 for (UserInfo profile : mUserManager.getProfiles(userId)) {
1577 if (profile.id == userId
1578 || (profile.profileGroupId == userId
1579 && isManagedProfileWithUnifiedLock(profile.id))) {
1580 profiles.add(profile.id);
1581 }
1582 }
1583 return profiles;
1584 }
1585
Ricky Waidc283a82016-03-24 19:55:08 +00001586 // This method should be called by LockPatternUtil only, all internal methods in this class
Rubin Xu1de89b32016-11-30 20:03:13 +00001587 // should call setLockCredentialInternal.
Amith Yamasani52c489c2012-03-28 11:42:42 -07001588 @Override
Rubin Xubb883202019-10-09 11:22:53 +01001589 public boolean setLockCredential(LockscreenCredential credential,
Rubin Xud9522402019-11-06 13:54:27 +00001590 LockscreenCredential savedCredential, int userId) {
Rich Canningsf64ec632019-02-21 12:40:36 -08001591
Rubin Xu3744acf2020-01-02 16:39:50 +00001592 if (!mHasSecureLockScreen) {
Lenka Trochtova66c492a2018-12-06 11:29:21 +01001593 throw new UnsupportedOperationException(
1594 "This operation requires secure lock screen feature");
1595 }
Jim Millere484eaf2016-04-13 16:35:36 -07001596 checkWritePermission(userId);
Rubin Xu6cd87c22020-02-20 16:44:27 +00001597 enforceFrpResolved();
Rubin Xu0090c582020-03-06 14:34:16 +00001598
1599 // When changing credential for profiles with unified challenge, some callers
1600 // will pass in empty credential while others will pass in the credential of
1601 // the parent user. setLockCredentialInternal() handles the formal case (empty
1602 // credential) correctly but not the latter. As a stopgap fix, convert the latter
1603 // case to the formal. The long-term fix would be fixing LSS such that it should
1604 // accept only the parent user credential on its public API interfaces, swap it
1605 // with the profile's random credential at that API boundary (i.e. here) and make
1606 // sure LSS internally does not special case profile with unififed challenge: b/80170828.
1607 if (!savedCredential.isNone() && isManagedProfileWithUnifiedLock(userId)) {
1608 // Verify the parent credential again, to make sure we have a fresh enough
1609 // auth token such that getDecryptedPasswordForTiedProfile() inside
1610 // setLockCredentialInternal() can function correctly.
1611 verifyCredential(savedCredential, /* challenge */ 0,
1612 mUserManager.getProfileParent(userId).id);
1613 savedCredential.zeroize();
1614 savedCredential = LockscreenCredential.createNone();
1615 }
Ricky Waidc283a82016-03-24 19:55:08 +00001616 synchronized (mSeparateChallengeLock) {
Rubin Xubb883202019-10-09 11:22:53 +01001617 if (!setLockCredentialInternal(credential, savedCredential,
Rubin Xud9522402019-11-06 13:54:27 +00001618 userId, /* isLockTiedToParent= */ false)) {
Rubin Xu6a7303d2019-08-16 13:19:56 +01001619 return false;
1620 }
Rubin Xubb883202019-10-09 11:22:53 +01001621 setSeparateProfileChallengeEnabledLocked(userId, true, /* unused */ null);
Andrew Scull5daf2732016-11-14 15:02:45 +00001622 notifyPasswordChanged(userId);
Ricky Waidc283a82016-03-24 19:55:08 +00001623 }
Pavel Grafova8da6972019-04-03 13:58:58 +01001624 if (mUserManager.getUserInfo(userId).isManagedProfile()) {
1625 // Make sure the profile doesn't get locked straight after setting work challenge.
1626 setDeviceUnlockedForUser(userId);
1627 }
Pavel Grafov28939982017-10-03 15:11:52 +01001628 notifySeparateProfileChallengeChanged(userId);
Rubin Xu6a7303d2019-08-16 13:19:56 +01001629 return true;
Ricky Waidc283a82016-03-24 19:55:08 +00001630 }
1631
Annie Meng086ddc82019-03-29 17:43:35 +00001632 /**
Rubin Xubb883202019-10-09 11:22:53 +01001633 * @param savedCredential if the user is a managed profile with unified challenge and
1634 * savedCredential is empty, LSS will try to re-derive the profile password internally.
1635 * TODO (b/80170828): Fix this so profile password is always passed in.
Annie Meng086ddc82019-03-29 17:43:35 +00001636 * @param isLockTiedToParent is {@code true} if {@code userId} is a profile and its new
1637 * credentials are being tied to its parent's credentials.
1638 */
Rubin Xubb883202019-10-09 11:22:53 +01001639 private boolean setLockCredentialInternal(LockscreenCredential credential,
Rubin Xud9522402019-11-06 13:54:27 +00001640 LockscreenCredential savedCredential, int userId, boolean isLockTiedToParent) {
Daulet Zhanguzin8ea0a622020-01-02 17:36:31 +00001641 Objects.requireNonNull(credential);
1642 Objects.requireNonNull(savedCredential);
Rubin Xu3bf722a2016-12-15 16:07:38 +00001643 synchronized (mSpManager) {
1644 if (isSyntheticPasswordBasedCredentialLocked(userId)) {
Rubin Xubb883202019-10-09 11:22:53 +01001645 return spBasedSetLockCredentialInternalLocked(credential, savedCredential, userId,
Rubin Xud9522402019-11-06 13:54:27 +00001646 isLockTiedToParent);
Rubin Xu3bf722a2016-12-15 16:07:38 +00001647 }
1648 }
Adrian Roos7374d3a2017-03-31 14:14:53 -07001649
Rubin Xubb883202019-10-09 11:22:53 +01001650 if (credential.isNone()) {
Barani Muthukumaran9ba99ed2019-12-18 00:36:06 -08001651 clearUserKeyProtection(userId, null);
Rubin Xuca6ece52019-07-31 15:02:13 +01001652 gateKeeperClearSecureUserId(userId);
Rubin Xu1de89b32016-11-30 20:03:13 +00001653 mStorage.writeCredentialHash(CredentialHash.createEmptyHash(), userId);
Rubin Xu5e891bc2019-10-14 10:22:23 +01001654 // Still update PASSWORD_TYPE_KEY if we are running in pre-synthetic password code path,
1655 // since it forms part of the state that determines the credential type
1656 // @see getCredentialTypeInternal
1657 setKeyguardStoredQuality(DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED, userId);
Chad Brubakera91a8502015-05-07 10:02:22 -07001658 setKeystorePassword(null, userId);
Paul Crowleycc701552016-05-17 14:18:49 -07001659 fixateNewestUserKeyAuth(userId);
Rubin Xua55b1682017-01-31 10:06:56 +00001660 synchronizeUnifiedWorkChallengeForProfiles(userId, null);
Rubin Xubb883202019-10-09 11:22:53 +01001661 setUserPasswordMetrics(LockscreenCredential.createNone(), userId);
1662 sendCredentialsOnChangeIfRequired(credential, userId, isLockTiedToParent);
Rubin Xu6a7303d2019-08-16 13:19:56 +01001663 return true;
Andres Moralesd9fc85a2015-04-09 19:14:42 -07001664 }
Rubin Xua55b1682017-01-31 10:06:56 +00001665
1666 CredentialHash currentHandle = mStorage.readCredentialHash(userId);
Ricky Waidc283a82016-03-24 19:55:08 +00001667 if (isManagedProfileWithUnifiedLock(userId)) {
1668 // get credential from keystore when managed profile has unified lock
Rubin Xubb883202019-10-09 11:22:53 +01001669 if (savedCredential.isNone()) {
Rubin Xua55b1682017-01-31 10:06:56 +00001670 try {
Rubin Xu0090c582020-03-06 14:34:16 +00001671 //TODO: remove as part of b/80170828
Rubin Xua55b1682017-01-31 10:06:56 +00001672 savedCredential = getDecryptedPasswordForTiedProfile(userId);
1673 } catch (FileNotFoundException e) {
1674 Slog.i(TAG, "Child profile key not found");
1675 } catch (UnrecoverableKeyException | InvalidKeyException | KeyStoreException
1676 | NoSuchAlgorithmException | NoSuchPaddingException
1677 | InvalidAlgorithmParameterException | IllegalBlockSizeException
1678 | BadPaddingException | CertificateException | IOException e) {
1679 Slog.e(TAG, "Failed to decrypt child profile key", e);
1680 }
Andres Morales8fa56652015-03-31 09:19:50 -07001681 }
Ricky Waidc283a82016-03-24 19:55:08 +00001682 } else {
Rubin Xua55b1682017-01-31 10:06:56 +00001683 if (currentHandle.hash == null) {
Rubin Xubb883202019-10-09 11:22:53 +01001684 if (!savedCredential.isNone()) {
Ricky Waidc283a82016-03-24 19:55:08 +00001685 Slog.w(TAG, "Saved credential provided, but none stored");
1686 }
Rubin Xubb883202019-10-09 11:22:53 +01001687 savedCredential.close();
1688 savedCredential = LockscreenCredential.createNone();
Ricky Waidc283a82016-03-24 19:55:08 +00001689 }
Andres Morales8fa56652015-03-31 09:19:50 -07001690 }
Rubin Xu3bf722a2016-12-15 16:07:38 +00001691 synchronized (mSpManager) {
1692 if (shouldMigrateToSyntheticPasswordLocked(userId)) {
Rubin Xubb883202019-10-09 11:22:53 +01001693 initializeSyntheticPasswordLocked(currentHandle.hash, savedCredential, userId);
1694 return spBasedSetLockCredentialInternalLocked(credential, savedCredential, userId,
Rubin Xud9522402019-11-06 13:54:27 +00001695 isLockTiedToParent);
Rubin Xu3bf722a2016-12-15 16:07:38 +00001696 }
1697 }
1698 if (DEBUG) Slog.d(TAG, "setLockCredentialInternal: user=" + userId);
Rubin Xubb883202019-10-09 11:22:53 +01001699 byte[] enrolledHandle = enrollCredential(currentHandle.hash,
1700 savedCredential.getCredential(), credential.getCredential(), userId);
Rubin Xu6a7303d2019-08-16 13:19:56 +01001701 if (enrolledHandle == null) {
1702 Slog.w(TAG, String.format("Failed to enroll %s: incorrect credential",
Rubin Xubb883202019-10-09 11:22:53 +01001703 credential.isPattern() ? "pattern" : "password"));
Rubin Xu6a7303d2019-08-16 13:19:56 +01001704 return false;
Andres Morales8fa56652015-03-31 09:19:50 -07001705 }
Rubin Xubb883202019-10-09 11:22:53 +01001706 CredentialHash willStore = CredentialHash.create(enrolledHandle, credential.getType());
Rubin Xu6a7303d2019-08-16 13:19:56 +01001707 mStorage.writeCredentialHash(willStore, userId);
Rubin Xu5e891bc2019-10-14 10:22:23 +01001708 // Still update PASSWORD_TYPE_KEY if we are running in pre-synthetic password code path,
1709 // since it forms part of the state that determines the credential type
1710 // @see getCredentialTypeInternal
1711 setKeyguardStoredQuality(
1712 LockPatternUtils.credentialTypeToPasswordQuality(credential.getType()), userId);
Rubin Xu6a7303d2019-08-16 13:19:56 +01001713 // push new secret and auth token to vold
1714 GateKeeperResponse gkResponse;
1715 try {
1716 gkResponse = getGateKeeperService().verifyChallenge(userId, 0, willStore.hash,
Rubin Xubb883202019-10-09 11:22:53 +01001717 credential.getCredential());
Rubin Xu6a7303d2019-08-16 13:19:56 +01001718 } catch (RemoteException e) {
1719 throw new IllegalStateException("Failed to verify current credential", e);
1720 }
1721 setUserKeyProtection(userId, credential, convertResponse(gkResponse));
1722 fixateNewestUserKeyAuth(userId);
1723 // Refresh the auth token
Rubin Xubb883202019-10-09 11:22:53 +01001724 doVerifyCredential(credential, CHALLENGE_FROM_CALLER, 0, userId,
Rubin Xu6a7303d2019-08-16 13:19:56 +01001725 null /* progressCallback */);
1726 synchronizeUnifiedWorkChallengeForProfiles(userId, null);
Rubin Xubb883202019-10-09 11:22:53 +01001727 sendCredentialsOnChangeIfRequired(credential, userId, isLockTiedToParent);
Rubin Xu6a7303d2019-08-16 13:19:56 +01001728 return true;
Andres Morales8fa56652015-03-31 09:19:50 -07001729 }
1730
Rubin Xua55b1682017-01-31 10:06:56 +00001731 private VerifyCredentialResponse convertResponse(GateKeeperResponse gateKeeperResponse) {
Adrian Roos7374d3a2017-03-31 14:14:53 -07001732 return VerifyCredentialResponse.fromGateKeeperResponse(gateKeeperResponse);
Rubin Xua55b1682017-01-31 10:06:56 +00001733 }
1734
Rubin Xubb883202019-10-09 11:22:53 +01001735 @VisibleForTesting /** Note: this method is overridden in unit tests */
1736 protected void tieProfileLockToParent(int userId, LockscreenCredential password) {
Ricky Waidc283a82016-03-24 19:55:08 +00001737 if (DEBUG) Slog.v(TAG, "tieProfileLockToParent for user: " + userId);
Ricky Waidc283a82016-03-24 19:55:08 +00001738 byte[] encryptionResult;
1739 byte[] iv;
1740 try {
1741 KeyGenerator keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES);
1742 keyGenerator.init(new SecureRandom());
1743 SecretKey secretKey = keyGenerator.generateKey();
Ricky Waidc283a82016-03-24 19:55:08 +00001744 java.security.KeyStore keyStore = java.security.KeyStore.getInstance("AndroidKeyStore");
1745 keyStore.load(null);
Ricky Wai97c8f8d2016-07-13 17:57:45 +01001746 try {
1747 keyStore.setEntry(
1748 LockPatternUtils.PROFILE_KEY_NAME_ENCRYPT + userId,
1749 new java.security.KeyStore.SecretKeyEntry(secretKey),
1750 new KeyProtection.Builder(KeyProperties.PURPOSE_ENCRYPT)
1751 .setBlockModes(KeyProperties.BLOCK_MODE_GCM)
1752 .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
1753 .build());
1754 keyStore.setEntry(
1755 LockPatternUtils.PROFILE_KEY_NAME_DECRYPT + userId,
1756 new java.security.KeyStore.SecretKeyEntry(secretKey),
1757 new KeyProtection.Builder(KeyProperties.PURPOSE_DECRYPT)
1758 .setBlockModes(KeyProperties.BLOCK_MODE_GCM)
1759 .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
1760 .setUserAuthenticationRequired(true)
1761 .setUserAuthenticationValidityDurationSeconds(30)
Pavel Grafove053c1e2017-08-08 16:53:32 +01001762 .setCriticalToDeviceEncryption(true)
Ricky Wai97c8f8d2016-07-13 17:57:45 +01001763 .build());
1764 // Key imported, obtain a reference to it.
1765 SecretKey keyStoreEncryptionKey = (SecretKey) keyStore.getKey(
1766 LockPatternUtils.PROFILE_KEY_NAME_ENCRYPT + userId, null);
1767 Cipher cipher = Cipher.getInstance(
1768 KeyProperties.KEY_ALGORITHM_AES + "/" + KeyProperties.BLOCK_MODE_GCM + "/"
1769 + KeyProperties.ENCRYPTION_PADDING_NONE);
1770 cipher.init(Cipher.ENCRYPT_MODE, keyStoreEncryptionKey);
Rubin Xubb883202019-10-09 11:22:53 +01001771 encryptionResult = cipher.doFinal(password.getCredential());
Ricky Wai97c8f8d2016-07-13 17:57:45 +01001772 iv = cipher.getIV();
1773 } finally {
1774 // The original key can now be discarded.
1775 keyStore.deleteEntry(LockPatternUtils.PROFILE_KEY_NAME_ENCRYPT + userId);
1776 }
Ricky Waidc283a82016-03-24 19:55:08 +00001777 } catch (CertificateException | UnrecoverableKeyException
Zach Jange61672a2016-11-22 17:47:18 +00001778 | IOException | BadPaddingException | IllegalBlockSizeException | KeyStoreException
Ricky Waidc283a82016-03-24 19:55:08 +00001779 | NoSuchPaddingException | NoSuchAlgorithmException | InvalidKeyException e) {
Rubin Xu0f9c2ff2019-08-14 16:25:57 +01001780 throw new IllegalStateException("Failed to encrypt key", e);
Ricky Waidc283a82016-03-24 19:55:08 +00001781 }
1782 ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
1783 try {
1784 if (iv.length != PROFILE_KEY_IV_SIZE) {
Rubin Xu0f9c2ff2019-08-14 16:25:57 +01001785 throw new IllegalArgumentException("Invalid iv length: " + iv.length);
Ricky Waidc283a82016-03-24 19:55:08 +00001786 }
1787 outputStream.write(iv);
1788 outputStream.write(encryptionResult);
1789 } catch (IOException e) {
Rubin Xu0f9c2ff2019-08-14 16:25:57 +01001790 throw new IllegalStateException("Failed to concatenate byte arrays", e);
Ricky Waidc283a82016-03-24 19:55:08 +00001791 }
1792 mStorage.writeChildProfileLock(userId, outputStream.toByteArray());
1793 }
1794
Andres Morales8fa56652015-03-31 09:19:50 -07001795 private byte[] enrollCredential(byte[] enrolledHandle,
Rubin Xuca6ece52019-07-31 15:02:13 +01001796 byte[] enrolledCredential, byte[] toEnroll, int userId) {
Jim Millerde1af082013-09-11 14:58:26 -07001797 checkWritePermission(userId);
Rubin Xuca6ece52019-07-31 15:02:13 +01001798 GateKeeperResponse response;
1799 try {
1800 response = getGateKeeperService().enroll(userId, enrolledHandle,
1801 enrolledCredential, toEnroll);
1802 } catch (RemoteException e) {
1803 Slog.e(TAG, "Failed to enroll credential", e);
1804 return null;
1805 }
Jim Millerde1af082013-09-11 14:58:26 -07001806
Andres Morales23974272015-05-14 22:42:26 -07001807 if (response == null) {
1808 return null;
Andres Morales8fa56652015-03-31 09:19:50 -07001809 }
Jim Millerde1af082013-09-11 14:58:26 -07001810
Andres Morales23974272015-05-14 22:42:26 -07001811 byte[] hash = response.getPayload();
1812 if (hash != null) {
1813 setKeystorePassword(toEnroll, userId);
1814 } else {
1815 // Should not happen
1816 Slog.e(TAG, "Throttled while enrolling a password");
1817 }
Andres Morales8fa56652015-03-31 09:19:50 -07001818 return hash;
Jim Millerde1af082013-09-11 14:58:26 -07001819 }
1820
Rubin Xuca6ece52019-07-31 15:02:13 +01001821 private void setAuthlessUserKeyProtection(int userId, byte[] key) {
Rubin Xu3bf722a2016-12-15 16:07:38 +00001822 if (DEBUG) Slog.d(TAG, "setAuthlessUserKeyProtectiond: user=" + userId);
1823 addUserKeyAuth(userId, null, key);
1824 }
1825
Rubin Xubb883202019-10-09 11:22:53 +01001826 private void setUserKeyProtection(int userId, LockscreenCredential credential,
1827 VerifyCredentialResponse vcr) {
Rubin Xua55b1682017-01-31 10:06:56 +00001828 if (DEBUG) Slog.d(TAG, "setUserKeyProtection: user=" + userId);
Paul Crowleyfaeb3eb2016-02-08 15:58:29 +00001829 if (vcr == null) {
Rubin Xuca6ece52019-07-31 15:02:13 +01001830 throw new IllegalArgumentException("Null response verifying a credential we just set");
Paul Crowleyfaeb3eb2016-02-08 15:58:29 +00001831 }
1832 if (vcr.getResponseCode() != VerifyCredentialResponse.RESPONSE_OK) {
Rubin Xuca6ece52019-07-31 15:02:13 +01001833 throw new IllegalArgumentException("Non-OK response verifying a credential we just set "
Rubin Xu1de89b32016-11-30 20:03:13 +00001834 + vcr.getResponseCode());
Paul Crowleyfaeb3eb2016-02-08 15:58:29 +00001835 }
1836 byte[] token = vcr.getPayload();
1837 if (token == null) {
Rubin Xuca6ece52019-07-31 15:02:13 +01001838 throw new IllegalArgumentException("Empty payload verifying a credential we just set");
Paul Crowleyfaeb3eb2016-02-08 15:58:29 +00001839 }
Paul Crowleycc701552016-05-17 14:18:49 -07001840 addUserKeyAuth(userId, token, secretFromCredential(credential));
Paul Crowleyfaeb3eb2016-02-08 15:58:29 +00001841 }
1842
Barani Muthukumaran9ba99ed2019-12-18 00:36:06 -08001843 private void clearUserKeyProtection(int userId, byte[] secret) {
Rubin Xua55b1682017-01-31 10:06:56 +00001844 if (DEBUG) Slog.d(TAG, "clearUserKeyProtection user=" + userId);
Barani Muthukumaran9ba99ed2019-12-18 00:36:06 -08001845 final UserInfo userInfo = mUserManager.getUserInfo(userId);
1846 final long callingId = Binder.clearCallingIdentity();
1847 try {
1848 mStorageManager.clearUserKeyAuth(userId, userInfo.serialNumber, null, secret);
1849 } catch (RemoteException e) {
1850 throw new IllegalStateException("clearUserKeyAuth failed user=" + userId);
1851 } finally {
1852 Binder.restoreCallingIdentity(callingId);
1853 }
Paul Crowleyfaeb3eb2016-02-08 15:58:29 +00001854 }
1855
Rubin Xubb883202019-10-09 11:22:53 +01001856 private static byte[] secretFromCredential(LockscreenCredential credential) {
Paul Crowleyfaeb3eb2016-02-08 15:58:29 +00001857 try {
1858 MessageDigest digest = MessageDigest.getInstance("SHA-512");
1859 // Personalize the hash
Rich Canningsf64ec632019-02-21 12:40:36 -08001860 byte[] personalization = "Android FBE credential hash".getBytes();
Paul Crowleyfaeb3eb2016-02-08 15:58:29 +00001861 // Pad it to the block size of the hash function
1862 personalization = Arrays.copyOf(personalization, 128);
1863 digest.update(personalization);
Rubin Xubb883202019-10-09 11:22:53 +01001864 digest.update(credential.getCredential());
Paul Crowleyfaeb3eb2016-02-08 15:58:29 +00001865 return digest.digest();
1866 } catch (NoSuchAlgorithmException e) {
Rubin Xu0f9c2ff2019-08-14 16:25:57 +01001867 throw new IllegalStateException("NoSuchAlgorithmException for SHA-512");
Paul Crowleyfaeb3eb2016-02-08 15:58:29 +00001868 }
1869 }
1870
Rubin Xuca7007b2019-03-25 11:44:41 +00001871 private boolean isUserKeyUnlocked(int userId) {
1872 try {
1873 return mStorageManager.isUserKeyUnlocked(userId);
1874 } catch (RemoteException e) {
Rubin Xue1beaf02019-10-22 11:36:51 +01001875 Slog.e(TAG, "failed to check user key locked state", e);
Rubin Xuca7007b2019-03-25 11:44:41 +00001876 return false;
1877 }
1878 }
1879
1880 /** Unlock disk encryption */
Rubin Xuca6ece52019-07-31 15:02:13 +01001881 private void unlockUserKey(int userId, byte[] token, byte[] secret) {
Rubin Xuca7007b2019-03-25 11:44:41 +00001882 final UserInfo userInfo = mUserManager.getUserInfo(userId);
Rubin Xuca6ece52019-07-31 15:02:13 +01001883 try {
1884 mStorageManager.unlockUserKey(userId, userInfo.serialNumber, token, secret);
1885 } catch (RemoteException e) {
1886 throw new IllegalStateException("Failed to unlock user key " + userId, e);
1887
1888 }
Rubin Xuca7007b2019-03-25 11:44:41 +00001889 }
1890
Rubin Xuca6ece52019-07-31 15:02:13 +01001891 private void addUserKeyAuth(int userId, byte[] token, byte[] secret) {
Rubin Xu0cbc19e2016-12-09 14:00:21 +00001892 final UserInfo userInfo = mUserManager.getUserInfo(userId);
Paul Crowley815036f2016-03-29 14:14:48 -07001893 final long callingId = Binder.clearCallingIdentity();
1894 try {
Rubin Xuca7007b2019-03-25 11:44:41 +00001895 mStorageManager.addUserKeyAuth(userId, userInfo.serialNumber, token, secret);
Rubin Xuca6ece52019-07-31 15:02:13 +01001896 } catch (RemoteException e) {
1897 throw new IllegalStateException("Failed to add new key to vold " + userId, e);
Paul Crowley815036f2016-03-29 14:14:48 -07001898 } finally {
1899 Binder.restoreCallingIdentity(callingId);
1900 }
Paul Crowleyfaeb3eb2016-02-08 15:58:29 +00001901 }
1902
Rubin Xuca6ece52019-07-31 15:02:13 +01001903 private void fixateNewestUserKeyAuth(int userId) {
Rubin Xua55b1682017-01-31 10:06:56 +00001904 if (DEBUG) Slog.d(TAG, "fixateNewestUserKeyAuth: user=" + userId);
Toni Barzic6c818722016-05-27 09:18:39 -07001905 final long callingId = Binder.clearCallingIdentity();
1906 try {
Rubin Xuca7007b2019-03-25 11:44:41 +00001907 mStorageManager.fixateNewestUserKeyAuth(userId);
Rubin Xuca6ece52019-07-31 15:02:13 +01001908 } catch (RemoteException e) {
1909 // OK to ignore the exception as vold would just accept both old and new
1910 // keys if this call fails, and will fix itself during the next boot
1911 Slog.w(TAG, "fixateNewestUserKeyAuth failed", e);
Toni Barzic6c818722016-05-27 09:18:39 -07001912 } finally {
1913 Binder.restoreCallingIdentity(callingId);
1914 }
Paul Crowleycc701552016-05-17 14:18:49 -07001915 }
1916
Jim Millerde1af082013-09-11 14:58:26 -07001917 @Override
Rubin Xuca6ece52019-07-31 15:02:13 +01001918 public void resetKeyStore(int userId) {
Ricky Wai7f405f12016-05-31 12:05:05 +01001919 checkWritePermission(userId);
Ricky Wai4613fe42016-05-24 11:11:42 +01001920 if (DEBUG) Slog.v(TAG, "Reset keystore for user: " + userId);
1921 int managedUserId = -1;
Rubin Xubb883202019-10-09 11:22:53 +01001922 LockscreenCredential managedUserDecryptedPassword = null;
Ricky Wai4613fe42016-05-24 11:11:42 +01001923 final List<UserInfo> profiles = mUserManager.getProfiles(userId);
1924 for (UserInfo pi : profiles) {
1925 // Unlock managed profile with unified lock
1926 if (pi.isManagedProfile()
Rubin Xu3744acf2020-01-02 16:39:50 +00001927 && !getSeparateProfileChallengeEnabledInternal(pi.id)
Ricky Wai4613fe42016-05-24 11:11:42 +01001928 && mStorage.hasChildProfileLock(pi.id)) {
1929 try {
1930 if (managedUserId == -1) {
1931 managedUserDecryptedPassword = getDecryptedPasswordForTiedProfile(pi.id);
1932 managedUserId = pi.id;
1933 } else {
1934 // Should not happen
1935 Slog.e(TAG, "More than one managed profile, uid1:" + managedUserId
1936 + ", uid2:" + pi.id);
1937 }
1938 } catch (UnrecoverableKeyException | InvalidKeyException | KeyStoreException
1939 | NoSuchAlgorithmException | NoSuchPaddingException
1940 | InvalidAlgorithmParameterException | IllegalBlockSizeException
1941 | BadPaddingException | CertificateException | IOException e) {
1942 Slog.e(TAG, "Failed to decrypt child profile key", e);
1943 }
1944 }
1945 }
1946 try {
1947 // Clear all the users credentials could have been installed in for this user.
1948 for (int profileId : mUserManager.getProfileIdsWithDisabled(userId)) {
1949 for (int uid : SYSTEM_CREDENTIAL_UIDS) {
1950 mKeyStore.clearUid(UserHandle.getUid(profileId, uid));
1951 }
1952 }
1953 } finally {
1954 if (managedUserId != -1 && managedUserDecryptedPassword != null) {
1955 if (DEBUG) Slog.v(TAG, "Restore tied profile lock");
Zach Jange61672a2016-11-22 17:47:18 +00001956 tieProfileLockToParent(managedUserId, managedUserDecryptedPassword);
Ricky Wai4613fe42016-05-24 11:11:42 +01001957 }
1958 }
Rubin Xubb883202019-10-09 11:22:53 +01001959 if (managedUserDecryptedPassword != null) {
1960 managedUserDecryptedPassword.zeroize();
Rich Canningsf64ec632019-02-21 12:40:36 -08001961 }
Ricky Wai4613fe42016-05-24 11:11:42 +01001962 }
1963
1964 @Override
Rubin Xubb883202019-10-09 11:22:53 +01001965 public VerifyCredentialResponse checkCredential(LockscreenCredential credential, int userId,
Rubin Xuca6ece52019-07-31 15:02:13 +01001966 ICheckCredentialProgressCallback progressCallback) {
Rubin Xu1de89b32016-11-30 20:03:13 +00001967 checkPasswordReadPermission(userId);
Rubin Xubb883202019-10-09 11:22:53 +01001968 return doVerifyCredential(credential, CHALLENGE_NONE, 0, userId, progressCallback);
Andres Moralesd9fc85a2015-04-09 19:14:42 -07001969 }
Adrian Roos261d5ab2014-10-29 14:42:38 +01001970
Andres Moralesd9fc85a2015-04-09 19:14:42 -07001971 @Override
Rubin Xubb883202019-10-09 11:22:53 +01001972 public VerifyCredentialResponse verifyCredential(LockscreenCredential credential,
1973 long challenge, int userId) {
Rubin Xu1de89b32016-11-30 20:03:13 +00001974 checkPasswordReadPermission(userId);
Kevin Chyn1cd21602020-04-24 12:05:27 -07001975 @ChallengeType int challengeType = CHALLENGE_FROM_CALLER;
1976 if (challenge == 0) {
1977 Slog.w(TAG, "VerifyCredential called with challenge=0");
1978 challengeType = CHALLENGE_NONE;
1979
1980 }
1981 return doVerifyCredential(credential, challengeType, challenge, userId,
Rubin Xu1de89b32016-11-30 20:03:13 +00001982 null /* progressCallback */);
Andres Moralesd9fc85a2015-04-09 19:14:42 -07001983 }
1984
Rubin Xubb883202019-10-09 11:22:53 +01001985 private VerifyCredentialResponse doVerifyCredential(LockscreenCredential credential,
Kevin Chynbc29dd72019-06-13 11:47:54 -07001986 @ChallengeType int challengeType, long challenge, int userId,
Rubin Xuca6ece52019-07-31 15:02:13 +01001987 ICheckCredentialProgressCallback progressCallback) {
Rubin Xubb883202019-10-09 11:22:53 +01001988 return doVerifyCredential(credential, challengeType, challenge, userId,
Kevin Chynbc29dd72019-06-13 11:47:54 -07001989 progressCallback, null /* resetLockouts */);
1990 }
1991
Rubin Xu1de89b32016-11-30 20:03:13 +00001992 /**
1993 * Verify user credential and unlock the user. Fix pattern bug by deprecating the old base zero
1994 * format.
1995 */
Rubin Xubb883202019-10-09 11:22:53 +01001996 private VerifyCredentialResponse doVerifyCredential(LockscreenCredential credential,
Kevin Chynbc29dd72019-06-13 11:47:54 -07001997 @ChallengeType int challengeType, long challenge, int userId,
1998 ICheckCredentialProgressCallback progressCallback,
Rubin Xuca6ece52019-07-31 15:02:13 +01001999 @Nullable ArrayList<PendingResetLockout> resetLockouts) {
Rubin Xubb883202019-10-09 11:22:53 +01002000 if (credential == null || credential.isNone()) {
Rubin Xu1de89b32016-11-30 20:03:13 +00002001 throw new IllegalArgumentException("Credential can't be null or empty");
2002 }
Rubin Xu5e891bc2019-10-14 10:22:23 +01002003 if (userId == USER_FRP && mInjector.settingsGlobalGetInt(mContext.getContentResolver(),
Adrian Roos7374d3a2017-03-31 14:14:53 -07002004 Settings.Global.DEVICE_PROVISIONED, 0) != 0) {
2005 Slog.e(TAG, "FRP credential can only be verified prior to provisioning.");
2006 return VerifyCredentialResponse.ERROR;
2007 }
Rubin Xue94a7702017-06-20 17:29:57 +01002008 VerifyCredentialResponse response = null;
Rubin Xubb883202019-10-09 11:22:53 +01002009 response = spBasedDoVerifyCredential(credential, challengeType, challenge,
Kevin Chynbc29dd72019-06-13 11:47:54 -07002010 userId, progressCallback, resetLockouts);
Rubin Xue94a7702017-06-20 17:29:57 +01002011 // The user employs synthetic password based credential.
2012 if (response != null) {
Robert Berry40386df2018-01-22 21:16:58 +00002013 if (response.getResponseCode() == VerifyCredentialResponse.RESPONSE_OK) {
Rubin Xubb883202019-10-09 11:22:53 +01002014 sendCredentialsOnUnlockIfRequired(credential, userId);
Robert Berry40386df2018-01-22 21:16:58 +00002015 }
Rubin Xue94a7702017-06-20 17:29:57 +01002016 return response;
Rubin Xu3bf722a2016-12-15 16:07:38 +00002017 }
Rubin Xue94a7702017-06-20 17:29:57 +01002018
Adrian Roos7374d3a2017-03-31 14:14:53 -07002019 if (userId == USER_FRP) {
Andrew Scull971f2942017-07-12 15:09:45 +01002020 Slog.wtf(TAG, "Unexpected FRP credential type, should be SP based.");
2021 return VerifyCredentialResponse.ERROR;
Adrian Roos7374d3a2017-03-31 14:14:53 -07002022 }
2023
Andrew Scull971f2942017-07-12 15:09:45 +01002024 final CredentialHash storedHash = mStorage.readCredentialHash(userId);
Rubin Xu5e891bc2019-10-14 10:22:23 +01002025 if (!credential.checkAgainstStoredType(storedHash.type)) {
Rubin Xu1de89b32016-11-30 20:03:13 +00002026 Slog.wtf(TAG, "doVerifyCredential type mismatch with stored credential??"
Rubin Xubb883202019-10-09 11:22:53 +01002027 + " stored: " + storedHash.type + " passed in: " + credential.getType());
Rubin Xu1de89b32016-11-30 20:03:13 +00002028 return VerifyCredentialResponse.ERROR;
2029 }
Andres Moralese40bad82015-05-28 14:21:36 -07002030
Rubin Xu7959e2a2019-07-31 11:26:53 +01002031 response = verifyCredential(userId, storedHash, credential,
Kevin Chynbc29dd72019-06-13 11:47:54 -07002032 challengeType, challenge, progressCallback);
Andres Morales59ef1262015-06-26 13:56:39 -07002033
Michal Karpinskie71f5832017-01-13 18:18:49 +00002034 if (response.getResponseCode() == VerifyCredentialResponse.RESPONSE_OK) {
2035 mStrongAuth.reportSuccessfulStrongAuthUnlock(userId);
Rubin Xu1de89b32016-11-30 20:03:13 +00002036 }
Andres Moralese40bad82015-05-28 14:21:36 -07002037
Rubin Xu1de89b32016-11-30 20:03:13 +00002038 return response;
Amith Yamasani52c489c2012-03-28 11:42:42 -07002039 }
2040
2041 @Override
Rubin Xubb883202019-10-09 11:22:53 +01002042 public VerifyCredentialResponse verifyTiedProfileChallenge(LockscreenCredential credential,
Rubin Xuca6ece52019-07-31 15:02:13 +01002043 long challenge, int userId) {
Ricky Wai53940d42016-04-05 15:29:24 +01002044 checkPasswordReadPermission(userId);
2045 if (!isManagedProfileWithUnifiedLock(userId)) {
Rubin Xuca6ece52019-07-31 15:02:13 +01002046 throw new IllegalArgumentException("User id must be managed profile with unified lock");
Ricky Wai53940d42016-04-05 15:29:24 +01002047 }
2048 final int parentProfileId = mUserManager.getProfileParent(userId).id;
2049 // Unlock parent by using parent's challenge
Rubin Xu1de89b32016-11-30 20:03:13 +00002050 final VerifyCredentialResponse parentResponse = doVerifyCredential(
2051 credential,
Kevin Chynbc29dd72019-06-13 11:47:54 -07002052 CHALLENGE_FROM_CALLER,
Rubin Xu1de89b32016-11-30 20:03:13 +00002053 challenge,
2054 parentProfileId,
2055 null /* progressCallback */);
Ricky Wai53940d42016-04-05 15:29:24 +01002056 if (parentResponse.getResponseCode() != VerifyCredentialResponse.RESPONSE_OK) {
2057 // Failed, just return parent's response
2058 return parentResponse;
2059 }
2060
2061 try {
2062 // Unlock work profile, and work profile with unified lock must use password only
Rubin Xu1de89b32016-11-30 20:03:13 +00002063 return doVerifyCredential(getDecryptedPasswordForTiedProfile(userId),
Kevin Chynbc29dd72019-06-13 11:47:54 -07002064 CHALLENGE_FROM_CALLER,
Ricky Wai53940d42016-04-05 15:29:24 +01002065 challenge,
Jorim Jaggie8fde5d2016-06-30 23:41:37 -07002066 userId, null /* progressCallback */);
Ricky Wai53940d42016-04-05 15:29:24 +01002067 } catch (UnrecoverableKeyException | InvalidKeyException | KeyStoreException
2068 | NoSuchAlgorithmException | NoSuchPaddingException
2069 | InvalidAlgorithmParameterException | IllegalBlockSizeException
2070 | BadPaddingException | CertificateException | IOException e) {
2071 Slog.e(TAG, "Failed to decrypt child profile key", e);
Rubin Xuca6ece52019-07-31 15:02:13 +01002072 throw new IllegalStateException("Unable to get tied profile token");
Ricky Wai53940d42016-04-05 15:29:24 +01002073 }
2074 }
2075
Rubin Xu1de89b32016-11-30 20:03:13 +00002076 /**
2077 * Lowest-level credential verification routine that talks to GateKeeper. If verification
2078 * passes, unlock the corresponding user and keystore. Also handles the migration from legacy
2079 * hash to GK.
2080 */
Andres Morales23974272015-05-14 22:42:26 -07002081 private VerifyCredentialResponse verifyCredential(int userId, CredentialHash storedHash,
Rubin Xubb883202019-10-09 11:22:53 +01002082 LockscreenCredential credential, @ChallengeType int challengeType, long challenge,
Rubin Xuca6ece52019-07-31 15:02:13 +01002083 ICheckCredentialProgressCallback progressCallback) {
Rubin Xubb883202019-10-09 11:22:53 +01002084 if ((storedHash == null || storedHash.hash.length == 0) && credential.isNone()) {
Andres Morales23974272015-05-14 22:42:26 -07002085 // don't need to pass empty credentials to GateKeeper
2086 return VerifyCredentialResponse.OK;
Andres Moralesd9fc85a2015-04-09 19:14:42 -07002087 }
2088
Rubin Xubb883202019-10-09 11:22:53 +01002089 if (storedHash == null || storedHash.hash.length == 0 || credential.isNone()) {
Andres Morales23974272015-05-14 22:42:26 -07002090 return VerifyCredentialResponse.ERROR;
Amith Yamasani52c489c2012-03-28 11:42:42 -07002091 }
Adrian Roos261d5ab2014-10-29 14:42:38 +01002092
Jeff Sharkeyeddf5182016-08-09 16:36:08 -06002093 // We're potentially going to be doing a bunch of disk I/O below as part
2094 // of unlocking the user, so yell if calling from the main thread.
2095 StrictMode.noteDiskRead();
2096
Rubin Xuca6ece52019-07-31 15:02:13 +01002097 GateKeeperResponse gateKeeperResponse;
2098 try {
Rubin Xubb883202019-10-09 11:22:53 +01002099 gateKeeperResponse = getGateKeeperService().verifyChallenge(
2100 userId, challenge, storedHash.hash, credential.getCredential());
Rubin Xuca6ece52019-07-31 15:02:13 +01002101 } catch (RemoteException e) {
2102 Slog.e(TAG, "gatekeeper verify failed", e);
2103 gateKeeperResponse = GateKeeperResponse.ERROR;
2104 }
Rubin Xua55b1682017-01-31 10:06:56 +00002105 VerifyCredentialResponse response = convertResponse(gateKeeperResponse);
2106 boolean shouldReEnroll = gateKeeperResponse.getShouldReEnroll();
Andres Morales8fa56652015-03-31 09:19:50 -07002107
Andres Morales23974272015-05-14 22:42:26 -07002108 if (response.getResponseCode() == VerifyCredentialResponse.RESPONSE_OK) {
Jorim Jaggie31f6b82016-07-01 16:15:09 -07002109
Andres Morales23974272015-05-14 22:42:26 -07002110 // credential has matched
Jorim Jaggie8fde5d2016-06-30 23:41:37 -07002111
2112 if (progressCallback != null) {
Rubin Xuca6ece52019-07-31 15:02:13 +01002113 try {
2114 progressCallback.onCredentialVerified();
2115 } catch (RemoteException e) {
Rubin Xue1beaf02019-10-22 11:36:51 +01002116 Slog.w(TAG, "progressCallback throws exception", e);
Rubin Xuca6ece52019-07-31 15:02:13 +01002117 }
Jorim Jaggie8fde5d2016-06-30 23:41:37 -07002118 }
Rubin Xubb883202019-10-09 11:22:53 +01002119 setUserPasswordMetrics(credential, userId);
2120 unlockKeystore(credential.getCredential(), userId);
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -07002121
Rubin Xu3bf722a2016-12-15 16:07:38 +00002122 Slog.i(TAG, "Unlocking user " + userId + " with token length "
2123 + response.getPayload().length);
Paul Crowleyfaeb3eb2016-02-08 15:58:29 +00002124 unlockUser(userId, response.getPayload(), secretFromCredential(credential));
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -07002125
Ricky Waidc283a82016-03-24 19:55:08 +00002126 if (isManagedProfileWithSeparatedLock(userId)) {
Pavel Grafova8da6972019-04-03 13:58:58 +01002127 setDeviceUnlockedForUser(userId);
Clara Bayarri56878a92015-10-29 15:43:55 +00002128 }
Andres Morales23974272015-05-14 22:42:26 -07002129 if (shouldReEnroll) {
Rubin Xubb883202019-10-09 11:22:53 +01002130 setLockCredentialInternal(credential, credential,
Rubin Xud9522402019-11-06 13:54:27 +00002131 userId, /* isLockTiedToParent= */ false);
Rubin Xu3bf722a2016-12-15 16:07:38 +00002132 } else {
2133 // Now that we've cleared of all required GK migration, let's do the final
2134 // migration to synthetic password.
2135 synchronized (mSpManager) {
2136 if (shouldMigrateToSyntheticPasswordLocked(userId)) {
Rubin Xu128180b2017-04-12 18:02:44 +01002137 AuthenticationToken auth = initializeSyntheticPasswordLocked(
Rubin Xubb883202019-10-09 11:22:53 +01002138 storedHash.hash, credential, userId);
Rubin Xu128180b2017-04-12 18:02:44 +01002139 activateEscrowTokens(auth, userId);
Rubin Xu3bf722a2016-12-15 16:07:38 +00002140 }
2141 }
Andres Morales23974272015-05-14 22:42:26 -07002142 }
Dmitry Dementyev6a509e42017-12-19 14:47:26 -08002143 // Use credentials to create recoverable keystore snapshot.
Rubin Xubb883202019-10-09 11:22:53 +01002144 sendCredentialsOnUnlockIfRequired(credential, userId);
Dmitry Dementyev6a509e42017-12-19 14:47:26 -08002145
Adrian Roos873010d2015-08-25 15:59:00 -07002146 } else if (response.getResponseCode() == VerifyCredentialResponse.RESPONSE_RETRY) {
2147 if (response.getTimeout() > 0) {
2148 requireStrongAuth(STRONG_AUTH_REQUIRED_AFTER_LOCKOUT, userId);
2149 }
Andres Morales23974272015-05-14 22:42:26 -07002150 }
Amith Yamasani52c489c2012-03-28 11:42:42 -07002151
Andres Morales23974272015-05-14 22:42:26 -07002152 return response;
2153 }
Andres Moralesd9fc85a2015-04-09 19:14:42 -07002154
Rubin Xu7cf45092017-08-28 11:47:35 +01002155 /**
Rubin Xu19854862019-08-15 16:37:23 +01002156 * Keep track of the given user's latest password metric. This should be called
2157 * when the user is authenticating or when a new password is being set. In comparison,
2158 * {@link #notifyPasswordChanged} only needs to be called when the user changes the password.
Rubin Xu7cf45092017-08-28 11:47:35 +01002159 */
Rubin Xubb883202019-10-09 11:22:53 +01002160 private void setUserPasswordMetrics(LockscreenCredential password, @UserIdInt int userHandle) {
Rubin Xu19854862019-08-15 16:37:23 +01002161 synchronized (this) {
Rubin Xubb883202019-10-09 11:22:53 +01002162 mUserPasswordMetrics.put(userHandle, PasswordMetrics.computeForCredential(password));
Rubin Xu19854862019-08-15 16:37:23 +01002163 }
2164 }
Andrew Scull5daf2732016-11-14 15:02:45 +00002165
Rubin Xu19854862019-08-15 16:37:23 +01002166 @VisibleForTesting
2167 PasswordMetrics getUserPasswordMetrics(int userHandle) {
2168 if (!isUserSecure(userHandle)) {
2169 // for users without password, mUserPasswordMetrics might not be initialized
2170 // since the user never unlock the device manually. In this case, always
2171 // return a default metrics object. This is to distinguish this case from
2172 // the case where during boot user password is unknown yet (returning null here)
Pavel Grafov6f334842019-08-06 14:37:06 +01002173 return new PasswordMetrics(CREDENTIAL_TYPE_NONE);
Rubin Xu19854862019-08-15 16:37:23 +01002174 }
2175 synchronized (this) {
2176 return mUserPasswordMetrics.get(userHandle);
2177 }
Andrew Scull5daf2732016-11-14 15:02:45 +00002178 }
2179
Rubin Xu3589e892020-03-26 22:27:55 +00002180 private PasswordMetrics loadPasswordMetrics(AuthenticationToken auth, int userHandle) {
2181 synchronized (mSpManager) {
2182 return mSpManager.getPasswordMetrics(auth, getSyntheticPasswordHandleLocked(userHandle),
2183 userHandle);
2184 }
2185 }
2186
Andrew Scull5daf2732016-11-14 15:02:45 +00002187 /**
Rubin Xu19854862019-08-15 16:37:23 +01002188 * Call after {@link #setUserPasswordMetrics} so metrics are updated before
Andrew Scull5daf2732016-11-14 15:02:45 +00002189 * reporting the password changed.
2190 */
2191 private void notifyPasswordChanged(@UserIdInt int userId) {
Andrew Scull5daf2732016-11-14 15:02:45 +00002192 mHandler.post(() -> {
Rubin Xu19854862019-08-15 16:37:23 +01002193 mInjector.getDevicePolicyManager().reportPasswordChanged(userId);
Adrian Roos1c8e3c02018-11-20 20:07:55 +01002194 LocalServices.getService(WindowManagerInternal.class).reportPasswordChanged(userId);
Andrew Scull5daf2732016-11-14 15:02:45 +00002195 });
2196 }
2197
Rubin Xubb883202019-10-09 11:22:53 +01002198 private LockscreenCredential createPattern(String patternString) {
2199 final byte[] patternBytes = patternString.getBytes();
2200 LockscreenCredential pattern = LockscreenCredential.createPattern(
2201 LockPatternUtils.byteArrayToPattern(patternBytes));
2202 Arrays.fill(patternBytes, (byte) 0);
2203 return pattern;
2204 }
2205
Amith Yamasani52c489c2012-03-28 11:42:42 -07002206 @Override
Rubin Xuca6ece52019-07-31 15:02:13 +01002207 public boolean checkVoldPassword(int userId) {
Paul Lawrence945490c2014-03-27 16:37:28 +00002208 if (!mFirstCallToVold) {
2209 return false;
2210 }
2211 mFirstCallToVold = false;
2212
2213 checkPasswordReadPermission(userId);
2214
2215 // There's no guarantee that this will safely connect, but if it fails
2216 // we will simply show the lock screen when we shouldn't, so relatively
2217 // benign. There is an outside chance something nasty would happen if
2218 // this service restarted before vold stales out the password in this
2219 // case. The nastiness is limited to not showing the lock screen when
2220 // we should, within the first minute of decrypting the phone if this
2221 // service can't connect to vold, it restarts, and then the new instance
2222 // does successfully connect.
Rubin Xu0cbc19e2016-12-09 14:00:21 +00002223 final IStorageManager service = mInjector.getStorageManager();
Rich Canningsf64ec632019-02-21 12:40:36 -08002224 // TODO(b/120484642): Update vold to return a password as a byte array
Paul Lawrence0bbd1082016-04-26 15:21:02 -07002225 String password;
2226 long identity = Binder.clearCallingIdentity();
2227 try {
2228 password = service.getPassword();
2229 service.clearPassword();
Rubin Xuca6ece52019-07-31 15:02:13 +01002230 } catch (RemoteException e) {
2231 Slog.w(TAG, "vold getPassword() failed", e);
2232 return false;
Paul Lawrence0bbd1082016-04-26 15:21:02 -07002233 } finally {
2234 Binder.restoreCallingIdentity(identity);
2235 }
Rubin Xu5e891bc2019-10-14 10:22:23 +01002236 if (TextUtils.isEmpty(password)) {
Paul Lawrence945490c2014-03-27 16:37:28 +00002237 return false;
2238 }
2239
2240 try {
Rubin Xu5e891bc2019-10-14 10:22:23 +01002241 final LockscreenCredential credential;
2242 switch (getCredentialTypeInternal(userId)) {
2243 case CREDENTIAL_TYPE_PATTERN:
2244 credential = createPattern(password);
2245 break;
2246 case CREDENTIAL_TYPE_PIN:
2247 credential = LockscreenCredential.createPin(password);
2248 break;
2249 case CREDENTIAL_TYPE_PASSWORD:
2250 credential = LockscreenCredential.createPassword(password);
2251 break;
2252 default:
2253 credential = null;
2254 Slog.e(TAG, "Unknown credential type");
Paul Lawrence945490c2014-03-27 16:37:28 +00002255 }
Paul Lawrence945490c2014-03-27 16:37:28 +00002256
Rubin Xu5e891bc2019-10-14 10:22:23 +01002257 if (credential != null
2258 && checkCredential(credential, userId, null /* progressCallback */)
Rubin Xu1de89b32016-11-30 20:03:13 +00002259 .getResponseCode() == GateKeeperResponse.RESPONSE_OK) {
Rubin Xu5e891bc2019-10-14 10:22:23 +01002260 return true;
Paul Lawrence945490c2014-03-27 16:37:28 +00002261 }
2262 } catch (Exception e) {
Rubin Xu5e891bc2019-10-14 10:22:23 +01002263 Slog.e(TAG, "checkVoldPassword failed: ", e);
Paul Lawrence945490c2014-03-27 16:37:28 +00002264 }
2265
2266 return false;
2267 }
2268
Amith Yamasanif11a5742016-06-16 08:20:07 -07002269 private void removeUser(int userId, boolean unknownUser) {
Rubin Xu066ce2f2019-11-29 17:17:46 +00002270 Slog.i(TAG, "RemoveUser: " + userId);
Rubin Xu7b7424b2017-03-31 18:03:20 +01002271 mSpManager.removeUser(userId);
Adrian Roosb5e47222015-08-14 15:53:06 -07002272 mStrongAuth.removeUser(userId);
Robin Lee49d810c2014-09-23 13:50:22 +01002273
2274 final KeyStore ks = KeyStore.getInstance();
Chad Brubaker83ce0952015-05-12 13:00:02 -07002275 ks.onUserRemoved(userId);
Rubin Xua3c71a12019-12-04 15:25:02 +00002276 mManagedProfilePasswordCache.removePassword(userId);
Andres Morales070fe632015-06-24 10:37:10 -07002277
Rubin Xuca6ece52019-07-31 15:02:13 +01002278 gateKeeperClearSecureUserId(userId);
Irina Dumitrescud74fb7c2019-03-06 16:42:29 +00002279 if (unknownUser || mUserManager.getUserInfo(userId).isManagedProfile()) {
Ricky Waidc283a82016-03-24 19:55:08 +00002280 removeKeystoreProfileKey(userId);
2281 }
Rubin Xu066ce2f2019-11-29 17:17:46 +00002282 // Clean up storage last, this is to ensure that cleanupDataForReusedUserIdIfNecessary()
2283 // can make the assumption that no USER_SERIAL_NUMBER_KEY means user is fully removed.
2284 mStorage.removeUser(userId);
Ricky Waidc283a82016-03-24 19:55:08 +00002285 }
2286
2287 private void removeKeystoreProfileKey(int targetUserId) {
Rubin Xu7b76f332019-11-08 12:10:12 +00002288 Slog.i(TAG, "Remove keystore profile key for user: " + targetUserId);
Ricky Waidc283a82016-03-24 19:55:08 +00002289 try {
2290 java.security.KeyStore keyStore = java.security.KeyStore.getInstance("AndroidKeyStore");
2291 keyStore.load(null);
Ricky Waid3982442016-05-24 19:27:08 +01002292 keyStore.deleteEntry(LockPatternUtils.PROFILE_KEY_NAME_ENCRYPT + targetUserId);
2293 keyStore.deleteEntry(LockPatternUtils.PROFILE_KEY_NAME_DECRYPT + targetUserId);
Ricky Waidc283a82016-03-24 19:55:08 +00002294 } catch (KeyStoreException | NoSuchAlgorithmException | CertificateException
2295 | IOException e) {
2296 // We have tried our best to remove all keys
2297 Slog.e(TAG, "Unable to remove keystore profile key for user:" + targetUserId, e);
2298 }
Amith Yamasani52c489c2012-03-28 11:42:42 -07002299 }
2300
Adrian Roosb5e47222015-08-14 15:53:06 -07002301 @Override
2302 public void registerStrongAuthTracker(IStrongAuthTracker tracker) {
2303 checkPasswordReadPermission(UserHandle.USER_ALL);
2304 mStrongAuth.registerStrongAuthTracker(tracker);
2305 }
2306
2307 @Override
2308 public void unregisterStrongAuthTracker(IStrongAuthTracker tracker) {
2309 checkPasswordReadPermission(UserHandle.USER_ALL);
2310 mStrongAuth.unregisterStrongAuthTracker(tracker);
2311 }
2312
2313 @Override
2314 public void requireStrongAuth(int strongAuthReason, int userId) {
2315 checkWritePermission(userId);
2316 mStrongAuth.requireStrongAuth(strongAuthReason, userId);
2317 }
2318
Adrian Roos4ab7e592016-04-13 15:38:13 -07002319 @Override
Haining Chenc06c4812020-01-13 20:38:53 -08002320 public void reportSuccessfulBiometricUnlock(boolean isStrongBiometric, int userId) {
2321 checkBiometricPermission();
2322 mStrongAuth.reportSuccessfulBiometricUnlock(isStrongBiometric, userId);
2323 }
2324
2325 @Override
2326 public void scheduleNonStrongBiometricIdleTimeout(int userId) {
2327 checkBiometricPermission();
2328 mStrongAuth.scheduleNonStrongBiometricIdleTimeout(userId);
2329 }
2330
2331 @Override
Adrian Roos4ab7e592016-04-13 15:38:13 -07002332 public void userPresent(int userId) {
2333 checkWritePermission(userId);
2334 mStrongAuth.reportUnlock(userId);
2335 }
2336
Victor Changa0940d32016-05-16 19:36:08 +01002337 @Override
2338 public int getStrongAuthForUser(int userId) {
2339 checkPasswordReadPermission(userId);
2340 return mStrongAuthTracker.getStrongAuthForUser(userId);
2341 }
2342
Jorim Jaggi2fef6f72016-11-01 19:06:25 -07002343 private boolean isCallerShell() {
2344 final int callingUid = Binder.getCallingUid();
2345 return callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID;
2346 }
2347
2348 private void enforceShell() {
2349 if (!isCallerShell()) {
2350 throw new SecurityException("Caller must be shell");
2351 }
2352 }
2353
2354 @Override
2355 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
Rubin Xuca6ece52019-07-31 15:02:13 +01002356 String[] args, ShellCallback callback, ResultReceiver resultReceiver) {
Jorim Jaggi2fef6f72016-11-01 19:06:25 -07002357 enforceShell();
2358 final long origId = Binder.clearCallingIdentity();
2359 try {
Felipe Leme1fc9c812018-07-11 10:02:23 -07002360 (new LockSettingsShellCommand(new LockPatternUtils(mContext))).exec(
Jorim Jaggi2fef6f72016-11-01 19:06:25 -07002361 this, in, out, err, args, callback, resultReceiver);
2362 } finally {
2363 Binder.restoreCallingIdentity(origId);
2364 }
2365 }
2366
Dmitry Dementyev1aa96132017-12-11 11:33:12 -08002367 @Override
Bo Zhu7f414d92018-02-28 09:28:19 -08002368 public void initRecoveryServiceWithSigFile(@NonNull String rootCertificateAlias,
2369 @NonNull byte[] recoveryServiceCertFile, @NonNull byte[] recoveryServiceSigFile)
2370 throws RemoteException {
2371 mRecoverableKeyStoreManager.initRecoveryServiceWithSigFile(rootCertificateAlias,
2372 recoveryServiceCertFile, recoveryServiceSigFile);
2373 }
2374
2375 @Override
Dmitry Dementyev4da14e02018-03-23 15:18:33 -07002376 public @NonNull KeyChainSnapshot getKeyChainSnapshot() throws RemoteException {
Dmitry Dementyevb4fb9872018-01-26 11:49:34 -08002377 return mRecoverableKeyStoreManager.getKeyChainSnapshot();
Dmitry Dementyev1aa96132017-12-11 11:33:12 -08002378 }
2379
Dmitry Dementyev4da14e02018-03-23 15:18:33 -07002380 @Override
Dmitry Dementyev14298312018-01-04 15:19:19 -08002381 public void setSnapshotCreatedPendingIntent(@Nullable PendingIntent intent)
Dmitry Dementyevb8b030b2017-12-19 11:02:54 -08002382 throws RemoteException {
Dmitry Dementyev14298312018-01-04 15:19:19 -08002383 mRecoverableKeyStoreManager.setSnapshotCreatedPendingIntent(intent);
Dmitry Dementyevb8b030b2017-12-19 11:02:54 -08002384 }
2385
Dmitry Dementyev1aa96132017-12-11 11:33:12 -08002386 @Override
Dmitry Dementyev7d8c78a2018-01-12 19:14:07 -08002387 public void setServerParams(byte[] serverParams) throws RemoteException {
2388 mRecoverableKeyStoreManager.setServerParams(serverParams);
Dmitry Dementyev1aa96132017-12-11 11:33:12 -08002389 }
2390
2391 @Override
Robert Berrybbe02ae2018-02-20 19:47:43 +00002392 public void setRecoveryStatus(String alias, int status) throws RemoteException {
2393 mRecoverableKeyStoreManager.setRecoveryStatus(alias, status);
Dmitry Dementyev1aa96132017-12-11 11:33:12 -08002394 }
2395
Dmitry Dementyev4da14e02018-03-23 15:18:33 -07002396 @Override
2397 public @NonNull Map getRecoveryStatus() throws RemoteException {
Robert Berry56f06b42018-02-23 13:31:32 +00002398 return mRecoverableKeyStoreManager.getRecoveryStatus();
Dmitry Dementyevb8b030b2017-12-19 11:02:54 -08002399 }
2400
Dmitry Dementyev1aa96132017-12-11 11:33:12 -08002401 @Override
Dmitry Dementyev0916e7c2018-01-23 13:02:08 -08002402 public void setRecoverySecretTypes(@NonNull @KeyChainProtectionParams.UserSecretType
Dmitry Dementyev14298312018-01-04 15:19:19 -08002403 int[] secretTypes) throws RemoteException {
2404 mRecoverableKeyStoreManager.setRecoverySecretTypes(secretTypes);
Dmitry Dementyev1aa96132017-12-11 11:33:12 -08002405 }
2406
2407 @Override
Dmitry Dementyev4da14e02018-03-23 15:18:33 -07002408 public @NonNull int[] getRecoverySecretTypes() throws RemoteException {
Dmitry Dementyev14298312018-01-04 15:19:19 -08002409 return mRecoverableKeyStoreManager.getRecoverySecretTypes();
Dmitry Dementyev1aa96132017-12-11 11:33:12 -08002410
2411 }
2412
2413 @Override
Dmitry Dementyev4da14e02018-03-23 15:18:33 -07002414 public @NonNull byte[] startRecoverySessionWithCertPath(@NonNull String sessionId,
Bo Zhub31ab672018-03-20 22:44:18 -07002415 @NonNull String rootCertificateAlias, @NonNull RecoveryCertPath verifierCertPath,
2416 @NonNull byte[] vaultParams, @NonNull byte[] vaultChallenge,
2417 @NonNull List<KeyChainProtectionParams> secrets)
Bo Zhu7c1972f2018-02-22 21:43:52 -08002418 throws RemoteException {
2419 return mRecoverableKeyStoreManager.startRecoverySessionWithCertPath(
Bo Zhub31ab672018-03-20 22:44:18 -07002420 sessionId, rootCertificateAlias, verifierCertPath, vaultParams, vaultChallenge,
2421 secrets);
Bo Zhu7c1972f2018-02-22 21:43:52 -08002422 }
2423
Dmitry Dementyev4da14e02018-03-23 15:18:33 -07002424 @Override
Robert Berry4a5c87d2018-03-19 18:00:46 +00002425 public Map<String, String> recoverKeyChainSnapshot(
2426 @NonNull String sessionId,
2427 @NonNull byte[] recoveryKeyBlob,
2428 @NonNull List<WrappedApplicationKey> applicationKeys) throws RemoteException {
2429 return mRecoverableKeyStoreManager.recoverKeyChainSnapshot(
2430 sessionId, recoveryKeyBlob, applicationKeys);
2431 }
2432
2433 @Override
Dmitry Dementyev745d2c92018-04-13 14:10:05 -07002434 public void closeSession(@NonNull String sessionId) throws RemoteException {
2435 mRecoverableKeyStoreManager.closeSession(sessionId);
Dmitry Dementyev1aa96132017-12-11 11:33:12 -08002436 }
2437
Robert Berrycfc990a2017-12-22 15:54:30 +00002438 @Override
Robert Berry5daccec2018-01-06 19:16:25 +00002439 public void removeKey(@NonNull String alias) throws RemoteException {
2440 mRecoverableKeyStoreManager.removeKey(alias);
2441 }
2442
2443 @Override
Dmitry Dementyev4da14e02018-03-23 15:18:33 -07002444 public @Nullable String generateKey(@NonNull String alias) throws RemoteException {
Robert Berrya3b99472018-02-23 15:59:02 +00002445 return mRecoverableKeyStoreManager.generateKey(alias);
Dmitry Dementyev29b9de52018-01-31 16:09:32 -08002446 }
2447
2448 @Override
Bo Zhuc7048342019-01-03 14:04:58 -08002449 public @Nullable String generateKeyWithMetadata(
2450 @NonNull String alias, @Nullable byte[] metadata) throws RemoteException {
2451 return mRecoverableKeyStoreManager.generateKeyWithMetadata(alias, metadata);
2452 }
2453
2454 @Override
2455 public @Nullable String importKey(@NonNull String alias, @NonNull byte[] keyBytes)
2456 throws RemoteException {
Bo Zhu2c8e5382018-02-26 15:54:25 -08002457 return mRecoverableKeyStoreManager.importKey(alias, keyBytes);
2458 }
2459
2460 @Override
Bo Zhuc7048342019-01-03 14:04:58 -08002461 public @Nullable String importKeyWithMetadata(@NonNull String alias, @NonNull byte[] keyBytes,
2462 @Nullable byte[] metadata) throws RemoteException {
2463 return mRecoverableKeyStoreManager.importKeyWithMetadata(alias, keyBytes, metadata);
2464 }
2465
2466 @Override
Dmitry Dementyev4da14e02018-03-23 15:18:33 -07002467 public @Nullable String getKey(@NonNull String alias) throws RemoteException {
Dmitry Dementyev29b9de52018-01-31 16:09:32 -08002468 return mRecoverableKeyStoreManager.getKey(alias);
2469 }
2470
Amith Yamasani52c489c2012-03-28 11:42:42 -07002471 private static final String[] VALID_SETTINGS = new String[] {
Rubin Xu1de89b32016-11-30 20:03:13 +00002472 LockPatternUtils.LOCKOUT_PERMANENT_KEY,
Rubin Xu1de89b32016-11-30 20:03:13 +00002473 LockPatternUtils.PATTERN_EVER_CHOSEN_KEY,
2474 LockPatternUtils.PASSWORD_TYPE_KEY,
2475 LockPatternUtils.PASSWORD_TYPE_ALTERNATE_KEY,
2476 LockPatternUtils.LOCK_PASSWORD_SALT_KEY,
2477 LockPatternUtils.DISABLE_LOCKSCREEN_KEY,
2478 LockPatternUtils.LOCKSCREEN_OPTIONS,
2479 LockPatternUtils.LOCKSCREEN_BIOMETRIC_WEAK_FALLBACK,
2480 LockPatternUtils.BIOMETRIC_WEAK_EVER_CHOSEN_KEY,
2481 LockPatternUtils.LOCKSCREEN_POWER_BUTTON_INSTANTLY_LOCKS,
2482 LockPatternUtils.PASSWORD_HISTORY_KEY,
2483 Secure.LOCK_PATTERN_ENABLED,
2484 Secure.LOCK_BIOMETRIC_WEAK_FLAGS,
2485 Secure.LOCK_PATTERN_VISIBLE,
2486 Secure.LOCK_PATTERN_TACTILE_FEEDBACK_ENABLED
Jim Miller187ec582013-04-15 18:27:54 -07002487 };
2488
Svetoslav Ganov6d2c0e52015-06-23 16:33:36 +00002489 // Reading these settings needs the contacts permission
2490 private static final String[] READ_CONTACTS_PROTECTED_SETTINGS = new String[] {
Rubin Xu1de89b32016-11-30 20:03:13 +00002491 Secure.LOCK_SCREEN_OWNER_INFO_ENABLED,
2492 Secure.LOCK_SCREEN_OWNER_INFO
Jim Miller187ec582013-04-15 18:27:54 -07002493 };
Paul Lawrence945490c2014-03-27 16:37:28 +00002494
Adrian Roos001b00d2015-02-24 17:08:48 +01002495 // Reading these settings needs the same permission as checking the password
2496 private static final String[] READ_PASSWORD_PROTECTED_SETTINGS = new String[] {
2497 LockPatternUtils.LOCK_PASSWORD_SALT_KEY,
2498 LockPatternUtils.PASSWORD_HISTORY_KEY,
Adrian Roos855fa302015-04-02 16:01:12 +02002499 LockPatternUtils.PASSWORD_TYPE_KEY,
Ricky Wai7f405f12016-05-31 12:05:05 +01002500 SEPARATE_PROFILE_CHALLENGE_KEY
Adrian Roos001b00d2015-02-24 17:08:48 +01002501 };
2502
Andres Morales301ea442015-04-17 09:15:47 -07002503 private class GateKeeperDiedRecipient implements IBinder.DeathRecipient {
2504 @Override
2505 public void binderDied() {
2506 mGateKeeperService.asBinder().unlinkToDeath(this, 0);
2507 mGateKeeperService = null;
2508 }
2509 }
2510
Rubin Xuca6ece52019-07-31 15:02:13 +01002511 protected synchronized IGateKeeperService getGateKeeperService() {
Andres Morales8fa56652015-03-31 09:19:50 -07002512 if (mGateKeeperService != null) {
2513 return mGateKeeperService;
2514 }
2515
Rubin Xu1de89b32016-11-30 20:03:13 +00002516 final IBinder service = ServiceManager.getService(Context.GATEKEEPER_SERVICE);
Andres Morales8fa56652015-03-31 09:19:50 -07002517 if (service != null) {
Rubin Xuca6ece52019-07-31 15:02:13 +01002518 try {
2519 service.linkToDeath(new GateKeeperDiedRecipient(), 0);
2520 } catch (RemoteException e) {
2521 Slog.w(TAG, " Unable to register death recipient", e);
2522 }
Andres Morales8fa56652015-03-31 09:19:50 -07002523 mGateKeeperService = IGateKeeperService.Stub.asInterface(service);
2524 return mGateKeeperService;
2525 }
2526
2527 Slog.e(TAG, "Unable to acquire GateKeeperService");
2528 return null;
2529 }
Rubin Xu3bf722a2016-12-15 16:07:38 +00002530
Rubin Xuca6ece52019-07-31 15:02:13 +01002531 private void gateKeeperClearSecureUserId(int userId) {
2532 try {
2533 getGateKeeperService().clearSecureUserId(userId);
2534 } catch (RemoteException e) {
2535 Slog.w(TAG, "Failed to clear SID", e);
2536 }
2537 }
2538
Andrew Scull1416bd02018-01-05 18:33:58 +00002539 private void onAuthTokenKnownForUser(@UserIdInt int userId, AuthenticationToken auth) {
David Anderson6ebc25b2019-02-12 16:25:56 -08002540 if (mInjector.isGsiRunning()) {
Kenny Rootf76cfc32019-11-08 14:36:03 -08002541 Slog.w(TAG, "Running in GSI; skipping calls to AuthSecret and RebootEscrow");
David Anderson6ebc25b2019-02-12 16:25:56 -08002542 return;
2543 }
2544
Kenny Rootf76cfc32019-11-08 14:36:03 -08002545 mRebootEscrowManager.callToRebootEscrowIfNeeded(userId, auth.getVersion(),
2546 auth.getSyntheticPassword());
2547
2548 callToAuthSecretIfNeeded(userId, auth);
2549 }
2550
2551 private void callToAuthSecretIfNeeded(@UserIdInt int userId,
2552 AuthenticationToken auth) {
Andrew Sculle6527c12018-01-05 18:33:58 +00002553 // Pass the primary user's auth secret to the HAL
2554 if (mAuthSecretService != null && mUserManager.getUserInfo(userId).isPrimary()) {
2555 try {
2556 final byte[] rawSecret = auth.deriveVendorAuthSecret();
2557 final ArrayList<Byte> secret = new ArrayList<>(rawSecret.length);
2558 for (int i = 0; i < rawSecret.length; ++i) {
2559 secret.add(rawSecret[i]);
2560 }
2561 mAuthSecretService.primaryUserCredential(secret);
2562 } catch (RemoteException e) {
2563 Slog.w(TAG, "Failed to pass primary user secret to AuthSecret HAL", e);
2564 }
2565 }
Andrew Scull1416bd02018-01-05 18:33:58 +00002566 }
2567
Andrew Scull1416bd02018-01-05 18:33:58 +00002568 /**
Rubin Xu3bf722a2016-12-15 16:07:38 +00002569 * Precondition: vold and keystore unlocked.
2570 *
2571 * Create new synthetic password, set up synthetic password blob protected by the supplied
2572 * user credential, and make the newly-created SP blob active.
2573 *
2574 * The invariant under a synthetic password is:
2575 * 1. If user credential exists, then both vold and keystore and protected with keys derived
2576 * from the synthetic password.
2577 * 2. If user credential does not exist, vold and keystore protection are cleared. This is to
2578 * make it consistent with current behaviour. It also allows ActivityManager to call
2579 * unlockUser() with empty secret.
2580 * 3. Once a user is migrated to have synthetic password, its value will never change, no matter
2581 * whether the user changes his lockscreen PIN or clear/reset it. When the user clears its
2582 * lockscreen PIN, we still maintain the existing synthetic password in a password blob
Andrew Scull1416bd02018-01-05 18:33:58 +00002583 * protected by a default PIN.
Rubin Xu3bf722a2016-12-15 16:07:38 +00002584 * 4. The user SID is linked with synthetic password, but its cleared/re-created when the user
2585 * clears/re-creates his lockscreen PIN.
2586 *
2587 *
2588 * Different cases of calling this method:
2589 * 1. credentialHash != null
2590 * This implies credential != null, a new SP blob will be provisioned, and existing SID
2591 * migrated to associate with the new SP.
2592 * This happens during a normal migration case when the user currently has password.
2593 *
2594 * 2. credentialhash == null and credential == null
Rubin Xu9a6d39a52018-02-07 08:52:34 +00002595 * A new SP blob and will be created, while the user has no credentials.
Rubin Xu3bf722a2016-12-15 16:07:38 +00002596 * This can happens when we are activating an escrow token on a unsecured device, during
2597 * which we want to create the SP structure with an empty user credential.
Rubin Xu9a6d39a52018-02-07 08:52:34 +00002598 * This could also happen during an untrusted reset to clear password.
Rubin Xu3bf722a2016-12-15 16:07:38 +00002599 *
2600 * 3. credentialhash == null and credential != null
Rubin Xud9522402019-11-06 13:54:27 +00002601 * The user sets a new lockscreen password FOR THE FIRST TIME on a SP-enabled device.
2602 * New credential and new SID will be created
Rubin Xu3bf722a2016-12-15 16:07:38 +00002603 */
Andrew Scull1416bd02018-01-05 18:33:58 +00002604 @GuardedBy("mSpManager")
Rubin Xu16c823e2017-06-27 14:44:58 +01002605 @VisibleForTesting
2606 protected AuthenticationToken initializeSyntheticPasswordLocked(byte[] credentialHash,
Rubin Xubb883202019-10-09 11:22:53 +01002607 LockscreenCredential credential, int userId) {
Rubin Xu3bf722a2016-12-15 16:07:38 +00002608 Slog.i(TAG, "Initialize SyntheticPassword for user: " + userId);
Rubin Xu9a6d39a52018-02-07 08:52:34 +00002609 final AuthenticationToken auth = mSpManager.newSyntheticPasswordAndSid(
2610 getGateKeeperService(), credentialHash, credential, userId);
Andrew Scull1416bd02018-01-05 18:33:58 +00002611 onAuthTokenKnownForUser(userId, auth);
Rubin Xu3bf722a2016-12-15 16:07:38 +00002612 if (auth == null) {
2613 Slog.wtf(TAG, "initializeSyntheticPasswordLocked returns null auth token");
2614 return null;
2615 }
2616 long handle = mSpManager.createPasswordBasedSyntheticPassword(getGateKeeperService(),
Rubin Xubb883202019-10-09 11:22:53 +01002617 credential, auth, userId);
2618 if (!credential.isNone()) {
Rubin Xu3bf722a2016-12-15 16:07:38 +00002619 if (credentialHash == null) {
2620 // Since when initializing SP, we didn't provide an existing password handle
2621 // for it to migrate SID, we need to create a new SID for the user.
2622 mSpManager.newSidForUser(getGateKeeperService(), auth, userId);
2623 }
2624 mSpManager.verifyChallenge(getGateKeeperService(), auth, 0L, userId);
2625 setAuthlessUserKeyProtection(userId, auth.deriveDiskEncryptionKey());
2626 setKeystorePassword(auth.deriveKeyStorePassword(), userId);
2627 } else {
Barani Muthukumaran9ba99ed2019-12-18 00:36:06 -08002628 clearUserKeyProtection(userId, null);
Rubin Xu3bf722a2016-12-15 16:07:38 +00002629 setKeystorePassword(null, userId);
Rubin Xuca6ece52019-07-31 15:02:13 +01002630 gateKeeperClearSecureUserId(userId);
Rubin Xu3bf722a2016-12-15 16:07:38 +00002631 }
2632 fixateNewestUserKeyAuth(userId);
Rubin Xue2f925f2019-08-14 16:53:55 +01002633 setSyntheticPasswordHandleLocked(handle, userId);
Rubin Xu3bf722a2016-12-15 16:07:38 +00002634 return auth;
2635 }
2636
Rubin Xu3589e892020-03-26 22:27:55 +00002637 @VisibleForTesting
2638 long getSyntheticPasswordHandleLocked(int userId) {
Adrian Roos60dcbbf2017-08-08 16:19:33 +02002639 return getLong(SYNTHETIC_PASSWORD_HANDLE_KEY,
2640 SyntheticPasswordManager.DEFAULT_HANDLE, userId);
Rubin Xu3bf722a2016-12-15 16:07:38 +00002641 }
2642
Rubin Xue2f925f2019-08-14 16:53:55 +01002643 private void setSyntheticPasswordHandleLocked(long handle, int userId) {
2644 final long oldHandle = getSyntheticPasswordHandleLocked(userId);
2645 setLong(SYNTHETIC_PASSWORD_HANDLE_KEY, handle, userId);
2646 setLong(PREV_SYNTHETIC_PASSWORD_HANDLE_KEY, oldHandle, userId);
2647 setLong(SYNTHETIC_PASSWORD_UPDATE_TIME_KEY, System.currentTimeMillis(), userId);
2648
2649 }
2650
Rubin Xu5e891bc2019-10-14 10:22:23 +01002651 @VisibleForTesting
2652 boolean isSyntheticPasswordBasedCredential(int userId) {
2653 synchronized (mSpManager) {
2654 return isSyntheticPasswordBasedCredentialLocked(userId);
2655 }
2656 }
2657
Rubin Xufcd49f92017-08-24 18:21:52 +01002658 private boolean isSyntheticPasswordBasedCredentialLocked(int userId) {
Adrian Roos7374d3a2017-03-31 14:14:53 -07002659 if (userId == USER_FRP) {
2660 final int type = mStorage.readPersistentDataBlock().type;
2661 return type == PersistentData.TYPE_SP || type == PersistentData.TYPE_SP_WEAVER;
2662 }
Rubin Xu3bf722a2016-12-15 16:07:38 +00002663 long handle = getSyntheticPasswordHandleLocked(userId);
Barani Muthukumaranbcbc5f52019-12-18 00:35:53 -08002664 return handle != SyntheticPasswordManager.DEFAULT_HANDLE;
Rubin Xu3bf722a2016-12-15 16:07:38 +00002665 }
2666
Rubin Xu16c823e2017-06-27 14:44:58 +01002667 @VisibleForTesting
Rubin Xufcd49f92017-08-24 18:21:52 +01002668 protected boolean shouldMigrateToSyntheticPasswordLocked(int userId) {
Barani Muthukumaranbcbc5f52019-12-18 00:35:53 -08002669 return true;
Rubin Xu3bf722a2016-12-15 16:07:38 +00002670 }
2671
Rubin Xubb883202019-10-09 11:22:53 +01002672 private VerifyCredentialResponse spBasedDoVerifyCredential(LockscreenCredential userCredential,
2673 @ChallengeType int challengeType, long challenge,
Kevin Chynbc29dd72019-06-13 11:47:54 -07002674 int userId, ICheckCredentialProgressCallback progressCallback,
Rubin Xuca6ece52019-07-31 15:02:13 +01002675 @Nullable ArrayList<PendingResetLockout> resetLockouts) {
Kevin Chynbe67ce02019-06-10 16:14:22 -07002676
Kevin Chyn28623b62019-06-11 11:43:33 -07002677 final boolean hasEnrolledBiometrics = mInjector.hasEnrolledBiometrics(userId);
Kevin Chynbe67ce02019-06-10 16:14:22 -07002678
Kevin Chynbc29dd72019-06-13 11:47:54 -07002679 Slog.d(TAG, "spBasedDoVerifyCredential: user=" + userId + " challengeType=" + challengeType
Kevin Chynbe67ce02019-06-10 16:14:22 -07002680 + " hasEnrolledBiometrics=" + hasEnrolledBiometrics);
Rubin Xue94a7702017-06-20 17:29:57 +01002681
Kevin Chyna38653c2019-02-11 17:46:21 -08002682 final PackageManager pm = mContext.getPackageManager();
2683 // TODO: When lockout is handled under the HAL for all biometrics (fingerprint),
2684 // we need to generate challenge for each one, have it signed by GK and reset lockout
2685 // for each modality.
Kevin Chynbc29dd72019-06-13 11:47:54 -07002686 if (challengeType == CHALLENGE_NONE && pm.hasSystemFeature(PackageManager.FEATURE_FACE)
Kevin Chynbe67ce02019-06-10 16:14:22 -07002687 && hasEnrolledBiometrics) {
Kevin Chynbc29dd72019-06-13 11:47:54 -07002688 // If there are multiple profiles in the same account, ensure we only generate the
2689 // challenge once.
2690 challengeType = CHALLENGE_INTERNAL;
Kevin Chyna38653c2019-02-11 17:46:21 -08002691 challenge = mContext.getSystemService(FaceManager.class).generateChallenge();
2692 }
2693
Rubin Xue94a7702017-06-20 17:29:57 +01002694 final AuthenticationResult authResult;
2695 VerifyCredentialResponse response;
2696 synchronized (mSpManager) {
2697 if (!isSyntheticPasswordBasedCredentialLocked(userId)) {
2698 return null;
2699 }
2700 if (userId == USER_FRP) {
2701 return mSpManager.verifyFrpCredential(getGateKeeperService(),
Rubin Xubb883202019-10-09 11:22:53 +01002702 userCredential, progressCallback);
Rubin Xue94a7702017-06-20 17:29:57 +01002703 }
2704
2705 long handle = getSyntheticPasswordHandleLocked(userId);
2706 authResult = mSpManager.unwrapPasswordBasedSyntheticPassword(
Rubin Xucf326f12017-11-15 11:55:35 +00002707 getGateKeeperService(), handle, userCredential, userId, progressCallback);
Rubin Xue94a7702017-06-20 17:29:57 +01002708
2709 response = authResult.gkResponse;
2710 // credential has matched
2711 if (response.getResponseCode() == VerifyCredentialResponse.RESPONSE_OK) {
2712 // perform verifyChallenge with synthetic password which generates the real GK auth
2713 // token and response for the current user
2714 response = mSpManager.verifyChallenge(getGateKeeperService(), authResult.authToken,
2715 challenge, userId);
2716 if (response.getResponseCode() != VerifyCredentialResponse.RESPONSE_OK) {
2717 // This shouldn't really happen: the unwrapping of SP succeeds, but SP doesn't
2718 // match the recorded GK password handle.
2719 Slog.wtf(TAG, "verifyChallenge with SP failed.");
2720 return VerifyCredentialResponse.ERROR;
2721 }
2722 }
Adrian Roos7374d3a2017-03-31 14:14:53 -07002723 }
Rubin Xu3bf722a2016-12-15 16:07:38 +00002724 if (response.getResponseCode() == VerifyCredentialResponse.RESPONSE_OK) {
Kevin Chynbc29dd72019-06-13 11:47:54 -07002725 // Do resetLockout / revokeChallenge when all profiles are unlocked
2726 if (hasEnrolledBiometrics) {
2727 if (resetLockouts == null) {
2728 resetLockouts = new ArrayList<>();
Kevin Chyna38653c2019-02-11 17:46:21 -08002729 }
Kevin Chynbc29dd72019-06-13 11:47:54 -07002730 resetLockouts.add(new PendingResetLockout(userId, response.getPayload()));
Kevin Chyna38653c2019-02-11 17:46:21 -08002731 }
Rubin Xu3bf722a2016-12-15 16:07:38 +00002732
Rubin Xu8a692732019-12-06 14:13:14 +00002733 onCredentialVerified(authResult.authToken, challengeType, challenge, resetLockouts,
Rubin Xu3589e892020-03-26 22:27:55 +00002734 PasswordMetrics.computeForCredential(userCredential), userId);
Rubin Xu3bf722a2016-12-15 16:07:38 +00002735 } else if (response.getResponseCode() == VerifyCredentialResponse.RESPONSE_RETRY) {
2736 if (response.getTimeout() > 0) {
2737 requireStrongAuth(STRONG_AUTH_REQUIRED_AFTER_LOCKOUT, userId);
2738 }
2739 }
2740
2741 return response;
2742 }
2743
Rubin Xu8a692732019-12-06 14:13:14 +00002744 private void onCredentialVerified(AuthenticationToken authToken,
2745 @ChallengeType int challengeType, long challenge,
Rubin Xu3589e892020-03-26 22:27:55 +00002746 @Nullable ArrayList<PendingResetLockout> resetLockouts, PasswordMetrics metrics,
2747 int userId) {
2748
2749 if (metrics != null) {
2750 synchronized (this) {
2751 mUserPasswordMetrics.put(userId, metrics);
2752 }
2753 } else {
2754 Slog.wtf(TAG, "Null metrics after credential verification");
2755 }
Rubin Xu8a692732019-12-06 14:13:14 +00002756
2757 unlockKeystore(authToken.deriveKeyStorePassword(), userId);
2758
2759 {
2760 final byte[] secret = authToken.deriveDiskEncryptionKey();
2761 unlockUser(userId, null, secret, challengeType, challenge, resetLockouts);
2762 Arrays.fill(secret, (byte) 0);
2763 }
2764 activateEscrowTokens(authToken, userId);
2765
2766 if (isManagedProfileWithSeparatedLock(userId)) {
2767 setDeviceUnlockedForUser(userId);
2768 }
2769 mStrongAuth.reportSuccessfulStrongAuthUnlock(userId);
2770
2771 onAuthTokenKnownForUser(userId, authToken);
2772 }
2773
Pavel Grafova8da6972019-04-03 13:58:58 +01002774 private void setDeviceUnlockedForUser(int userId) {
2775 final TrustManager trustManager = mContext.getSystemService(TrustManager.class);
2776 trustManager.setDeviceLockedForUser(userId, false);
2777 }
2778
Rubin Xu3bf722a2016-12-15 16:07:38 +00002779 /**
2780 * Change the user's lockscreen password by creating a new SP blob and update the handle, based
2781 * on an existing authentication token. Even though a new SP blob is created, the underlying
2782 * synthetic password is never changed.
2783 *
2784 * When clearing credential, we keep the SP unchanged, but clear its password handle so its
2785 * SID is gone. We also clear password from (software-based) keystore and vold, which will be
2786 * added back when new password is set in future.
2787 */
Andrew Scull1416bd02018-01-05 18:33:58 +00002788 @GuardedBy("mSpManager")
Rubin Xubb883202019-10-09 11:22:53 +01002789 private long setLockCredentialWithAuthTokenLocked(LockscreenCredential credential,
2790 AuthenticationToken auth, int userId) {
Rubin Xu3bf722a2016-12-15 16:07:38 +00002791 if (DEBUG) Slog.d(TAG, "setLockCredentialWithAuthTokenLocked: user=" + userId);
2792 long newHandle = mSpManager.createPasswordBasedSyntheticPassword(getGateKeeperService(),
Rubin Xubb883202019-10-09 11:22:53 +01002793 credential, auth, userId);
2794 final Map<Integer, LockscreenCredential> profilePasswords;
2795 if (!credential.isNone()) {
Rubin Xuca7007b2019-03-25 11:44:41 +00002796 // not needed by synchronizeUnifiedWorkChallengeForProfiles()
Rubin Xu3bf722a2016-12-15 16:07:38 +00002797 profilePasswords = null;
2798
2799 if (mSpManager.hasSidForUser(userId)) {
2800 // We are changing password of a secured device, nothing more needed as
2801 // createPasswordBasedSyntheticPassword has already taken care of maintaining
2802 // the password handle and SID unchanged.
2803
2804 //refresh auth token
2805 mSpManager.verifyChallenge(getGateKeeperService(), auth, 0L, userId);
2806 } else {
2807 // A new password is set on a previously-unsecured device, we need to generate
2808 // a new SID, and re-add keys to vold and keystore.
2809 mSpManager.newSidForUser(getGateKeeperService(), auth, userId);
2810 mSpManager.verifyChallenge(getGateKeeperService(), auth, 0L, userId);
2811 setAuthlessUserKeyProtection(userId, auth.deriveDiskEncryptionKey());
2812 fixateNewestUserKeyAuth(userId);
2813 setKeystorePassword(auth.deriveKeyStorePassword(), userId);
2814 }
2815 } else {
2816 // Cache all profile password if they use unified work challenge. This will later be
2817 // used to clear the profile's password in synchronizeUnifiedWorkChallengeForProfiles()
2818 profilePasswords = getDecryptedPasswordsForAllTiedProfiles(userId);
2819
2820 // we are clearing password of a secured device, so need to nuke SID as well.
2821 mSpManager.clearSidForUser(userId);
Rubin Xuca6ece52019-07-31 15:02:13 +01002822 gateKeeperClearSecureUserId(userId);
Rubin Xu3bf722a2016-12-15 16:07:38 +00002823 // Clear key from vold so ActivityManager can just unlock the user with empty secret
Rubin Xuca7007b2019-03-25 11:44:41 +00002824 // during boot. Vold storage needs to be unlocked before manipulation of the keys can
2825 // succeed.
2826 unlockUserKey(userId, null, auth.deriveDiskEncryptionKey());
Barani Muthukumaran9ba99ed2019-12-18 00:36:06 -08002827 clearUserKeyProtection(userId, auth.deriveDiskEncryptionKey());
Rubin Xu3bf722a2016-12-15 16:07:38 +00002828 fixateNewestUserKeyAuth(userId);
Rubin Xuca7007b2019-03-25 11:44:41 +00002829 unlockKeystore(auth.deriveKeyStorePassword(), userId);
Rubin Xu3bf722a2016-12-15 16:07:38 +00002830 setKeystorePassword(null, userId);
Alex Johnston6183cf92019-10-03 15:59:03 +01002831 removeBiometricsForUser(userId);
Rubin Xu3bf722a2016-12-15 16:07:38 +00002832 }
Rubin Xue2f925f2019-08-14 16:53:55 +01002833 setSyntheticPasswordHandleLocked(newHandle, userId);
Rubin Xu3bf722a2016-12-15 16:07:38 +00002834 synchronizeUnifiedWorkChallengeForProfiles(userId, profilePasswords);
Rubin Xu7cf45092017-08-28 11:47:35 +01002835
Rubin Xubb883202019-10-09 11:22:53 +01002836 setUserPasswordMetrics(credential, userId);
Rubin Xua3c71a12019-12-04 15:25:02 +00002837 mManagedProfilePasswordCache.removePassword(userId);
Rich Canningsf64ec632019-02-21 12:40:36 -08002838
2839 if (profilePasswords != null) {
Rubin Xubb883202019-10-09 11:22:53 +01002840 for (Map.Entry<Integer, LockscreenCredential> entry : profilePasswords.entrySet()) {
2841 entry.getValue().zeroize();
Rich Canningsf64ec632019-02-21 12:40:36 -08002842 }
2843 }
2844
Rubin Xu3bf722a2016-12-15 16:07:38 +00002845 return newHandle;
2846 }
2847
Alex Johnston6183cf92019-10-03 15:59:03 +01002848 private void removeBiometricsForUser(int userId) {
2849 removeAllFingerprintForUser(userId);
2850 removeAllFaceForUser(userId);
2851 }
2852
2853 private void removeAllFingerprintForUser(final int userId) {
2854 FingerprintManager mFingerprintManager = mInjector.getFingerprintManager();
2855 if (mFingerprintManager != null && mFingerprintManager.isHardwareDetected()) {
2856 if (mFingerprintManager.hasEnrolledFingerprints(userId)) {
2857 mFingerprintManager.setActiveUser(userId);
2858 CountDownLatch latch = new CountDownLatch(1);
2859 // For the purposes of M and N, groupId is the same as userId.
2860 Fingerprint finger = new Fingerprint(null, userId, 0, 0);
2861 mFingerprintManager.remove(finger, userId,
2862 fingerprintManagerRemovalCallback(latch));
2863 try {
2864 latch.await(10000, TimeUnit.MILLISECONDS);
2865 } catch (InterruptedException e) {
2866 Slog.e(TAG, "Latch interrupted when removing fingerprint", e);
2867 }
2868 }
2869 }
2870 }
2871
2872 private void removeAllFaceForUser(final int userId) {
2873 FaceManager mFaceManager = mInjector.getFaceManager();
2874 if (mFaceManager != null && mFaceManager.isHardwareDetected()) {
2875 if (mFaceManager.hasEnrolledTemplates(userId)) {
2876 mFaceManager.setActiveUser(userId);
2877 CountDownLatch latch = new CountDownLatch(1);
2878 Face face = new Face(null, 0, 0);
2879 mFaceManager.remove(face, userId, faceManagerRemovalCallback(latch));
2880 try {
2881 latch.await(10000, TimeUnit.MILLISECONDS);
2882 } catch (InterruptedException e) {
2883 Slog.e(TAG, "Latch interrupted when removing face", e);
2884 }
2885 }
2886 }
2887 }
2888
2889 private FingerprintManager.RemovalCallback fingerprintManagerRemovalCallback(
2890 CountDownLatch latch) {
2891 return new FingerprintManager.RemovalCallback() {
2892 @Override
2893 public void onRemovalError(Fingerprint fp, int errMsgId, CharSequence err) {
2894 Slog.e(TAG, String.format(
2895 "Can't remove fingerprint %d in group %d. Reason: %s",
2896 fp.getBiometricId(), fp.getGroupId(), err));
2897 latch.countDown();
2898 }
2899
2900 @Override
2901 public void onRemovalSucceeded(Fingerprint fp, int remaining) {
2902 if (remaining == 0) {
2903 latch.countDown();
2904 }
2905 }
2906 };
2907 }
2908
2909 private FaceManager.RemovalCallback faceManagerRemovalCallback(CountDownLatch latch) {
2910 return new FaceManager.RemovalCallback() {
2911 @Override
2912 public void onRemovalError(Face face, int errMsgId, CharSequence err) {
2913 Slog.e(TAG, String.format("Can't remove face %d. Reason: %s",
2914 face.getBiometricId(), err));
2915 latch.countDown();
2916 }
2917
2918 @Override
2919 public void onRemovalSucceeded(Face face, int remaining) {
2920 if (remaining == 0) {
2921 latch.countDown();
2922 }
2923 }
2924 };
2925 }
2926
Rubin Xubb883202019-10-09 11:22:53 +01002927 /**
2928 * @param savedCredential if the user is a managed profile with unified challenge and
2929 * savedCredential is empty, LSS will try to re-derive the profile password internally.
2930 * TODO (b/80170828): Fix this so profile password is always passed in.
2931 */
Andrew Scull1416bd02018-01-05 18:33:58 +00002932 @GuardedBy("mSpManager")
Rubin Xubb883202019-10-09 11:22:53 +01002933 private boolean spBasedSetLockCredentialInternalLocked(LockscreenCredential credential,
Rubin Xud9522402019-11-06 13:54:27 +00002934 LockscreenCredential savedCredential, int userId, boolean isLockTiedToParent) {
Rubin Xu3bf722a2016-12-15 16:07:38 +00002935 if (DEBUG) Slog.d(TAG, "spBasedSetLockCredentialInternalLocked: user=" + userId);
Rubin Xubb883202019-10-09 11:22:53 +01002936 if (savedCredential.isNone() && isManagedProfileWithUnifiedLock(userId)) {
Rubin Xu3bf722a2016-12-15 16:07:38 +00002937 // get credential from keystore when managed profile has unified lock
2938 try {
Rubin Xu0090c582020-03-06 14:34:16 +00002939 //TODO: remove as part of b/80170828
Rubin Xu3bf722a2016-12-15 16:07:38 +00002940 savedCredential = getDecryptedPasswordForTiedProfile(userId);
2941 } catch (FileNotFoundException e) {
2942 Slog.i(TAG, "Child profile key not found");
2943 } catch (UnrecoverableKeyException | InvalidKeyException | KeyStoreException
2944 | NoSuchAlgorithmException | NoSuchPaddingException
2945 | InvalidAlgorithmParameterException | IllegalBlockSizeException
2946 | BadPaddingException | CertificateException | IOException e) {
2947 Slog.e(TAG, "Failed to decrypt child profile key", e);
2948 }
2949 }
2950 long handle = getSyntheticPasswordHandleLocked(userId);
Rubin Xu8b30ec32017-03-05 00:47:09 +00002951 AuthenticationResult authResult = mSpManager.unwrapPasswordBasedSyntheticPassword(
Rubin Xucf326f12017-11-15 11:55:35 +00002952 getGateKeeperService(), handle, savedCredential, userId, null);
Rubin Xu8b30ec32017-03-05 00:47:09 +00002953 VerifyCredentialResponse response = authResult.gkResponse;
2954 AuthenticationToken auth = authResult.authToken;
Rubin Xu16c823e2017-06-27 14:44:58 +01002955
Rubin Xud9522402019-11-06 13:54:27 +00002956 if (auth == null) {
2957 if (response == null
2958 || response.getResponseCode() == VerifyCredentialResponse.RESPONSE_ERROR) {
2959 Slog.w(TAG, "Failed to enroll: incorrect credential.");
2960 return false;
Irina Dumitrescuc90674d2019-02-28 17:34:19 +00002961 }
Rubin Xud9522402019-11-06 13:54:27 +00002962 if (response.getResponseCode() == VerifyCredentialResponse.RESPONSE_RETRY) {
2963 Slog.w(TAG, "Failed to enroll: rate limit exceeded.");
2964 return false;
2965 }
2966 // Should not be reachable, but just in case.
2967 throw new IllegalStateException("password change failed");
Rubin Xu3bf722a2016-12-15 16:07:38 +00002968 }
Rubin Xu9a6d39a52018-02-07 08:52:34 +00002969
Rubin Xud9522402019-11-06 13:54:27 +00002970 onAuthTokenKnownForUser(userId, auth);
2971 setLockCredentialWithAuthTokenLocked(credential, auth, userId);
2972 mSpManager.destroyPasswordBasedSyntheticPassword(handle, userId);
Rubin Xubb883202019-10-09 11:22:53 +01002973 sendCredentialsOnChangeIfRequired(credential, userId, isLockTiedToParent);
Rubin Xu6a7303d2019-08-16 13:19:56 +01002974 return true;
Rubin Xuf095f832017-01-31 15:23:34 +00002975 }
2976
Rubin Xuf01e9072018-03-30 20:59:28 +01002977 /**
2978 * Returns a fixed pseudorandom byte string derived from the user's synthetic password.
2979 * This is used to salt the password history hash to protect the hash against offline
2980 * bruteforcing, since rederiving this value requires a successful authentication.
Rubin Xu4ed98982018-05-23 14:27:53 +01002981 * If user is a managed profile with unified challenge, currentCredential is ignored.
Rubin Xuf01e9072018-03-30 20:59:28 +01002982 */
2983 @Override
Rubin Xubb883202019-10-09 11:22:53 +01002984 public byte[] getHashFactor(LockscreenCredential currentCredential, int userId) {
Rubin Xuf01e9072018-03-30 20:59:28 +01002985 checkPasswordReadPermission(userId);
Rubin Xu4ed98982018-05-23 14:27:53 +01002986 if (isManagedProfileWithUnifiedLock(userId)) {
2987 try {
2988 currentCredential = getDecryptedPasswordForTiedProfile(userId);
2989 } catch (Exception e) {
2990 Slog.e(TAG, "Failed to get work profile credential", e);
2991 return null;
2992 }
2993 }
Rubin Xuf01e9072018-03-30 20:59:28 +01002994 synchronized (mSpManager) {
2995 if (!isSyntheticPasswordBasedCredentialLocked(userId)) {
2996 Slog.w(TAG, "Synthetic password not enabled");
2997 return null;
2998 }
2999 long handle = getSyntheticPasswordHandleLocked(userId);
3000 AuthenticationResult auth = mSpManager.unwrapPasswordBasedSyntheticPassword(
3001 getGateKeeperService(), handle, currentCredential, userId, null);
3002 if (auth.authToken == null) {
3003 Slog.w(TAG, "Current credential is incorrect");
3004 return null;
3005 }
3006 return auth.authToken.derivePasswordHashFactor();
3007 }
3008 }
3009
Rubin Xuca6ece52019-07-31 15:02:13 +01003010 private long addEscrowToken(byte[] token, int userId, EscrowTokenStateChangeCallback callback) {
Rubin Xuf095f832017-01-31 15:23:34 +00003011 if (DEBUG) Slog.d(TAG, "addEscrowToken: user=" + userId);
3012 synchronized (mSpManager) {
Rubin Xu8b30ec32017-03-05 00:47:09 +00003013 // Migrate to synthetic password based credentials if the user has no password,
Rubin Xuf095f832017-01-31 15:23:34 +00003014 // the token can then be activated immediately.
3015 AuthenticationToken auth = null;
3016 if (!isUserSecure(userId)) {
3017 if (shouldMigrateToSyntheticPasswordLocked(userId)) {
Rubin Xubb883202019-10-09 11:22:53 +01003018 auth = initializeSyntheticPasswordLocked(
3019 /* credentialHash */ null, LockscreenCredential.createNone(), userId);
Rubin Xuf095f832017-01-31 15:23:34 +00003020 } else /* isSyntheticPasswordBasedCredentialLocked(userId) */ {
3021 long pwdHandle = getSyntheticPasswordHandleLocked(userId);
3022 auth = mSpManager.unwrapPasswordBasedSyntheticPassword(getGateKeeperService(),
Rubin Xubb883202019-10-09 11:22:53 +01003023 pwdHandle, LockscreenCredential.createNone(), userId, null).authToken;
Rubin Xuf095f832017-01-31 15:23:34 +00003024 }
3025 }
Rubin Xu128180b2017-04-12 18:02:44 +01003026 if (isSyntheticPasswordBasedCredentialLocked(userId)) {
3027 disableEscrowTokenOnNonManagedDevicesIfNeeded(userId);
3028 if (!mSpManager.hasEscrowData(userId)) {
3029 throw new SecurityException("Escrow token is disabled on the current user");
3030 }
Rubin Xuf095f832017-01-31 15:23:34 +00003031 }
Ram Periathiruvadi32d53552019-02-19 13:25:46 -08003032 long handle = mSpManager.createTokenBasedSyntheticPassword(token, userId, callback);
Rubin Xuf095f832017-01-31 15:23:34 +00003033 if (auth != null) {
3034 mSpManager.activateTokenBasedSyntheticPassword(handle, auth, userId);
3035 }
3036 return handle;
3037 }
3038 }
3039
Rubin Xufcd49f92017-08-24 18:21:52 +01003040 private void activateEscrowTokens(AuthenticationToken auth, int userId) {
Rubin Xuf095f832017-01-31 15:23:34 +00003041 if (DEBUG) Slog.d(TAG, "activateEscrowTokens: user=" + userId);
3042 synchronized (mSpManager) {
Rubin Xue94a7702017-06-20 17:29:57 +01003043 disableEscrowTokenOnNonManagedDevicesIfNeeded(userId);
Rubin Xuf095f832017-01-31 15:23:34 +00003044 for (long handle : mSpManager.getPendingTokensForUser(userId)) {
3045 Slog.i(TAG, String.format("activateEscrowTokens: %x %d ", handle, userId));
3046 mSpManager.activateTokenBasedSyntheticPassword(handle, auth, userId);
3047 }
3048 }
3049 }
3050
Rubin Xufcd49f92017-08-24 18:21:52 +01003051 private boolean isEscrowTokenActive(long handle, int userId) {
Rubin Xuf095f832017-01-31 15:23:34 +00003052 synchronized (mSpManager) {
3053 return mSpManager.existsHandle(handle, userId);
3054 }
3055 }
3056
Rubin Xufc067732019-03-18 11:01:18 +00003057 @Override
3058 public boolean hasPendingEscrowToken(int userId) {
3059 checkPasswordReadPermission(userId);
3060 synchronized (mSpManager) {
3061 return !mSpManager.getPendingTokensForUser(userId).isEmpty();
3062 }
3063 }
3064
Rubin Xufcd49f92017-08-24 18:21:52 +01003065 private boolean removeEscrowToken(long handle, int userId) {
Rubin Xuf095f832017-01-31 15:23:34 +00003066 synchronized (mSpManager) {
3067 if (handle == getSyntheticPasswordHandleLocked(userId)) {
3068 Slog.w(TAG, "Cannot remove password handle");
3069 return false;
3070 }
3071 if (mSpManager.removePendingToken(handle, userId)) {
3072 return true;
3073 }
3074 if (mSpManager.existsHandle(handle, userId)) {
3075 mSpManager.destroyTokenBasedSyntheticPassword(handle, userId);
3076 return true;
3077 } else {
3078 return false;
3079 }
3080 }
3081 }
3082
Rubin Xubb883202019-10-09 11:22:53 +01003083 private boolean setLockCredentialWithToken(LockscreenCredential credential, long tokenHandle,
3084 byte[] token, int userId) {
Rubin Xuf095f832017-01-31 15:23:34 +00003085 boolean result;
3086 synchronized (mSpManager) {
3087 if (!mSpManager.hasEscrowData(userId)) {
3088 throw new SecurityException("Escrow token is disabled on the current user");
3089 }
Rubin Xubb883202019-10-09 11:22:53 +01003090 result = setLockCredentialWithTokenInternalLocked(
3091 credential, tokenHandle, token, userId);
Rubin Xuf095f832017-01-31 15:23:34 +00003092 }
3093 if (result) {
3094 synchronized (mSeparateChallengeLock) {
Rubin Xubb883202019-10-09 11:22:53 +01003095 setSeparateProfileChallengeEnabledLocked(userId, true, /* unused */ null);
Rubin Xuf095f832017-01-31 15:23:34 +00003096 }
Rubin Xubb883202019-10-09 11:22:53 +01003097 if (credential.isNone()) {
Rubin Xuca7007b2019-03-25 11:44:41 +00003098 // If clearing credential, unlock the user manually in order to progress user start
3099 // Call unlockUser() on a handler thread so no lock is held (either by LSS or by
3100 // the caller like DPMS), otherwise it can lead to deadlock.
3101 mHandler.post(() -> unlockUser(userId, null, null));
3102 }
Rubin Xuf095f832017-01-31 15:23:34 +00003103 notifyPasswordChanged(userId);
Pavel Grafov28939982017-10-03 15:11:52 +01003104 notifySeparateProfileChallengeChanged(userId);
Rubin Xuf095f832017-01-31 15:23:34 +00003105 }
3106 return result;
3107 }
3108
Rubin Xuca7007b2019-03-25 11:44:41 +00003109 @GuardedBy("mSpManager")
Rubin Xubb883202019-10-09 11:22:53 +01003110 private boolean setLockCredentialWithTokenInternalLocked(LockscreenCredential credential,
3111 long tokenHandle, byte[] token, int userId) {
Andrew Scull1416bd02018-01-05 18:33:58 +00003112 final AuthenticationResult result;
Rubin Xuca7007b2019-03-25 11:44:41 +00003113 result = mSpManager.unwrapTokenBasedSyntheticPassword(
3114 getGateKeeperService(), tokenHandle, token, userId);
3115 if (result.authToken == null) {
3116 Slog.w(TAG, "Invalid escrow token supplied");
3117 return false;
Rubin Xuf095f832017-01-31 15:23:34 +00003118 }
Rubin Xuca7007b2019-03-25 11:44:41 +00003119 if (result.gkResponse.getResponseCode() != VerifyCredentialResponse.RESPONSE_OK) {
3120 // Most likely, an untrusted credential reset happened in the past which
3121 // changed the synthetic password
3122 Slog.e(TAG, "Obsolete token: synthetic password derived but it fails GK "
3123 + "verification.");
3124 return false;
3125 }
Rubin Xud9522402019-11-06 13:54:27 +00003126 onAuthTokenKnownForUser(userId, result.authToken);
Rubin Xuca7007b2019-03-25 11:44:41 +00003127 long oldHandle = getSyntheticPasswordHandleLocked(userId);
Rubin Xubb883202019-10-09 11:22:53 +01003128 setLockCredentialWithAuthTokenLocked(credential, result.authToken, userId);
Rubin Xuca7007b2019-03-25 11:44:41 +00003129 mSpManager.destroyPasswordBasedSyntheticPassword(oldHandle, userId);
Andrew Scull1416bd02018-01-05 18:33:58 +00003130 return true;
Rubin Xuf095f832017-01-31 15:23:34 +00003131 }
3132
Rubin Xuca6ece52019-07-31 15:02:13 +01003133 private boolean unlockUserWithToken(long tokenHandle, byte[] token, int userId) {
Rubin Xuf095f832017-01-31 15:23:34 +00003134 AuthenticationResult authResult;
3135 synchronized (mSpManager) {
3136 if (!mSpManager.hasEscrowData(userId)) {
3137 throw new SecurityException("Escrow token is disabled on the current user");
3138 }
3139 authResult = mSpManager.unwrapTokenBasedSyntheticPassword(getGateKeeperService(),
3140 tokenHandle, token, userId);
3141 if (authResult.authToken == null) {
3142 Slog.w(TAG, "Invalid escrow token supplied");
Rubin Xufcd49f92017-08-24 18:21:52 +01003143 return false;
Rubin Xuf095f832017-01-31 15:23:34 +00003144 }
3145 }
Rubin Xu8a692732019-12-06 14:13:14 +00003146 // TODO: Reset biometrics lockout here. Ideally that should be self-contained inside
3147 // onCredentialVerified(), which will require some refactoring on the current lockout
3148 // reset logic.
Rubin Xu3589e892020-03-26 22:27:55 +00003149
3150 onCredentialVerified(authResult.authToken, CHALLENGE_NONE, 0, null,
3151 loadPasswordMetrics(authResult.authToken, userId), userId);
Rubin Xufcd49f92017-08-24 18:21:52 +01003152 return true;
Rubin Xu3bf722a2016-12-15 16:07:38 +00003153 }
3154
Rubin Xua3c71a12019-12-04 15:25:02 +00003155 @Override
3156 public boolean tryUnlockWithCachedUnifiedChallenge(int userId) {
3157 try (LockscreenCredential cred = mManagedProfilePasswordCache.retrievePassword(userId)) {
3158 if (cred == null) {
3159 return false;
3160 }
3161 return doVerifyCredential(cred, CHALLENGE_NONE, 0, userId, null /* progressCallback */)
3162 .getResponseCode() == VerifyCredentialResponse.RESPONSE_OK;
3163 }
3164 }
3165
3166 @Override
3167 public void removeCachedUnifiedChallenge(int userId) {
3168 mManagedProfilePasswordCache.removePassword(userId);
3169 }
3170
Rubin Xue2f925f2019-08-14 16:53:55 +01003171 static String timestampToString(long timestamp) {
3172 return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(timestamp));
3173 }
3174
Rubin Xude633f32020-04-02 16:37:32 +01003175 private static String credentialTypeToString(int credentialType) {
3176 switch (credentialType) {
3177 case CREDENTIAL_TYPE_NONE:
3178 return "None";
3179 case CREDENTIAL_TYPE_PATTERN:
3180 return "Pattern";
3181 case CREDENTIAL_TYPE_PIN:
3182 return "Pin";
3183 case CREDENTIAL_TYPE_PASSWORD:
3184 return "Password";
3185 default:
3186 return "Unknown " + credentialType;
3187 }
3188 }
3189
Rubin Xu3bf722a2016-12-15 16:07:38 +00003190 @Override
Rubin Xue2f925f2019-08-14 16:53:55 +01003191 protected void dump(FileDescriptor fd, PrintWriter printWriter, String[] args) {
3192 if (!DumpUtils.checkDumpPermission(mContext, TAG, printWriter)) return;
3193 IndentingPrintWriter pw = new IndentingPrintWriter(printWriter, " ");
Rubin Xu3bf722a2016-12-15 16:07:38 +00003194
Rubin Xua0a0d352017-05-15 16:18:01 +00003195 pw.println("Current lock settings service state:");
Rubin Xue2f925f2019-08-14 16:53:55 +01003196 pw.println();
Rubin Xu3bf722a2016-12-15 16:07:38 +00003197
Rubin Xue2f925f2019-08-14 16:53:55 +01003198 pw.println("User State:");
3199 pw.increaseIndent();
Rubin Xua0a0d352017-05-15 16:18:01 +00003200 List<UserInfo> users = mUserManager.getUsers();
3201 for (int user = 0; user < users.size(); user++) {
3202 final int userId = users.get(user).id;
Rubin Xue2f925f2019-08-14 16:53:55 +01003203 pw.println("User " + userId);
3204 pw.increaseIndent();
Rubin Xua0a0d352017-05-15 16:18:01 +00003205 synchronized (mSpManager) {
Rubin Xue2f925f2019-08-14 16:53:55 +01003206 pw.println(String.format("SP Handle: %x",
Rubin Xu3bf722a2016-12-15 16:07:38 +00003207 getSyntheticPasswordHandleLocked(userId)));
Rubin Xue2f925f2019-08-14 16:53:55 +01003208 pw.println(String.format("Last changed: %s (%x)",
3209 timestampToString(getLong(SYNTHETIC_PASSWORD_UPDATE_TIME_KEY, 0, userId)),
3210 getLong(PREV_SYNTHETIC_PASSWORD_HANDLE_KEY, 0, userId)));
Rubin Xua0a0d352017-05-15 16:18:01 +00003211 }
3212 try {
Rubin Xue2f925f2019-08-14 16:53:55 +01003213 pw.println(String.format("SID: %x",
Rubin Xua0a0d352017-05-15 16:18:01 +00003214 getGateKeeperService().getSecureUserId(userId)));
3215 } catch (RemoteException e) {
3216 // ignore.
Rubin Xu3bf722a2016-12-15 16:07:38 +00003217 }
Rubin Xue2f925f2019-08-14 16:53:55 +01003218 // It's OK to dump the password type since anyone with physical access can just
3219 // observe it from the keyguard directly.
Rubin Xu5e891bc2019-10-14 10:22:23 +01003220 pw.println("Quality: " + getKeyguardStoredQuality(userId));
Rubin Xude633f32020-04-02 16:37:32 +01003221 pw.println("CredentialType: " + credentialTypeToString(
3222 getCredentialTypeInternal(userId)));
Rubin Xuba6fef52019-10-25 11:10:43 +01003223 pw.println("SeparateChallenge: " + getSeparateProfileChallengeEnabledInternal(userId));
Rubin Xu5e891bc2019-10-14 10:22:23 +01003224 pw.println(String.format("Metrics: %s",
Rubin Xu19854862019-08-15 16:37:23 +01003225 getUserPasswordMetrics(userId) != null ? "known" : "unknown"));
Rubin Xue2f925f2019-08-14 16:53:55 +01003226 pw.decreaseIndent();
Rubin Xu3bf722a2016-12-15 16:07:38 +00003227 }
Rubin Xue2f925f2019-08-14 16:53:55 +01003228 pw.println();
3229 pw.decreaseIndent();
3230
3231 pw.println("Storage:");
3232 pw.increaseIndent();
3233 mStorage.dump(pw);
3234 pw.println();
3235 pw.decreaseIndent();
Haining Chenc06c4812020-01-13 20:38:53 -08003236
3237 pw.println("StrongAuth:");
3238 pw.increaseIndent();
3239 mStrongAuth.dump(pw);
3240 pw.println();
3241 pw.decreaseIndent();
Kenny Root61888782020-03-13 12:12:58 -07003242
3243 pw.println("RebootEscrow:");
3244 pw.increaseIndent();
3245 mRebootEscrowManager.dump(pw);
3246 pw.println();
3247 pw.decreaseIndent();
Rubin Xu3bf722a2016-12-15 16:07:38 +00003248 }
3249
Rubin Xu0f1e56d2019-08-23 13:34:25 +01003250 /**
3251 * Cryptographically disable escrow token support for the current user, if the user is not
3252 * managed (either user has a profile owner, or if device is managed). Do not disable
3253 * if we are running an automotive build.
3254 */
Rubin Xuf095f832017-01-31 15:23:34 +00003255 private void disableEscrowTokenOnNonManagedDevicesIfNeeded(int userId) {
Rubin Xu0f1e56d2019-08-23 13:34:25 +01003256 final UserManagerInternal userManagerInternal = mInjector.getUserManagerInternal();
Rakesh Iyercb18d562017-03-06 18:05:53 -08003257
Rubin Xu0f1e56d2019-08-23 13:34:25 +01003258 // Managed profile should have escrow enabled
3259 if (userManagerInternal.isUserManaged(userId)) {
3260 Slog.i(TAG, "Managed profile can have escrow token");
3261 return;
3262 }
Rakesh Iyercb18d562017-03-06 18:05:53 -08003263
Rubin Xu0f1e56d2019-08-23 13:34:25 +01003264 // Devices with Device Owner should have escrow enabled on all users.
3265 if (userManagerInternal.isDeviceManaged()) {
3266 Slog.i(TAG, "Corp-owned device can have escrow token");
3267 return;
3268 }
3269
3270 // If the device is yet to be provisioned (still in SUW), there is still
3271 // a chance that Device Owner will be set on the device later, so postpone
3272 // disabling escrow token for now.
3273 if (!mInjector.getDeviceStateCache().isDeviceProvisioned()) {
3274 Slog.i(TAG, "Postpone disabling escrow tokens until device is provisioned");
3275 return;
3276 }
3277
3278 // Escrow tokens are enabled on automotive builds.
3279 if (mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE)) {
3280 return;
3281 }
3282
3283 // Disable escrow token permanently on all other device/user types.
3284 Slog.i(TAG, "Disabling escrow token on user " + userId);
3285 if (isSyntheticPasswordBasedCredentialLocked(userId)) {
3286 mSpManager.destroyEscrowData(userId);
Rubin Xuf095f832017-01-31 15:23:34 +00003287 }
3288 }
3289
Adrian Roos7374d3a2017-03-31 14:14:53 -07003290 private class DeviceProvisionedObserver extends ContentObserver {
3291 private final Uri mDeviceProvisionedUri = Settings.Global.getUriFor(
3292 Settings.Global.DEVICE_PROVISIONED);
3293
3294 private boolean mRegistered;
3295
3296 public DeviceProvisionedObserver() {
3297 super(null);
3298 }
3299
3300 @Override
Andrew Scullede482d2018-01-30 13:54:29 +00003301 public void onChange(boolean selfChange, Uri uri, @UserIdInt int userId) {
Adrian Roos7374d3a2017-03-31 14:14:53 -07003302 if (mDeviceProvisionedUri.equals(uri)) {
3303 updateRegistration();
3304
3305 if (isProvisioned()) {
3306 Slog.i(TAG, "Reporting device setup complete to IGateKeeperService");
3307 reportDeviceSetupComplete();
Adrian Roos454f53f2017-08-08 14:56:42 +02003308 clearFrpCredentialIfOwnerNotSecure();
Adrian Roos7374d3a2017-03-31 14:14:53 -07003309 }
3310 }
3311 }
3312
3313 public void onSystemReady() {
Adrian Roos2adc2632017-09-05 17:01:42 +02003314 if (frpCredentialEnabled(mContext)) {
Adrian Roos7374d3a2017-03-31 14:14:53 -07003315 updateRegistration();
3316 } else {
3317 // If we don't intend to use frpCredentials and we're not provisioned yet, send
3318 // deviceSetupComplete immediately, so gatekeeper can discard any lingering
3319 // credentials immediately.
3320 if (!isProvisioned()) {
3321 Slog.i(TAG, "FRP credential disabled, reporting device setup complete "
3322 + "to Gatekeeper immediately");
3323 reportDeviceSetupComplete();
3324 }
3325 }
3326 }
3327
3328 private void reportDeviceSetupComplete() {
3329 try {
3330 getGateKeeperService().reportDeviceSetupComplete();
3331 } catch (RemoteException e) {
3332 Slog.e(TAG, "Failure reporting to IGateKeeperService", e);
3333 }
3334 }
3335
Adrian Roos454f53f2017-08-08 14:56:42 +02003336 /**
3337 * Clears the FRP credential if the user that controls it does not have a secure
3338 * lockscreen.
3339 */
3340 private void clearFrpCredentialIfOwnerNotSecure() {
3341 List<UserInfo> users = mUserManager.getUsers();
3342 for (UserInfo user : users) {
Adrian Roos2adc2632017-09-05 17:01:42 +02003343 if (userOwnsFrpCredential(mContext, user)) {
Adrian Roos454f53f2017-08-08 14:56:42 +02003344 if (!isUserSecure(user.id)) {
3345 mStorage.writePersistentDataBlock(PersistentData.TYPE_NONE, user.id,
3346 0, null);
3347 }
3348 return;
3349 }
3350 }
3351 }
3352
Adrian Roos7374d3a2017-03-31 14:14:53 -07003353 private void updateRegistration() {
3354 boolean register = !isProvisioned();
3355 if (register == mRegistered) {
3356 return;
3357 }
3358 if (register) {
3359 mContext.getContentResolver().registerContentObserver(mDeviceProvisionedUri,
3360 false, this);
3361 } else {
3362 mContext.getContentResolver().unregisterContentObserver(this);
3363 }
3364 mRegistered = register;
3365 }
3366
3367 private boolean isProvisioned() {
3368 return Settings.Global.getInt(mContext.getContentResolver(),
3369 Settings.Global.DEVICE_PROVISIONED, 0) != 0;
3370 }
3371 }
Rubin Xufcd49f92017-08-24 18:21:52 +01003372
3373 private final class LocalService extends LockSettingsInternal {
3374
3375 @Override
Ram Periathiruvadi32d53552019-02-19 13:25:46 -08003376 public long addEscrowToken(byte[] token, int userId,
3377 EscrowTokenStateChangeCallback callback) {
Rubin Xuca6ece52019-07-31 15:02:13 +01003378 return LockSettingsService.this.addEscrowToken(token, userId, callback);
Rubin Xufcd49f92017-08-24 18:21:52 +01003379 }
3380
3381 @Override
3382 public boolean removeEscrowToken(long handle, int userId) {
3383 return LockSettingsService.this.removeEscrowToken(handle, userId);
3384 }
3385
3386 @Override
3387 public boolean isEscrowTokenActive(long handle, int userId) {
3388 return LockSettingsService.this.isEscrowTokenActive(handle, userId);
3389 }
3390
3391 @Override
Rubin Xubb883202019-10-09 11:22:53 +01003392 public boolean setLockCredentialWithToken(LockscreenCredential credential, long tokenHandle,
3393 byte[] token, int userId) {
Rubin Xu3744acf2020-01-02 16:39:50 +00003394 if (!mHasSecureLockScreen) {
Lenka Trochtova66c492a2018-12-06 11:29:21 +01003395 throw new UnsupportedOperationException(
3396 "This operation requires secure lock screen feature.");
3397 }
Rubin Xubb883202019-10-09 11:22:53 +01003398 return LockSettingsService.this.setLockCredentialWithToken(
3399 credential, tokenHandle, token, userId);
Rubin Xufcd49f92017-08-24 18:21:52 +01003400 }
3401
3402 @Override
3403 public boolean unlockUserWithToken(long tokenHandle, byte[] token, int userId) {
Rubin Xuca6ece52019-07-31 15:02:13 +01003404 return LockSettingsService.this.unlockUserWithToken(tokenHandle, token, userId);
Rubin Xufcd49f92017-08-24 18:21:52 +01003405 }
Rubin Xu19854862019-08-15 16:37:23 +01003406
3407 @Override
3408 public PasswordMetrics getUserPasswordMetrics(int userHandle) {
3409 long identity = Binder.clearCallingIdentity();
3410 try {
3411 if (isManagedProfileWithUnifiedLock(userHandle)) {
3412 // A managed profile with unified challenge is supposed to be protected by the
3413 // parent lockscreen, so asking for its password metrics is not really useful,
3414 // as this method would just return the metrics of the random profile password
3415 Slog.w(TAG, "Querying password metrics for unified challenge profile: "
3416 + userHandle);
3417 }
3418 } finally {
3419 Binder.restoreCallingIdentity(identity);
3420 }
3421 return LockSettingsService.this.getUserPasswordMetrics(userHandle);
3422 }
3423
Kenny Rootf76cfc32019-11-08 14:36:03 -08003424 @Override
3425 public void prepareRebootEscrow() {
3426 if (!mRebootEscrowManager.prepareRebootEscrow()) {
3427 return;
3428 }
3429 mStrongAuth.requireStrongAuth(STRONG_AUTH_REQUIRED_FOR_UNATTENDED_UPDATE, USER_ALL);
3430 }
3431
3432 @Override
3433 public void setRebootEscrowListener(RebootEscrowListener listener) {
3434 mRebootEscrowManager.setRebootEscrowListener(listener);
3435 }
3436
3437 @Override
3438 public void clearRebootEscrow() {
3439 if (!mRebootEscrowManager.clearRebootEscrow()) {
3440 return;
3441 }
3442 mStrongAuth.noLongerRequireStrongAuth(STRONG_AUTH_REQUIRED_FOR_UNATTENDED_UPDATE,
3443 USER_ALL);
3444 }
3445
3446 @Override
3447 public boolean armRebootEscrow() {
3448 return mRebootEscrowManager.armRebootEscrowIfNeeded();
3449 }
Rubin Xu9e765ab2020-04-29 15:06:30 +01003450
3451 @Override
3452 public void refreshStrongAuthTimeout(int userId) {
3453 mStrongAuth.refreshStrongAuthTimeout(userId);
3454 }
Kenny Rootf76cfc32019-11-08 14:36:03 -08003455 }
3456
3457 private class RebootEscrowCallbacks implements RebootEscrowManager.Callbacks {
3458 @Override
3459 public boolean isUserSecure(int userId) {
3460 return LockSettingsService.this.isUserSecure(userId);
3461 }
3462
3463 @Override
3464 public void onRebootEscrowRestored(byte spVersion, byte[] syntheticPassword, int userId) {
3465 SyntheticPasswordManager.AuthenticationToken
3466 authToken = new SyntheticPasswordManager.AuthenticationToken(spVersion);
3467 authToken.recreateDirectly(syntheticPassword);
Rubin Xu3589e892020-03-26 22:27:55 +00003468 onCredentialVerified(authToken, CHALLENGE_NONE, 0, null,
3469 loadPasswordMetrics(authToken, userId), userId);
Kenny Rootf76cfc32019-11-08 14:36:03 -08003470 }
Rubin Xufcd49f92017-08-24 18:21:52 +01003471 }
Amith Yamasani52c489c2012-03-28 11:42:42 -07003472}