blob: ee968c87e75313f9a406db6a550bed80616e65d6 [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;
20import static android.Manifest.permission.READ_CONTACTS;
21import static android.content.Context.KEYGUARD_SERVICE;
Adrian Roosb953e182017-08-17 17:58:26 +020022import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Adrian Roos7374d3a2017-03-31 14:14:53 -070023
Rubin Xu3bf722a2016-12-15 16:07:38 +000024import static com.android.internal.widget.LockPatternUtils.SYNTHETIC_PASSWORD_ENABLED_KEY;
25import static com.android.internal.widget.LockPatternUtils.SYNTHETIC_PASSWORD_HANDLE_KEY;
Bo Zhuc7048342019-01-03 14:04:58 -080026import static com.android.internal.widget.LockPatternUtils.StrongAuthTracker.STRONG_AUTH_REQUIRED_AFTER_BOOT;
27import static com.android.internal.widget.LockPatternUtils.StrongAuthTracker.STRONG_AUTH_REQUIRED_AFTER_LOCKOUT;
Adrian Roos7374d3a2017-03-31 14:14:53 -070028import static com.android.internal.widget.LockPatternUtils.USER_FRP;
29import static com.android.internal.widget.LockPatternUtils.frpCredentialEnabled;
Adrian Roos454f53f2017-08-08 14:56:42 +020030import static com.android.internal.widget.LockPatternUtils.userOwnsFrpCredential;
Rubin Xu1de89b32016-11-30 20:03:13 +000031
Dmitry Dementyev1aa96132017-12-11 11:33:12 -080032import android.annotation.NonNull;
33import android.annotation.Nullable;
Andrew Scull5daf2732016-11-14 15:02:45 +000034import android.annotation.UserIdInt;
Sudheer Shankadc589ac2016-11-10 15:30:17 -080035import android.app.ActivityManager;
Rubin Xu0cbc19e2016-12-09 14:00:21 +000036import android.app.IActivityManager;
Kenny Guyb1b30262016-02-09 16:02:35 +000037import android.app.KeyguardManager;
Jim Miller4f93c582016-01-27 19:05:43 -080038import android.app.Notification;
39import android.app.NotificationManager;
40import android.app.PendingIntent;
Adrian Roos230635e2015-01-07 20:50:29 +010041import android.app.admin.DevicePolicyManager;
Pavel Grafov28939982017-10-03 15:11:52 +010042import android.app.admin.DevicePolicyManagerInternal;
Andrew Scull5daf2732016-11-14 15:02:45 +000043import android.app.admin.PasswordMetrics;
Amith Yamasani072543f2015-02-13 11:09:45 -080044import android.app.backup.BackupManager;
Adrian Roosb5e47222015-08-14 15:53:06 -070045import android.app.trust.IStrongAuthTracker;
Clara Bayarri56878a92015-10-29 15:43:55 +000046import android.app.trust.TrustManager;
Robin Leef0246a82014-08-13 09:50:25 +010047import android.content.BroadcastReceiver;
Amith Yamasani52c489c2012-03-28 11:42:42 -070048import android.content.ContentResolver;
Amith Yamasani52c489c2012-03-28 11:42:42 -070049import android.content.Context;
Robin Leef0246a82014-08-13 09:50:25 +010050import android.content.Intent;
51import android.content.IntentFilter;
Jim Miller158fe192013-04-17 15:23:55 -070052import android.content.pm.PackageManager;
Jim Miller187ec582013-04-15 18:27:54 -070053import android.content.pm.UserInfo;
Jim Miller4f93c582016-01-27 19:05:43 -080054import android.content.res.Resources;
Adrian Roos7374d3a2017-03-31 14:14:53 -070055import android.database.ContentObserver;
Amith Yamasani52c489c2012-03-28 11:42:42 -070056import android.database.sqlite.SQLiteDatabase;
Andrew Sculle6527c12018-01-05 18:33:58 +000057import android.hardware.authsecret.V1_0.IAuthSecret;
Kevin Chyna38653c2019-02-11 17:46:21 -080058import android.hardware.biometrics.BiometricManager;
59import android.hardware.face.FaceManager;
Adrian Roos7374d3a2017-03-31 14:14:53 -070060import android.net.Uri;
Amith Yamasani52c489c2012-03-28 11:42:42 -070061import android.os.Binder;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -060062import android.os.Bundle;
Ricky Waib0cdf382016-05-16 17:28:04 +010063import android.os.Handler;
Paul Lawrence945490c2014-03-27 16:37:28 +000064import android.os.IBinder;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -060065import android.os.IProgressListener;
Ricky Wai4613fe42016-05-24 11:11:42 +010066import android.os.Process;
Amith Yamasani52c489c2012-03-28 11:42:42 -070067import android.os.RemoteException;
Jorim Jaggi2fef6f72016-11-01 19:06:25 -070068import android.os.ResultReceiver;
Paul Lawrence945490c2014-03-27 16:37:28 +000069import android.os.ServiceManager;
Rubin Xu1de89b32016-11-30 20:03:13 +000070import android.os.ShellCallback;
Jeff Sharkeyeddf5182016-08-09 16:36:08 -060071import android.os.StrictMode;
Amith Yamasanid1645f82012-06-12 11:53:26 -070072import android.os.SystemProperties;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070073import android.os.UserHandle;
Jim Miller187ec582013-04-15 18:27:54 -070074import android.os.UserManager;
Rubin Xu1de89b32016-11-30 20:03:13 +000075import android.os.storage.IStorageManager;
76import android.os.storage.StorageManager;
Amith Yamasani52c489c2012-03-28 11:42:42 -070077import android.provider.Settings;
78import android.provider.Settings.Secure;
Jim Miller187ec582013-04-15 18:27:54 -070079import android.provider.Settings.SettingNotFoundException;
Jim Millerde1af082013-09-11 14:58:26 -070080import android.security.KeyStore;
Ricky Waidc283a82016-03-24 19:55:08 +000081import android.security.keystore.AndroidKeyStoreProvider;
82import android.security.keystore.KeyProperties;
83import android.security.keystore.KeyProtection;
Pavel Grafov0acc4bf2017-08-23 12:20:54 +010084import android.security.keystore.UserNotAuthenticatedException;
Dmitry Dementyev0916e7c2018-01-23 13:02:08 -080085import android.security.keystore.recovery.KeyChainProtectionParams;
Bo Zhuc7048342019-01-03 14:04:58 -080086import android.security.keystore.recovery.KeyChainSnapshot;
Bo Zhu7c1972f2018-02-22 21:43:52 -080087import android.security.keystore.recovery.RecoveryCertPath;
Robert Berry81ee34b2018-01-23 11:59:59 +000088import android.security.keystore.recovery.WrappedApplicationKey;
Andres Morales23974272015-05-14 22:42:26 -070089import android.service.gatekeeper.GateKeeperResponse;
Andres Morales8fa56652015-03-31 09:19:50 -070090import android.service.gatekeeper.IGateKeeperService;
Amith Yamasani52c489c2012-03-28 11:42:42 -070091import android.text.TextUtils;
Rubin Xua55b1682017-01-31 10:06:56 +000092import android.util.ArrayMap;
Adrian Roosb953e182017-08-17 17:58:26 +020093import android.util.EventLog;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -060094import android.util.Log;
Amith Yamasani52c489c2012-03-28 11:42:42 -070095import android.util.Slog;
Andrew Scull1416bd02018-01-05 18:33:58 +000096import android.util.SparseArray;
Amith Yamasani52c489c2012-03-28 11:42:42 -070097
Pavel Grafov28939982017-10-03 15:11:52 +010098import com.android.internal.annotations.GuardedBy;
Rubin Xu0cbc19e2016-12-09 14:00:21 +000099import com.android.internal.annotations.VisibleForTesting;
Chris Wren282cfef2017-03-27 15:01:44 -0400100import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
Geoffrey Pitschaf759c52017-02-15 09:35:38 -0500101import com.android.internal.notification.SystemNotificationChannels;
Amith Yamasani072543f2015-02-13 11:09:45 -0800102import com.android.internal.util.ArrayUtils;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -0600103import com.android.internal.util.DumpUtils;
Adrian Roos7374d3a2017-03-31 14:14:53 -0700104import com.android.internal.util.Preconditions;
Jorim Jaggie8fde5d2016-06-30 23:41:37 -0700105import com.android.internal.widget.ICheckCredentialProgressCallback;
Jeff Sharkey7a96c392012-11-15 14:01:46 -0800106import com.android.internal.widget.ILockSettings;
107import com.android.internal.widget.LockPatternUtils;
Rubin Xufcd49f92017-08-24 18:21:52 +0100108import com.android.internal.widget.LockSettingsInternal;
Andres Morales23974272015-05-14 22:42:26 -0700109import com.android.internal.widget.VerifyCredentialResponse;
Pavel Grafov28939982017-10-03 15:11:52 +0100110import com.android.server.LocalServices;
Andrew Scull507d11c2017-05-03 17:19:01 +0100111import com.android.server.SystemService;
112import com.android.server.locksettings.LockSettingsStorage.CredentialHash;
Dmitry Dementyev1aa96132017-12-11 11:33:12 -0800113import com.android.server.locksettings.LockSettingsStorage.PersistentData;
Andrew Scull507d11c2017-05-03 17:19:01 +0100114import com.android.server.locksettings.SyntheticPasswordManager.AuthenticationResult;
115import com.android.server.locksettings.SyntheticPasswordManager.AuthenticationToken;
Bo Zhuc7048342019-01-03 14:04:58 -0800116import com.android.server.locksettings.recoverablekeystore.RecoverableKeyStoreManager;
Adrian Roos1c8e3c02018-11-20 20:07:55 +0100117import com.android.server.wm.WindowManagerInternal;
Jeff Sharkey7a96c392012-11-15 14:01:46 -0800118
Ricky Waidc283a82016-03-24 19:55:08 +0000119import libcore.util.HexEncoding;
120
121import java.io.ByteArrayOutputStream;
Jorim Jaggi2fef6f72016-11-01 19:06:25 -0700122import java.io.FileDescriptor;
Ricky Waidc283a82016-03-24 19:55:08 +0000123import java.io.FileNotFoundException;
124import java.io.IOException;
Rubin Xu3bf722a2016-12-15 16:07:38 +0000125import java.io.PrintWriter;
Ricky Waidc283a82016-03-24 19:55:08 +0000126import java.security.InvalidAlgorithmParameterException;
127import java.security.InvalidKeyException;
128import java.security.KeyStoreException;
Paul Crowleyfaeb3eb2016-02-08 15:58:29 +0000129import java.security.MessageDigest;
130import java.security.NoSuchAlgorithmException;
Ricky Waidc283a82016-03-24 19:55:08 +0000131import java.security.SecureRandom;
132import java.security.UnrecoverableKeyException;
133import java.security.cert.CertificateException;
Andrew Sculle6527c12018-01-05 18:33:58 +0000134import java.util.ArrayList;
Bo Zhuc7048342019-01-03 14:04:58 -0800135import java.util.Arrays;
Jim Miller187ec582013-04-15 18:27:54 -0700136import java.util.List;
Rubin Xua55b1682017-01-31 10:06:56 +0000137import java.util.Map;
Andrew Sculle6527c12018-01-05 18:33:58 +0000138import java.util.NoSuchElementException;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -0600139import java.util.concurrent.CountDownLatch;
140import java.util.concurrent.TimeUnit;
Amith Yamasani52c489c2012-03-28 11:42:42 -0700141
Ricky Waidc283a82016-03-24 19:55:08 +0000142import javax.crypto.BadPaddingException;
143import javax.crypto.Cipher;
144import javax.crypto.IllegalBlockSizeException;
145import javax.crypto.KeyGenerator;
146import javax.crypto.NoSuchPaddingException;
147import javax.crypto.SecretKey;
148import javax.crypto.spec.GCMParameterSpec;
149
Amith Yamasani52c489c2012-03-28 11:42:42 -0700150/**
Rubin Xu1de89b32016-11-30 20:03:13 +0000151 * Keeps the lock pattern/password data and related settings for each user. Used by
152 * LockPatternUtils. Needs to be a service because Settings app also needs to be able to save
153 * lockscreen information for secondary users.
154 *
Amith Yamasani52c489c2012-03-28 11:42:42 -0700155 * @hide
156 */
157public class LockSettingsService extends ILockSettings.Stub {
Amith Yamasani52c489c2012-03-28 11:42:42 -0700158 private static final String TAG = "LockSettingsService";
Jim Miller4f93c582016-01-27 19:05:43 -0800159 private static final String PERMISSION = ACCESS_KEYGUARD_SECURE_STORAGE;
Jim Miller4f93c582016-01-27 19:05:43 -0800160 private static final boolean DEBUG = false;
Amith Yamasani52c489c2012-03-28 11:42:42 -0700161
Ricky Waidc283a82016-03-24 19:55:08 +0000162 private static final int PROFILE_KEY_IV_SIZE = 12;
163 private static final String SEPARATE_PROFILE_CHALLENGE_KEY = "lockscreen.profilechallenge";
Paul Crowley7a0cc0a2017-05-31 22:12:57 +0000164 private static final int SYNTHETIC_PASSWORD_ENABLED_BY_DEFAULT = 1;
Rubin Xu1de89b32016-11-30 20:03:13 +0000165
Rubin Xua0a0d352017-05-15 16:18:01 +0000166 // Order of holding lock: mSeparateChallengeLock -> mSpManager -> this
Rubin Xue94a7702017-06-20 17:29:57 +0100167 // Do not call into ActivityManager while holding mSpManager lock.
Ricky Waidc283a82016-03-24 19:55:08 +0000168 private final Object mSeparateChallengeLock = new Object();
169
Adrian Roos7374d3a2017-03-31 14:14:53 -0700170 private final DeviceProvisionedObserver mDeviceProvisionedObserver =
171 new DeviceProvisionedObserver();
172
Rubin Xu0cbc19e2016-12-09 14:00:21 +0000173 private final Injector mInjector;
Amith Yamasani52c489c2012-03-28 11:42:42 -0700174 private final Context mContext;
Rubin Xu7cf45092017-08-28 11:47:35 +0100175 @VisibleForTesting
176 protected final Handler mHandler;
Rubin Xu0cbc19e2016-12-09 14:00:21 +0000177 @VisibleForTesting
178 protected final LockSettingsStorage mStorage;
Rakesh Iyera7aa4d62016-01-19 17:27:23 -0800179 private final LockSettingsStrongAuth mStrongAuth;
Victor Changa0940d32016-05-16 19:36:08 +0100180 private final SynchronizedStrongAuthTracker mStrongAuthTracker;
Adrian Roos261d5ab2014-10-29 14:42:38 +0100181
Rubin Xu0cbc19e2016-12-09 14:00:21 +0000182 private final LockPatternUtils mLockPatternUtils;
183 private final NotificationManager mNotificationManager;
184 private final UserManager mUserManager;
185 private final IActivityManager mActivityManager;
Andrew Scull8fc2ec82017-05-19 10:50:36 +0100186 private final SyntheticPasswordManager mSpManager;
Rubin Xu0cbc19e2016-12-09 14:00:21 +0000187
188 private final KeyStore mKeyStore;
189
Dmitry Dementyev1aa96132017-12-11 11:33:12 -0800190 private final RecoverableKeyStoreManager mRecoverableKeyStoreManager;
191
Paul Lawrence945490c2014-03-27 16:37:28 +0000192 private boolean mFirstCallToVold;
Rubin Xu0cbc19e2016-12-09 14:00:21 +0000193 protected IGateKeeperService mGateKeeperService;
Andrew Sculle6527c12018-01-05 18:33:58 +0000194 protected IAuthSecret mAuthSecretService;
Rubin Xu3bf722a2016-12-15 16:07:38 +0000195
David Anderson6ebc25b2019-02-12 16:25:56 -0800196 private static final String GSI_RUNNING_PROP = "ro.gsid.image_running";
197
Ricky Wai4613fe42016-05-24 11:11:42 +0100198 /**
199 * The UIDs that are used for system credential storage in keystore.
200 */
Rubin Xu1de89b32016-11-30 20:03:13 +0000201 private static final int[] SYSTEM_CREDENTIAL_UIDS = {
202 Process.WIFI_UID, Process.VPN_UID,
Rubin Xu24b89b12017-04-26 19:44:16 +0100203 Process.ROOT_UID, Process.SYSTEM_UID };
Andres Morales23974272015-05-14 22:42:26 -0700204
Jim Miller4f93c582016-01-27 19:05:43 -0800205 // This class manages life cycle events for encrypted users on File Based Encryption (FBE)
206 // devices. The most basic of these is to show/hide notifications about missing features until
207 // the user unlocks the account and credential-encrypted storage is available.
208 public static final class Lifecycle extends SystemService {
209 private LockSettingsService mLockSettingsService;
210
211 public Lifecycle(Context context) {
212 super(context);
213 }
214
215 @Override
216 public void onStart() {
Ricky Waidc283a82016-03-24 19:55:08 +0000217 AndroidKeyStoreProvider.install();
Jim Miller4f93c582016-01-27 19:05:43 -0800218 mLockSettingsService = new LockSettingsService(getContext());
219 publishBinderService("lock_settings", mLockSettingsService);
220 }
221
222 @Override
Adrian Roos60dcbbf2017-08-08 16:19:33 +0200223 public void onBootPhase(int phase) {
224 super.onBootPhase(phase);
225 if (phase == PHASE_ACTIVITY_MANAGER_READY) {
226 mLockSettingsService.migrateOldDataAfterSystemReady();
227 }
228 }
229
230 @Override
Andrew Scull85a63bc2016-10-24 13:47:47 +0100231 public void onStartUser(int userHandle) {
232 mLockSettingsService.onStartUser(userHandle);
Jim Miller4f93c582016-01-27 19:05:43 -0800233 }
234
235 @Override
236 public void onUnlockUser(int userHandle) {
237 mLockSettingsService.onUnlockUser(userHandle);
238 }
239
240 @Override
241 public void onCleanupUser(int userHandle) {
242 mLockSettingsService.onCleanupUser(userHandle);
243 }
244 }
245
Rubin Xu0cbc19e2016-12-09 14:00:21 +0000246 @VisibleForTesting
247 protected static class SynchronizedStrongAuthTracker
248 extends LockPatternUtils.StrongAuthTracker {
Victor Changa0940d32016-05-16 19:36:08 +0100249 public SynchronizedStrongAuthTracker(Context context) {
250 super(context);
251 }
252
253 @Override
254 protected void handleStrongAuthRequiredChanged(int strongAuthFlags, int userId) {
255 synchronized (this) {
256 super.handleStrongAuthRequiredChanged(strongAuthFlags, userId);
257 }
258 }
259
260 @Override
261 public int getStrongAuthForUser(int userId) {
262 synchronized (this) {
263 return super.getStrongAuthForUser(userId);
264 }
265 }
266
Rubin Xu0cbc19e2016-12-09 14:00:21 +0000267 void register(LockSettingsStrongAuth strongAuth) {
268 strongAuth.registerStrongAuthTracker(this.mStub);
Victor Changa0940d32016-05-16 19:36:08 +0100269 }
270 }
271
Ricky Waidc283a82016-03-24 19:55:08 +0000272 /**
273 * Tie managed profile to primary profile if it is in unified mode and not tied before.
274 *
275 * @param managedUserId Managed profile user Id
276 * @param managedUserPassword Managed profile original password (when it has separated lock).
277 * NULL when it does not have a separated lock before.
278 */
Rich Canningsf64ec632019-02-21 12:40:36 -0800279 public void tieManagedProfileLockIfNecessary(int managedUserId, byte[] managedUserPassword) {
Ricky Waidc283a82016-03-24 19:55:08 +0000280 if (DEBUG) Slog.v(TAG, "Check child profile lock for user: " + managedUserId);
281 // Only for managed profile
Rubin Xu0cbc19e2016-12-09 14:00:21 +0000282 if (!mUserManager.getUserInfo(managedUserId).isManagedProfile()) {
Ricky Waidc283a82016-03-24 19:55:08 +0000283 return;
284 }
285 // Do not tie managed profile when work challenge is enabled
286 if (mLockPatternUtils.isSeparateProfileChallengeEnabled(managedUserId)) {
287 return;
288 }
289 // Do not tie managed profile to parent when it's done already
290 if (mStorage.hasChildProfileLock(managedUserId)) {
291 return;
292 }
293 // Do not tie it to parent when parent does not have a screen lock
294 final int parentId = mUserManager.getProfileParent(managedUserId).id;
Rubin Xua55b1682017-01-31 10:06:56 +0000295 if (!isUserSecure(parentId)) {
Ricky Waidc283a82016-03-24 19:55:08 +0000296 if (DEBUG) Slog.v(TAG, "Parent does not have a screen lock");
297 return;
298 }
Rubin Xubfc7faaf2016-11-22 15:18:32 +0000299 // Do not tie when the parent has no SID (but does have a screen lock).
300 // This can only happen during an upgrade path where SID is yet to be
301 // generated when the user unlocks for the first time.
302 try {
303 if (getGateKeeperService().getSecureUserId(parentId) == 0) {
304 return;
305 }
306 } catch (RemoteException e) {
307 Slog.e(TAG, "Failed to talk to GateKeeper service", e);
308 return;
309 }
Ricky Waidc283a82016-03-24 19:55:08 +0000310 if (DEBUG) Slog.v(TAG, "Tie managed profile to parent now!");
311 byte[] randomLockSeed = new byte[] {};
312 try {
313 randomLockSeed = SecureRandom.getInstance("SHA1PRNG").generateSeed(40);
Rich Canningsf64ec632019-02-21 12:40:36 -0800314 char[] newPasswordChars = HexEncoding.encode(randomLockSeed);
315 byte[] newPassword = new byte[newPasswordChars.length];
316 for (int i = 0; i < newPasswordChars.length; i++) {
317 newPassword[i] = (byte) newPasswordChars[i];
318 }
319 Arrays.fill(newPasswordChars, '\u0000');
Adrian Roos7374d3a2017-03-31 14:14:53 -0700320 final int quality = DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC;
Rubin Xu1de89b32016-11-30 20:03:13 +0000321 setLockCredentialInternal(newPassword, LockPatternUtils.CREDENTIAL_TYPE_PASSWORD,
Adrian Roos7374d3a2017-03-31 14:14:53 -0700322 managedUserPassword, quality, managedUserId);
Ricky Wai7b9eb412016-05-12 17:29:12 +0100323 // We store a private credential for the managed user that's unlocked by the primary
324 // account holder's credential. As such, the user will never be prompted to enter this
325 // password directly, so we always store a password.
Adrian Roos7374d3a2017-03-31 14:14:53 -0700326 setLong(LockPatternUtils.PASSWORD_TYPE_KEY, quality, managedUserId);
Zach Jange61672a2016-11-22 17:47:18 +0000327 tieProfileLockToParent(managedUserId, newPassword);
Rich Canningsf64ec632019-02-21 12:40:36 -0800328 Arrays.fill(newPassword, (byte) 0);
Ricky Waidc283a82016-03-24 19:55:08 +0000329 } catch (NoSuchAlgorithmException | RemoteException e) {
330 Slog.e(TAG, "Fail to tie managed profile", e);
331 // Nothing client can do to fix this issue, so we do not throw exception out
332 }
333 }
334
Rubin Xu0cbc19e2016-12-09 14:00:21 +0000335 static class Injector {
Jim Millerde1af082013-09-11 14:58:26 -0700336
Rubin Xu0cbc19e2016-12-09 14:00:21 +0000337 protected Context mContext;
338
339 public Injector(Context context) {
340 mContext = context;
341 }
342
343 public Context getContext() {
344 return mContext;
345 }
346
347 public Handler getHandler() {
348 return new Handler();
349 }
350
351 public LockSettingsStorage getStorage() {
352 final LockSettingsStorage storage = new LockSettingsStorage(mContext);
353 storage.setDatabaseOnCreateCallback(new LockSettingsStorage.Callback() {
354 @Override
355 public void initialize(SQLiteDatabase db) {
356 // Get the lockscreen default from a system property, if available
357 boolean lockScreenDisable = SystemProperties.getBoolean(
358 "ro.lockscreen.disable.default", false);
359 if (lockScreenDisable) {
360 storage.writeKeyValue(db, LockPatternUtils.DISABLE_LOCKSCREEN_KEY, "1", 0);
361 }
362 }
363 });
364 return storage;
365 }
366
367 public LockSettingsStrongAuth getStrongAuth() {
368 return new LockSettingsStrongAuth(mContext);
369 }
370
371 public SynchronizedStrongAuthTracker getStrongAuthTracker() {
372 return new SynchronizedStrongAuthTracker(mContext);
373 }
374
375 public IActivityManager getActivityManager() {
376 return ActivityManager.getService();
377 }
378
379 public LockPatternUtils getLockPatternUtils() {
380 return new LockPatternUtils(mContext);
381 }
382
383 public NotificationManager getNotificationManager() {
384 return (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
385 }
386
387 public UserManager getUserManager() {
388 return (UserManager) mContext.getSystemService(Context.USER_SERVICE);
389 }
390
Rubin Xu8b30ec32017-03-05 00:47:09 +0000391 public DevicePolicyManager getDevicePolicyManager() {
392 return (DevicePolicyManager) mContext.getSystemService(Context.DEVICE_POLICY_SERVICE);
393 }
394
Rubin Xu0cbc19e2016-12-09 14:00:21 +0000395 public KeyStore getKeyStore() {
396 return KeyStore.getInstance();
397 }
398
Dmitry Dementyev29b9de52018-01-31 16:09:32 -0800399 public RecoverableKeyStoreManager getRecoverableKeyStoreManager(KeyStore keyStore) {
400 return RecoverableKeyStoreManager.getInstance(mContext, keyStore);
Dmitry Dementyev1aa96132017-12-11 11:33:12 -0800401 }
402
Rubin Xu0cbc19e2016-12-09 14:00:21 +0000403 public IStorageManager getStorageManager() {
404 final IBinder service = ServiceManager.getService("mount");
405 if (service != null) {
406 return IStorageManager.Stub.asInterface(service);
407 }
408 return null;
409 }
Rubin Xu3bf722a2016-12-15 16:07:38 +0000410
411 public SyntheticPasswordManager getSyntheticPasswordManager(LockSettingsStorage storage) {
Adrian Roos2adc2632017-09-05 17:01:42 +0200412 return new SyntheticPasswordManager(getContext(), storage, getUserManager());
Rubin Xu3bf722a2016-12-15 16:07:38 +0000413 }
414
Kevin Chyncf1a62e2019-02-21 11:11:59 -0800415 public boolean hasBiometrics() {
416 return BiometricManager.hasBiometrics(mContext);
417 }
418
Rubin Xu3bf722a2016-12-15 16:07:38 +0000419 public int binderGetCallingUid() {
420 return Binder.getCallingUid();
421 }
David Anderson6ebc25b2019-02-12 16:25:56 -0800422
423 public boolean isGsiRunning() {
424 return SystemProperties.getInt(GSI_RUNNING_PROP, 0) > 0;
425 }
Rubin Xu0cbc19e2016-12-09 14:00:21 +0000426 }
427
428 public LockSettingsService(Context context) {
429 this(new Injector(context));
430 }
431
432 @VisibleForTesting
433 protected LockSettingsService(Injector injector) {
434 mInjector = injector;
435 mContext = injector.getContext();
436 mKeyStore = injector.getKeyStore();
Dmitry Dementyev29b9de52018-01-31 16:09:32 -0800437 mRecoverableKeyStoreManager = injector.getRecoverableKeyStoreManager(mKeyStore);
Rubin Xu0cbc19e2016-12-09 14:00:21 +0000438 mHandler = injector.getHandler();
439 mStrongAuth = injector.getStrongAuth();
440 mActivityManager = injector.getActivityManager();
441
442 mLockPatternUtils = injector.getLockPatternUtils();
Paul Lawrence945490c2014-03-27 16:37:28 +0000443 mFirstCallToVold = true;
Robin Leef0246a82014-08-13 09:50:25 +0100444
445 IntentFilter filter = new IntentFilter();
446 filter.addAction(Intent.ACTION_USER_ADDED);
Adrian Roos3dcae682014-10-29 14:43:56 +0100447 filter.addAction(Intent.ACTION_USER_STARTING);
Adrian Roosdb0f76e2015-01-07 22:19:38 +0100448 filter.addAction(Intent.ACTION_USER_REMOVED);
Rubin Xu0cbc19e2016-12-09 14:00:21 +0000449 injector.getContext().registerReceiverAsUser(mBroadcastReceiver, UserHandle.ALL, filter,
450 null, null);
Adrian Roos261d5ab2014-10-29 14:42:38 +0100451
Rubin Xu0cbc19e2016-12-09 14:00:21 +0000452 mStorage = injector.getStorage();
453 mNotificationManager = injector.getNotificationManager();
454 mUserManager = injector.getUserManager();
455 mStrongAuthTracker = injector.getStrongAuthTracker();
456 mStrongAuthTracker.register(mStrongAuth);
Rubin Xu3bf722a2016-12-15 16:07:38 +0000457
458 mSpManager = injector.getSyntheticPasswordManager(mStorage);
Rubin Xufcd49f92017-08-24 18:21:52 +0100459
460 LocalServices.addService(LockSettingsInternal.class, new LocalService());
Jim Miller4f93c582016-01-27 19:05:43 -0800461 }
462
463 /**
Rubin Xu1de89b32016-11-30 20:03:13 +0000464 * If the account is credential-encrypted, show notification requesting the user to unlock the
465 * device.
Jim Miller4f93c582016-01-27 19:05:43 -0800466 */
Andrew Scull85a63bc2016-10-24 13:47:47 +0100467 private void maybeShowEncryptionNotificationForUser(@UserIdInt int userId) {
468 final UserInfo user = mUserManager.getUserInfo(userId);
469 if (!user.isManagedProfile()) {
470 // When the user is locked, we communicate it loud-and-clear
471 // on the lockscreen; we only show a notification below for
472 // locked managed profiles.
473 return;
474 }
475
476 final UserHandle userHandle = user.getUserHandle();
Rubin Xua55b1682017-01-31 10:06:56 +0000477 final boolean isSecure = isUserSecure(userId);
Andrew Scull85a63bc2016-10-24 13:47:47 +0100478 if (isSecure && !mUserManager.isUserUnlockingOrUnlocked(userHandle)) {
479 UserInfo parent = mUserManager.getProfileParent(userId);
480 if (parent != null &&
481 mUserManager.isUserUnlockingOrUnlocked(parent.getUserHandle()) &&
482 !mUserManager.isQuietModeEnabled(userHandle)) {
483 // Only show notifications for managed profiles once their parent
484 // user is unlocked.
485 showEncryptionNotificationForProfile(userHandle);
Jim Miller4f93c582016-01-27 19:05:43 -0800486 }
Jim Miller4f93c582016-01-27 19:05:43 -0800487 }
488 }
489
Kenny Guyb1b30262016-02-09 16:02:35 +0000490 private void showEncryptionNotificationForProfile(UserHandle user) {
491 Resources r = mContext.getResources();
492 CharSequence title = r.getText(
493 com.android.internal.R.string.user_encrypted_title);
494 CharSequence message = r.getText(
495 com.android.internal.R.string.profile_encrypted_message);
496 CharSequence detail = r.getText(
497 com.android.internal.R.string.profile_encrypted_detail);
498
499 final KeyguardManager km = (KeyguardManager) mContext.getSystemService(KEYGUARD_SERVICE);
Rubin Xu1de89b32016-11-30 20:03:13 +0000500 final Intent unlockIntent = km.createConfirmDeviceCredentialIntent(null, null,
501 user.getIdentifier());
Kenny Guyb1b30262016-02-09 16:02:35 +0000502 if (unlockIntent == null) {
503 return;
504 }
Rubin Xu1de89b32016-11-30 20:03:13 +0000505 unlockIntent.setFlags(
506 Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
Kenny Guyb1b30262016-02-09 16:02:35 +0000507 PendingIntent intent = PendingIntent.getActivity(mContext, 0, unlockIntent,
508 PendingIntent.FLAG_UPDATE_CURRENT);
509
510 showEncryptionNotification(user, title, message, detail, intent);
511 }
512
Rubin Xu1de89b32016-11-30 20:03:13 +0000513 private void showEncryptionNotification(UserHandle user, CharSequence title,
514 CharSequence message, CharSequence detail, PendingIntent intent) {
Kenny Guyb1b30262016-02-09 16:02:35 +0000515 if (DEBUG) Slog.v(TAG, "showing encryption notification, user: " + user.getIdentifier());
Jeff Sharkey4a399362016-05-26 09:47:43 -0600516
517 // Suppress all notifications on non-FBE devices for now
518 if (!StorageManager.isFileEncryptedNativeOrEmulated()) return;
519
Geoffrey Pitschaf759c52017-02-15 09:35:38 -0500520 Notification notification =
521 new Notification.Builder(mContext, SystemNotificationChannels.SECURITY)
522 .setSmallIcon(com.android.internal.R.drawable.ic_user_secure)
523 .setWhen(0)
524 .setOngoing(true)
525 .setTicker(title)
526 .setColor(mContext.getColor(
527 com.android.internal.R.color.system_notification_accent_color))
528 .setContentTitle(title)
529 .setContentText(message)
530 .setSubText(detail)
531 .setVisibility(Notification.VISIBILITY_PUBLIC)
532 .setContentIntent(intent)
533 .build();
Chris Wren282cfef2017-03-27 15:01:44 -0400534 mNotificationManager.notifyAsUser(null, SystemMessage.NOTE_FBE_ENCRYPTED_NOTIFICATION,
535 notification, user);
Jim Miller4f93c582016-01-27 19:05:43 -0800536 }
537
Andrew Scull85a63bc2016-10-24 13:47:47 +0100538 private void hideEncryptionNotification(UserHandle userHandle) {
Rubin Xu1de89b32016-11-30 20:03:13 +0000539 if (DEBUG) Slog.v(TAG, "hide encryption notification, user: " + userHandle.getIdentifier());
Chris Wren282cfef2017-03-27 15:01:44 -0400540 mNotificationManager.cancelAsUser(null, SystemMessage.NOTE_FBE_ENCRYPTED_NOTIFICATION,
541 userHandle);
Jim Miller4f93c582016-01-27 19:05:43 -0800542 }
543
544 public void onCleanupUser(int userId) {
545 hideEncryptionNotification(new UserHandle(userId));
Rubin Xu0da89832018-03-26 14:35:34 +0100546 // User is stopped with its CE key evicted. Require strong auth next time to be able to
547 // unlock the user's storage. Use STRONG_AUTH_REQUIRED_AFTER_BOOT since stopping and
548 // restarting a user later is equivalent to rebooting the device.
549 requireStrongAuth(STRONG_AUTH_REQUIRED_AFTER_BOOT, userId);
Jim Miller4f93c582016-01-27 19:05:43 -0800550 }
551
Andrew Scull85a63bc2016-10-24 13:47:47 +0100552 public void onStartUser(final int userId) {
553 maybeShowEncryptionNotificationForUser(userId);
554 }
555
Pavel Grafov0acc4bf2017-08-23 12:20:54 +0100556 /**
557 * Check if profile got unlocked but the keystore is still locked. This happens on full disk
558 * encryption devices since the profile may not yet be running when we consider unlocking it
559 * during the normal flow. In this case unlock the keystore for the profile.
560 */
561 private void ensureProfileKeystoreUnlocked(int userId) {
562 final KeyStore ks = KeyStore.getInstance();
563 if (ks.state(userId) == KeyStore.State.LOCKED
564 && tiedManagedProfileReadyToUnlock(mUserManager.getUserInfo(userId))) {
565 Slog.i(TAG, "Managed profile got unlocked, will unlock its keystore");
566 try {
567 // If boot took too long and the password in vold got expired, parent keystore will
568 // be still locked, we ignore this case since the user will be prompted to unlock
569 // the device after boot.
570 unlockChildProfile(userId, true /* ignoreUserNotAuthenticated */);
571 } catch (RemoteException e) {
572 Slog.e(TAG, "Failed to unlock child profile");
573 }
574 }
575 }
576
Ricky Waib0cdf382016-05-16 17:28:04 +0100577 public void onUnlockUser(final int userId) {
Rubin Xua55b1682017-01-31 10:06:56 +0000578 // Perform tasks which require locks in LSS on a handler, as we are callbacks from
579 // ActivityManager.unlockUser()
580 mHandler.post(new Runnable() {
581 @Override
582 public void run() {
Pavel Grafov0acc4bf2017-08-23 12:20:54 +0100583 ensureProfileKeystoreUnlocked(userId);
Rubin Xua55b1682017-01-31 10:06:56 +0000584 // Hide notification first, as tie managed profile lock takes time
585 hideEncryptionNotification(new UserHandle(userId));
Ricky Waib0cdf382016-05-16 17:28:04 +0100586
Rubin Xua55b1682017-01-31 10:06:56 +0000587 // Now we have unlocked the parent user we should show notifications
588 // about any profiles that exist.
589 List<UserInfo> profiles = mUserManager.getProfiles(userId);
590 for (int i = 0; i < profiles.size(); i++) {
591 UserInfo profile = profiles.get(i);
592 final boolean isSecure = isUserSecure(profile.id);
593 if (isSecure && profile.isManagedProfile()) {
594 UserHandle userHandle = profile.getUserHandle();
595 if (!mUserManager.isUserUnlockingOrUnlocked(userHandle) &&
596 !mUserManager.isQuietModeEnabled(userHandle)) {
597 showEncryptionNotificationForProfile(userHandle);
598 }
599 }
600 }
601
602 if (mUserManager.getUserInfo(userId).isManagedProfile()) {
Ricky Waib0cdf382016-05-16 17:28:04 +0100603 tieManagedProfileLockIfNecessary(userId, null);
604 }
Andrew Scullf49794b2018-04-13 12:01:25 +0100605
606 // If the user doesn't have a credential, try and derive their secret for the
607 // AuthSecret HAL. The secret will have been enrolled if the user previously set a
608 // credential and still needs to be passed to the HAL once that credential is
609 // removed.
610 if (mUserManager.getUserInfo(userId).isPrimary() && !isUserSecure(userId)) {
611 tryDeriveAuthTokenForUnsecuredPrimaryUser(userId);
612 }
Kenny Guyb1b30262016-02-09 16:02:35 +0000613 }
Rubin Xua55b1682017-01-31 10:06:56 +0000614 });
Amith Yamasani52c489c2012-03-28 11:42:42 -0700615 }
616
Andrew Scullf49794b2018-04-13 12:01:25 +0100617 private void tryDeriveAuthTokenForUnsecuredPrimaryUser(@UserIdInt int userId) {
618 synchronized (mSpManager) {
619 // Make sure the user has a synthetic password to derive
620 if (!isSyntheticPasswordBasedCredentialLocked(userId)) {
621 return;
622 }
623
624 try {
625 final long handle = getSyntheticPasswordHandleLocked(userId);
Rich Canningsf64ec632019-02-21 12:40:36 -0800626 final byte[] noCredential = null;
Andrew Scullf49794b2018-04-13 12:01:25 +0100627 AuthenticationResult result =
628 mSpManager.unwrapPasswordBasedSyntheticPassword(
629 getGateKeeperService(), handle, noCredential, userId, null);
630 if (result.authToken != null) {
631 Slog.i(TAG, "Retrieved auth token for user " + userId);
632 onAuthTokenKnownForUser(userId, result.authToken);
633 } else {
634 Slog.e(TAG, "Auth token not available for user " + userId);
635 }
636 } catch (RemoteException e) {
637 Slog.e(TAG, "Failure retrieving auth token", e);
638 }
639 }
640 }
641
Robin Leef0246a82014-08-13 09:50:25 +0100642 private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
643 @Override
644 public void onReceive(Context context, Intent intent) {
Robin Lee1096cf82014-09-01 16:52:47 +0100645 if (Intent.ACTION_USER_ADDED.equals(intent.getAction())) {
Chad Brubaker83ce0952015-05-12 13:00:02 -0700646 // Notify keystore that a new user was added.
Robin Leef0246a82014-08-13 09:50:25 +0100647 final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, 0);
Amith Yamasanif11a5742016-06-16 08:20:07 -0700648 if (userHandle > UserHandle.USER_SYSTEM) {
649 removeUser(userHandle, /* unknownUser= */ true);
650 }
Robin Lee49d810c2014-09-23 13:50:22 +0100651 final KeyStore ks = KeyStore.getInstance();
Ricky Waidc283a82016-03-24 19:55:08 +0000652 final UserInfo parentInfo = mUserManager.getProfileParent(userHandle);
Chad Brubaker83ce0952015-05-12 13:00:02 -0700653 final int parentHandle = parentInfo != null ? parentInfo.id : -1;
654 ks.onUserAdded(userHandle, parentHandle);
Adrian Roos3dcae682014-10-29 14:43:56 +0100655 } else if (Intent.ACTION_USER_STARTING.equals(intent.getAction())) {
656 final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, 0);
657 mStorage.prefetchUser(userHandle);
Adrian Roosdb0f76e2015-01-07 22:19:38 +0100658 } else if (Intent.ACTION_USER_REMOVED.equals(intent.getAction())) {
659 final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, 0);
660 if (userHandle > 0) {
Amith Yamasanif11a5742016-06-16 08:20:07 -0700661 removeUser(userHandle, /* unknownUser= */ false);
Adrian Roosdb0f76e2015-01-07 22:19:38 +0100662 }
Robin Leef0246a82014-08-13 09:50:25 +0100663 }
664 }
665 };
666
Jim Miller4f93c582016-01-27 19:05:43 -0800667 @Override // binder interface
Amith Yamasani52c489c2012-03-28 11:42:42 -0700668 public void systemReady() {
Adrian Roosb953e182017-08-17 17:58:26 +0200669 if (mContext.checkCallingOrSelfPermission(PERMISSION) != PERMISSION_GRANTED) {
670 EventLog.writeEvent(0x534e4554, "28251513", getCallingUid(), ""); // SafetyNet
671 }
672 checkWritePermission(UserHandle.USER_SYSTEM);
Amith Yamasani52c489c2012-03-28 11:42:42 -0700673 migrateOldData();
Andres Morales301ea442015-04-17 09:15:47 -0700674 try {
675 getGateKeeperService();
Rubin Xu7b7424b2017-03-31 18:03:20 +0100676 mSpManager.initWeaverService();
Andres Morales301ea442015-04-17 09:15:47 -0700677 } catch (RemoteException e) {
678 Slog.e(TAG, "Failure retrieving IGateKeeperService", e);
679 }
Andrew Sculle6527c12018-01-05 18:33:58 +0000680 // Find the AuthSecret HAL
681 try {
682 mAuthSecretService = IAuthSecret.getService();
683 } catch (NoSuchElementException e) {
684 Slog.i(TAG, "Device doesn't implement AuthSecret HAL");
685 } catch (RemoteException e) {
686 Slog.w(TAG, "Failed to get AuthSecret HAL", e);
687 }
Adrian Roos7374d3a2017-03-31 14:14:53 -0700688 mDeviceProvisionedObserver.onSystemReady();
Xiaohui Chen7c696362015-09-16 09:56:14 -0700689 // TODO: maybe skip this for split system user mode.
690 mStorage.prefetchUser(UserHandle.USER_SYSTEM);
Amith Yamasani52c489c2012-03-28 11:42:42 -0700691 }
692
693 private void migrateOldData() {
Rubin Xufe354472017-11-21 12:05:06 +0000694 // These Settings moved before multi-user was enabled, so we only have to do it for the
695 // root user.
696 if (getString("migrated", null, 0) == null) {
697 final ContentResolver cr = mContext.getContentResolver();
698 for (String validSetting : VALID_SETTINGS) {
699 String value = Settings.Secure.getString(cr, validSetting);
700 if (value != null) {
701 setString(validSetting, value, 0);
Jim Miller187ec582013-04-15 18:27:54 -0700702 }
Amith Yamasani52c489c2012-03-28 11:42:42 -0700703 }
Rubin Xufe354472017-11-21 12:05:06 +0000704 // No need to move the password / pattern files. They're already in the right place.
705 setString("migrated", "true", 0);
706 Slog.i(TAG, "Migrated lock settings to new location");
707 }
Amith Yamasani52c489c2012-03-28 11:42:42 -0700708
Rubin Xufe354472017-11-21 12:05:06 +0000709 // These Settings changed after multi-user was enabled, hence need to be moved per user.
710 if (getString("migrated_user_specific", null, 0) == null) {
711 final ContentResolver cr = mContext.getContentResolver();
712 List<UserInfo> users = mUserManager.getUsers();
713 for (int user = 0; user < users.size(); user++) {
714 // Migrate owner info
715 final int userId = users.get(user).id;
716 final String OWNER_INFO = Secure.LOCK_SCREEN_OWNER_INFO;
717 String ownerInfo = Settings.Secure.getStringForUser(cr, OWNER_INFO, userId);
718 if (!TextUtils.isEmpty(ownerInfo)) {
719 setString(OWNER_INFO, ownerInfo, userId);
720 Settings.Secure.putStringForUser(cr, OWNER_INFO, "", userId);
Adrian Roos43830582015-04-21 16:04:43 -0700721 }
722
Rubin Xufe354472017-11-21 12:05:06 +0000723 // Migrate owner info enabled. Note there was a bug where older platforms only
724 // stored this value if the checkbox was toggled at least once. The code detects
725 // this case by handling the exception.
726 final String OWNER_INFO_ENABLED = Secure.LOCK_SCREEN_OWNER_INFO_ENABLED;
727 boolean enabled;
Ricky Wai97c8f8d2016-07-13 17:57:45 +0100728 try {
Rubin Xufe354472017-11-21 12:05:06 +0000729 int ivalue = Settings.Secure.getIntForUser(cr, OWNER_INFO_ENABLED, userId);
730 enabled = ivalue != 0;
731 setLong(OWNER_INFO_ENABLED, enabled ? 1 : 0, userId);
732 } catch (SettingNotFoundException e) {
733 // Setting was never stored. Store it if the string is not empty.
734 if (!TextUtils.isEmpty(ownerInfo)) {
735 setLong(OWNER_INFO_ENABLED, 1, userId);
Ricky Wai97c8f8d2016-07-13 17:57:45 +0100736 }
Rubin Xufe354472017-11-21 12:05:06 +0000737 }
738 Settings.Secure.putIntForUser(cr, OWNER_INFO_ENABLED, 0, userId);
739 }
740 // No need to move the password / pattern files. They're already in the right place.
741 setString("migrated_user_specific", "true", 0);
742 Slog.i(TAG, "Migrated per-user lock settings to new location");
743 }
744
745 // Migrates biometric weak such that the fallback mechanism becomes the primary.
746 if (getString("migrated_biometric_weak", null, 0) == null) {
747 List<UserInfo> users = mUserManager.getUsers();
748 for (int i = 0; i < users.size(); i++) {
749 int userId = users.get(i).id;
750 long type = getLong(LockPatternUtils.PASSWORD_TYPE_KEY,
751 DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED,
752 userId);
753 long alternateType = getLong(LockPatternUtils.PASSWORD_TYPE_ALTERNATE_KEY,
754 DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED,
755 userId);
756 if (type == DevicePolicyManager.PASSWORD_QUALITY_BIOMETRIC_WEAK) {
757 setLong(LockPatternUtils.PASSWORD_TYPE_KEY,
758 alternateType,
759 userId);
760 }
761 setLong(LockPatternUtils.PASSWORD_TYPE_ALTERNATE_KEY,
762 DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED,
763 userId);
764 }
765 setString("migrated_biometric_weak", "true", 0);
766 Slog.i(TAG, "Migrated biometric weak to use the fallback instead");
767 }
768
769 // Migrates lockscreen.disabled. Prior to M, the flag was ignored when more than one
770 // user was present on the system, so if we're upgrading to M and there is more than one
771 // user we disable the flag to remain consistent.
772 if (getString("migrated_lockscreen_disabled", null, 0) == null) {
773 final List<UserInfo> users = mUserManager.getUsers();
774 final int userCount = users.size();
775 int switchableUsers = 0;
776 for (int i = 0; i < userCount; i++) {
777 if (users.get(i).supportsSwitchTo()) {
778 switchableUsers++;
Ricky Wai97c8f8d2016-07-13 17:57:45 +0100779 }
Ricky Wai7b9eb412016-05-12 17:29:12 +0100780 }
Greg Plesureb2e4532016-11-02 17:10:27 -0400781
Rubin Xufe354472017-11-21 12:05:06 +0000782 if (switchableUsers > 1) {
Greg Plesureb2e4532016-11-02 17:10:27 -0400783 for (int i = 0; i < userCount; i++) {
784 int id = users.get(i).id;
Rubin Xufe354472017-11-21 12:05:06 +0000785
786 if (getBoolean(LockPatternUtils.DISABLE_LOCKSCREEN_KEY, false, id)) {
787 setBoolean(LockPatternUtils.DISABLE_LOCKSCREEN_KEY, false, id);
788 }
Greg Plesureb2e4532016-11-02 17:10:27 -0400789 }
Greg Plesureb2e4532016-11-02 17:10:27 -0400790 }
Rubin Xufe354472017-11-21 12:05:06 +0000791
792 setString("migrated_lockscreen_disabled", "true", 0);
793 Slog.i(TAG, "Migrated lockscreen disabled flag");
794 }
795
796 final List<UserInfo> users = mUserManager.getUsers();
797 for (int i = 0; i < users.size(); i++) {
798 final UserInfo userInfo = users.get(i);
799 if (userInfo.isManagedProfile() && mStorage.hasChildProfileLock(userInfo.id)) {
800 // When managed profile has a unified lock, the password quality stored has 2
801 // possibilities only.
802 // 1). PASSWORD_QUALITY_UNSPECIFIED, which is upgraded from dp2, and we are
803 // going to set it back to PASSWORD_QUALITY_ALPHANUMERIC.
804 // 2). PASSWORD_QUALITY_ALPHANUMERIC, which is the actual password quality for
805 // unified lock.
806 final long quality = getLong(LockPatternUtils.PASSWORD_TYPE_KEY,
807 DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED, userInfo.id);
808 if (quality == DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED) {
809 // Only possible when it's upgraded from nyc dp3
810 Slog.i(TAG, "Migrated tied profile lock type");
811 setLong(LockPatternUtils.PASSWORD_TYPE_KEY,
812 DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC, userInfo.id);
813 } else if (quality != DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC) {
814 // It should not happen
815 Slog.e(TAG, "Invalid tied profile lock type: " + quality);
816 }
817 }
818 try {
819 final String alias = LockPatternUtils.PROFILE_KEY_NAME_ENCRYPT + userInfo.id;
820 java.security.KeyStore keyStore =
821 java.security.KeyStore.getInstance("AndroidKeyStore");
822 keyStore.load(null);
823 if (keyStore.containsAlias(alias)) {
824 keyStore.deleteEntry(alias);
825 }
826 } catch (KeyStoreException | NoSuchAlgorithmException |
827 CertificateException | IOException e) {
828 Slog.e(TAG, "Unable to remove tied profile key", e);
829 }
830 }
831
832 boolean isWatch = mContext.getPackageManager().hasSystemFeature(
833 PackageManager.FEATURE_WATCH);
834 // Wear used to set DISABLE_LOCKSCREEN to 'true', but because Wear now allows accounts
835 // and device management the lockscreen must be re-enabled now for users that upgrade.
836 if (isWatch && getString("migrated_wear_lockscreen_disabled", null, 0) == null) {
837 final int userCount = users.size();
838 for (int i = 0; i < userCount; i++) {
839 int id = users.get(i).id;
840 setBoolean(LockPatternUtils.DISABLE_LOCKSCREEN_KEY, false, id);
841 }
842 setString("migrated_wear_lockscreen_disabled", "true", 0);
843 Slog.i(TAG, "Migrated lockscreen_disabled for Wear devices");
Amith Yamasani52c489c2012-03-28 11:42:42 -0700844 }
845 }
846
Adrian Roos60dcbbf2017-08-08 16:19:33 +0200847 private void migrateOldDataAfterSystemReady() {
848 try {
849 // Migrate the FRP credential to the persistent data block
Adrian Roos2adc2632017-09-05 17:01:42 +0200850 if (LockPatternUtils.frpCredentialEnabled(mContext)
851 && !getBoolean("migrated_frp", false, 0)) {
Adrian Roos60dcbbf2017-08-08 16:19:33 +0200852 migrateFrpCredential();
853 setBoolean("migrated_frp", true, 0);
854 Slog.i(TAG, "Migrated migrated_frp.");
855 }
856 } catch (RemoteException e) {
857 Slog.e(TAG, "Unable to migrateOldDataAfterSystemReady", e);
858 }
859 }
860
861 /**
862 * Migrate the credential for the FRP credential owner user if the following are satisfied:
863 * - the user has a secure credential
864 * - the FRP credential is not set up
865 * - the credential is based on a synthetic password.
866 */
867 private void migrateFrpCredential() throws RemoteException {
868 if (mStorage.readPersistentDataBlock() != PersistentData.NONE) {
869 return;
870 }
871 for (UserInfo userInfo : mUserManager.getUsers()) {
Adrian Roos2adc2632017-09-05 17:01:42 +0200872 if (userOwnsFrpCredential(mContext, userInfo) && isUserSecure(userInfo.id)) {
Adrian Roos60dcbbf2017-08-08 16:19:33 +0200873 synchronized (mSpManager) {
874 if (isSyntheticPasswordBasedCredentialLocked(userInfo.id)) {
875 int actualQuality = (int) getLong(LockPatternUtils.PASSWORD_TYPE_KEY,
876 DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED, userInfo.id);
877
878 mSpManager.migrateFrpPasswordLocked(
879 getSyntheticPasswordHandleLocked(userInfo.id),
880 userInfo,
881 redactActualQualityToMostLenientEquivalentQuality(actualQuality));
882 }
883 }
884 return;
885 }
886 }
887 }
888
889 /**
890 * Returns the lowest password quality that still presents the same UI for entering it.
891 *
892 * For the FRP credential, we do not want to leak the actual quality of the password, only what
893 * kind of UI it requires. However, when migrating, we only know the actual quality, not the
894 * originally requested quality; since this is only used to determine what input variant to
895 * present to the user, we just assume the lowest possible quality was requested.
896 */
897 private int redactActualQualityToMostLenientEquivalentQuality(int quality) {
898 switch (quality) {
899 case DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC:
900 case DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC:
901 case DevicePolicyManager.PASSWORD_QUALITY_COMPLEX:
902 return DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC;
903 case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC:
904 case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC_COMPLEX:
905 return DevicePolicyManager.PASSWORD_QUALITY_NUMERIC;
906 case DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED:
907 case DevicePolicyManager.PASSWORD_QUALITY_SOMETHING:
908 case DevicePolicyManager.PASSWORD_QUALITY_MANAGED:
909 case DevicePolicyManager.PASSWORD_QUALITY_BIOMETRIC_WEAK:
910 default:
911 return quality;
912 }
913 }
914
Jim Miller5ecd8112013-01-09 18:50:26 -0800915 private final void checkWritePermission(int userId) {
Jim Miller505329b2013-11-08 13:25:36 -0800916 mContext.enforceCallingOrSelfPermission(PERMISSION, "LockSettingsWrite");
Amith Yamasani52c489c2012-03-28 11:42:42 -0700917 }
918
Jim Miller5ecd8112013-01-09 18:50:26 -0800919 private final void checkPasswordReadPermission(int userId) {
Jim Miller505329b2013-11-08 13:25:36 -0800920 mContext.enforceCallingOrSelfPermission(PERMISSION, "LockSettingsRead");
Amith Yamasani52c489c2012-03-28 11:42:42 -0700921 }
922
Adrian Roosb953e182017-08-17 17:58:26 +0200923 private final void checkPasswordHavePermission(int userId) {
924 if (mContext.checkCallingOrSelfPermission(PERMISSION) != PERMISSION_GRANTED) {
925 EventLog.writeEvent(0x534e4554, "28251513", getCallingUid(), ""); // SafetyNet
926 }
927 mContext.enforceCallingOrSelfPermission(PERMISSION, "LockSettingsHave");
928 }
929
Jim Miller158fe192013-04-17 15:23:55 -0700930 private final void checkReadPermission(String requestedKey, int userId) {
Amith Yamasani52c489c2012-03-28 11:42:42 -0700931 final int callingUid = Binder.getCallingUid();
Adrian Roos001b00d2015-02-24 17:08:48 +0100932
Svetoslav Ganov6d2c0e52015-06-23 16:33:36 +0000933 for (int i = 0; i < READ_CONTACTS_PROTECTED_SETTINGS.length; i++) {
934 String key = READ_CONTACTS_PROTECTED_SETTINGS[i];
935 if (key.equals(requestedKey) && mContext.checkCallingOrSelfPermission(READ_CONTACTS)
Jim Miller158fe192013-04-17 15:23:55 -0700936 != PackageManager.PERMISSION_GRANTED) {
937 throw new SecurityException("uid=" + callingUid
Svetoslav Ganov6d2c0e52015-06-23 16:33:36 +0000938 + " needs permission " + READ_CONTACTS + " to read "
Jim Miller158fe192013-04-17 15:23:55 -0700939 + requestedKey + " for user " + userId);
940 }
Amith Yamasani52c489c2012-03-28 11:42:42 -0700941 }
Adrian Roos001b00d2015-02-24 17:08:48 +0100942
943 for (int i = 0; i < READ_PASSWORD_PROTECTED_SETTINGS.length; i++) {
944 String key = READ_PASSWORD_PROTECTED_SETTINGS[i];
945 if (key.equals(requestedKey) && mContext.checkCallingOrSelfPermission(PERMISSION)
946 != PackageManager.PERMISSION_GRANTED) {
947 throw new SecurityException("uid=" + callingUid
948 + " needs permission " + PERMISSION + " to read "
949 + requestedKey + " for user " + userId);
950 }
951 }
Amith Yamasani52c489c2012-03-28 11:42:42 -0700952 }
953
954 @Override
Rubin Xufe354472017-11-21 12:05:06 +0000955 public boolean getSeparateProfileChallengeEnabled(int userId) {
Ricky Wai7f405f12016-05-31 12:05:05 +0100956 checkReadPermission(SEPARATE_PROFILE_CHALLENGE_KEY, userId);
Ricky Waidc283a82016-03-24 19:55:08 +0000957 synchronized (mSeparateChallengeLock) {
958 return getBoolean(SEPARATE_PROFILE_CHALLENGE_KEY, false, userId);
959 }
960 }
961
962 @Override
963 public void setSeparateProfileChallengeEnabled(int userId, boolean enabled,
Rich Canningsf64ec632019-02-21 12:40:36 -0800964 byte[] managedUserPassword) {
Ricky Wai7f405f12016-05-31 12:05:05 +0100965 checkWritePermission(userId);
Lenka Trochtova66c492a2018-12-06 11:29:21 +0100966 if (!mLockPatternUtils.hasSecureLockScreen()) {
967 throw new UnsupportedOperationException(
968 "This operation requires secure lock screen feature.");
969 }
Ricky Waidc283a82016-03-24 19:55:08 +0000970 synchronized (mSeparateChallengeLock) {
Pavel Grafov28939982017-10-03 15:11:52 +0100971 setSeparateProfileChallengeEnabledLocked(userId, enabled, managedUserPassword);
Ricky Waidc283a82016-03-24 19:55:08 +0000972 }
Pavel Grafov28939982017-10-03 15:11:52 +0100973 notifySeparateProfileChallengeChanged(userId);
974 }
975
976 @GuardedBy("mSeparateChallengeLock")
Rich Canningsf64ec632019-02-21 12:40:36 -0800977 private void setSeparateProfileChallengeEnabledLocked(@UserIdInt int userId,
978 boolean enabled, byte[] managedUserPassword) {
Pavel Grafovf10ae7e2018-06-25 12:13:38 +0100979 final boolean old = getBoolean(SEPARATE_PROFILE_CHALLENGE_KEY, false, userId);
Pavel Grafov28939982017-10-03 15:11:52 +0100980 setBoolean(SEPARATE_PROFILE_CHALLENGE_KEY, enabled, userId);
Pavel Grafovf10ae7e2018-06-25 12:13:38 +0100981 try {
982 if (enabled) {
983 mStorage.removeChildProfileLock(userId);
984 removeKeystoreProfileKey(userId);
985 } else {
986 tieManagedProfileLockIfNecessary(userId, managedUserPassword);
987 }
988 } catch (IllegalStateException e) {
989 setBoolean(SEPARATE_PROFILE_CHALLENGE_KEY, old, userId);
990 throw e;
Pavel Grafov28939982017-10-03 15:11:52 +0100991 }
992 }
993
994 private void notifySeparateProfileChallengeChanged(int userId) {
Andrew Scull7f4ff4c2018-01-05 18:33:58 +0000995 final DevicePolicyManagerInternal dpmi = LocalServices.getService(
996 DevicePolicyManagerInternal.class);
997 if (dpmi != null) {
998 dpmi.reportSeparateProfileChallengeChanged(userId);
999 }
Ricky Waidc283a82016-03-24 19:55:08 +00001000 }
1001
1002 @Override
Rubin Xufe354472017-11-21 12:05:06 +00001003 public void setBoolean(String key, boolean value, int userId) {
Amith Yamasani52c489c2012-03-28 11:42:42 -07001004 checkWritePermission(userId);
Adrian Roos261d5ab2014-10-29 14:42:38 +01001005 setStringUnchecked(key, userId, value ? "1" : "0");
Amith Yamasani52c489c2012-03-28 11:42:42 -07001006 }
1007
1008 @Override
Rubin Xufe354472017-11-21 12:05:06 +00001009 public void setLong(String key, long value, int userId) {
Amith Yamasani52c489c2012-03-28 11:42:42 -07001010 checkWritePermission(userId);
Adrian Roos261d5ab2014-10-29 14:42:38 +01001011 setStringUnchecked(key, userId, Long.toString(value));
Amith Yamasani52c489c2012-03-28 11:42:42 -07001012 }
1013
1014 @Override
Rubin Xufe354472017-11-21 12:05:06 +00001015 public void setString(String key, String value, int userId) {
Amith Yamasani52c489c2012-03-28 11:42:42 -07001016 checkWritePermission(userId);
Adrian Roos261d5ab2014-10-29 14:42:38 +01001017 setStringUnchecked(key, userId, value);
1018 }
Amith Yamasani52c489c2012-03-28 11:42:42 -07001019
Adrian Roos261d5ab2014-10-29 14:42:38 +01001020 private void setStringUnchecked(String key, int userId, String value) {
Adrian Roos7374d3a2017-03-31 14:14:53 -07001021 Preconditions.checkArgument(userId != USER_FRP, "cannot store lock settings for FRP user");
1022
Adrian Roos261d5ab2014-10-29 14:42:38 +01001023 mStorage.writeKeyValue(key, value, userId);
Amith Yamasani072543f2015-02-13 11:09:45 -08001024 if (ArrayUtils.contains(SETTINGS_TO_BACKUP, key)) {
1025 BackupManager.dataChanged("com.android.providers.settings");
1026 }
Amith Yamasani52c489c2012-03-28 11:42:42 -07001027 }
1028
1029 @Override
Adrian Roos60dcbbf2017-08-08 16:19:33 +02001030 public boolean getBoolean(String key, boolean defaultValue, int userId) {
Jim Miller158fe192013-04-17 15:23:55 -07001031 checkReadPermission(key, userId);
Adrian Roos9dd16eb2015-01-08 16:20:49 +01001032 String value = getStringUnchecked(key, null, userId);
Amith Yamasani52c489c2012-03-28 11:42:42 -07001033 return TextUtils.isEmpty(value) ?
1034 defaultValue : (value.equals("1") || value.equals("true"));
1035 }
1036
1037 @Override
Adrian Roos60dcbbf2017-08-08 16:19:33 +02001038 public long getLong(String key, long defaultValue, int userId) {
Jim Miller158fe192013-04-17 15:23:55 -07001039 checkReadPermission(key, userId);
Adrian Roos9dd16eb2015-01-08 16:20:49 +01001040 String value = getStringUnchecked(key, null, userId);
Amith Yamasani52c489c2012-03-28 11:42:42 -07001041 return TextUtils.isEmpty(value) ? defaultValue : Long.parseLong(value);
1042 }
1043
1044 @Override
Adrian Roos60dcbbf2017-08-08 16:19:33 +02001045 public String getString(String key, String defaultValue, int userId) {
Jim Miller158fe192013-04-17 15:23:55 -07001046 checkReadPermission(key, userId);
Adrian Roos9dd16eb2015-01-08 16:20:49 +01001047 return getStringUnchecked(key, defaultValue, userId);
1048 }
1049
1050 public String getStringUnchecked(String key, String defaultValue, int userId) {
1051 if (Settings.Secure.LOCK_PATTERN_ENABLED.equals(key)) {
Adrian Roos7811d9f2015-07-27 15:10:13 -07001052 long ident = Binder.clearCallingIdentity();
1053 try {
1054 return mLockPatternUtils.isLockPatternEnabled(userId) ? "1" : "0";
1055 } finally {
1056 Binder.restoreCallingIdentity(ident);
1057 }
Adrian Roos9dd16eb2015-01-08 16:20:49 +01001058 }
1059
Adrian Roos7374d3a2017-03-31 14:14:53 -07001060 if (userId == USER_FRP) {
1061 return getFrpStringUnchecked(key);
1062 }
1063
Bryce Lee46145962015-12-14 14:39:10 -08001064 if (LockPatternUtils.LEGACY_LOCK_PATTERN_ENABLED.equals(key)) {
1065 key = Settings.Secure.LOCK_PATTERN_ENABLED;
1066 }
1067
Adrian Roos261d5ab2014-10-29 14:42:38 +01001068 return mStorage.readKeyValue(key, defaultValue, userId);
Amith Yamasani52c489c2012-03-28 11:42:42 -07001069 }
1070
Adrian Roos7374d3a2017-03-31 14:14:53 -07001071 private String getFrpStringUnchecked(String key) {
1072 if (LockPatternUtils.PASSWORD_TYPE_KEY.equals(key)) {
1073 return String.valueOf(readFrpPasswordQuality());
1074 }
1075 return null;
1076 }
1077
1078 private int readFrpPasswordQuality() {
1079 return mStorage.readPersistentDataBlock().qualityForUi;
1080 }
1081
Adrian Roos4f788452014-05-22 20:45:59 +02001082 @Override
Amith Yamasani52c489c2012-03-28 11:42:42 -07001083 public boolean havePassword(int userId) throws RemoteException {
Adrian Roosb953e182017-08-17 17:58:26 +02001084 checkPasswordHavePermission(userId);
Rubin Xu3bf722a2016-12-15 16:07:38 +00001085 synchronized (mSpManager) {
1086 if (isSyntheticPasswordBasedCredentialLocked(userId)) {
1087 long handle = getSyntheticPasswordHandleLocked(userId);
1088 return mSpManager.getCredentialType(handle, userId) ==
1089 LockPatternUtils.CREDENTIAL_TYPE_PASSWORD;
1090 }
1091 }
Amith Yamasani52c489c2012-03-28 11:42:42 -07001092 // Do we need a permissions check here?
Adrian Roos261d5ab2014-10-29 14:42:38 +01001093 return mStorage.hasPassword(userId);
Amith Yamasani52c489c2012-03-28 11:42:42 -07001094 }
1095
1096 @Override
1097 public boolean havePattern(int userId) throws RemoteException {
Adrian Roosb953e182017-08-17 17:58:26 +02001098 checkPasswordHavePermission(userId);
Rubin Xu3bf722a2016-12-15 16:07:38 +00001099 synchronized (mSpManager) {
1100 if (isSyntheticPasswordBasedCredentialLocked(userId)) {
1101 long handle = getSyntheticPasswordHandleLocked(userId);
1102 return mSpManager.getCredentialType(handle, userId) ==
1103 LockPatternUtils.CREDENTIAL_TYPE_PATTERN;
1104 }
1105 }
Amith Yamasani52c489c2012-03-28 11:42:42 -07001106 // Do we need a permissions check here?
Adrian Roos261d5ab2014-10-29 14:42:38 +01001107 return mStorage.hasPattern(userId);
Amith Yamasani52c489c2012-03-28 11:42:42 -07001108 }
1109
Rubin Xua55b1682017-01-31 10:06:56 +00001110 private boolean isUserSecure(int userId) {
Rubin Xu3bf722a2016-12-15 16:07:38 +00001111 synchronized (mSpManager) {
Rubin Xufcd49f92017-08-24 18:21:52 +01001112 if (isSyntheticPasswordBasedCredentialLocked(userId)) {
1113 long handle = getSyntheticPasswordHandleLocked(userId);
1114 return mSpManager.getCredentialType(handle, userId) !=
1115 LockPatternUtils.CREDENTIAL_TYPE_NONE;
Rubin Xu3bf722a2016-12-15 16:07:38 +00001116 }
1117 }
Rubin Xua55b1682017-01-31 10:06:56 +00001118 return mStorage.hasCredential(userId);
1119 }
1120
Rich Canningsf64ec632019-02-21 12:40:36 -08001121 private void setKeystorePassword(byte[] password, int userHandle) {
Robin Leef0246a82014-08-13 09:50:25 +01001122 final KeyStore ks = KeyStore.getInstance();
Rich Canningsf64ec632019-02-21 12:40:36 -08001123 // TODO(b/120484642): Update keystore to accept byte[] passwords
1124 String passwordString = password == null ? null : new String(password);
1125 ks.onUserPasswordChanged(userHandle, passwordString);
Chad Brubakera91a8502015-05-07 10:02:22 -07001126 }
1127
Rich Canningsf64ec632019-02-21 12:40:36 -08001128 private void unlockKeystore(byte[] password, int userHandle) {
Ricky Waidc283a82016-03-24 19:55:08 +00001129 if (DEBUG) Slog.v(TAG, "Unlock keystore for user: " + userHandle);
Rich Canningsf64ec632019-02-21 12:40:36 -08001130 // TODO(b/120484642): Update keystore to accept byte[] passwords
1131 String passwordString = password == null ? null : new String(password);
Chad Brubakera91a8502015-05-07 10:02:22 -07001132 final KeyStore ks = KeyStore.getInstance();
Rich Canningsf64ec632019-02-21 12:40:36 -08001133 ks.unlock(userHandle, passwordString);
Ricky Waidc283a82016-03-24 19:55:08 +00001134 }
Chad Brubakera91a8502015-05-07 10:02:22 -07001135
Rubin Xu0cbc19e2016-12-09 14:00:21 +00001136 @VisibleForTesting
Rich Canningsf64ec632019-02-21 12:40:36 -08001137 protected byte[] getDecryptedPasswordForTiedProfile(int userId)
Ricky Waidc283a82016-03-24 19:55:08 +00001138 throws KeyStoreException, UnrecoverableKeyException,
1139 NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
1140 InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException,
1141 CertificateException, IOException {
Rich Canningsf64ec632019-02-21 12:40:36 -08001142 if (DEBUG) Slog.v(TAG, "Get child profile decrypted key");
Ricky Waidc283a82016-03-24 19:55:08 +00001143 byte[] storedData = mStorage.readChildProfileLock(userId);
1144 if (storedData == null) {
1145 throw new FileNotFoundException("Child profile lock file not found");
1146 }
1147 byte[] iv = Arrays.copyOfRange(storedData, 0, PROFILE_KEY_IV_SIZE);
1148 byte[] encryptedPassword = Arrays.copyOfRange(storedData, PROFILE_KEY_IV_SIZE,
1149 storedData.length);
1150 byte[] decryptionResult;
1151 java.security.KeyStore keyStore = java.security.KeyStore.getInstance("AndroidKeyStore");
1152 keyStore.load(null);
1153 SecretKey decryptionKey = (SecretKey) keyStore.getKey(
Ricky Waid3982442016-05-24 19:27:08 +01001154 LockPatternUtils.PROFILE_KEY_NAME_DECRYPT + userId, null);
Ricky Waidc283a82016-03-24 19:55:08 +00001155
1156 Cipher cipher = Cipher.getInstance(KeyProperties.KEY_ALGORITHM_AES + "/"
1157 + KeyProperties.BLOCK_MODE_GCM + "/" + KeyProperties.ENCRYPTION_PADDING_NONE);
1158
1159 cipher.init(Cipher.DECRYPT_MODE, decryptionKey, new GCMParameterSpec(128, iv));
1160 decryptionResult = cipher.doFinal(encryptedPassword);
Rich Canningsf64ec632019-02-21 12:40:36 -08001161 return decryptionResult;
Ricky Waidc283a82016-03-24 19:55:08 +00001162 }
1163
Pavel Grafov0acc4bf2017-08-23 12:20:54 +01001164 private void unlockChildProfile(int profileHandle, boolean ignoreUserNotAuthenticated)
1165 throws RemoteException {
Ricky Waidc283a82016-03-24 19:55:08 +00001166 try {
Rubin Xu1de89b32016-11-30 20:03:13 +00001167 doVerifyCredential(getDecryptedPasswordForTiedProfile(profileHandle),
1168 LockPatternUtils.CREDENTIAL_TYPE_PASSWORD,
1169 false, 0 /* no challenge */, profileHandle, null /* progressCallback */);
Ricky Waidc283a82016-03-24 19:55:08 +00001170 } catch (UnrecoverableKeyException | InvalidKeyException | KeyStoreException
1171 | NoSuchAlgorithmException | NoSuchPaddingException
1172 | InvalidAlgorithmParameterException | IllegalBlockSizeException
1173 | BadPaddingException | CertificateException | IOException e) {
1174 if (e instanceof FileNotFoundException) {
1175 Slog.i(TAG, "Child profile key not found");
Pavel Grafov0acc4bf2017-08-23 12:20:54 +01001176 } else if (ignoreUserNotAuthenticated && e instanceof UserNotAuthenticatedException) {
1177 Slog.i(TAG, "Parent keystore seems locked, ignoring");
Clara Bayarri0a587d22016-02-23 14:49:41 -08001178 } else {
Ricky Waidc283a82016-03-24 19:55:08 +00001179 Slog.e(TAG, "Failed to decrypt child profile key", e);
Clara Bayarri0a587d22016-02-23 14:49:41 -08001180 }
Jim Millerde1af082013-09-11 14:58:26 -07001181 }
1182 }
1183
Paul Crowleyfaeb3eb2016-02-08 15:58:29 +00001184 private void unlockUser(int userId, byte[] token, byte[] secret) {
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06001185 // TODO: make this method fully async so we can update UI with progress strings
1186 final CountDownLatch latch = new CountDownLatch(1);
1187 final IProgressListener listener = new IProgressListener.Stub() {
1188 @Override
1189 public void onStarted(int id, Bundle extras) throws RemoteException {
Jeff Sharkeyfd241082016-04-19 15:58:24 -06001190 Log.d(TAG, "unlockUser started");
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06001191 }
1192
1193 @Override
1194 public void onProgress(int id, int progress, Bundle extras) throws RemoteException {
Jeff Sharkeyfd241082016-04-19 15:58:24 -06001195 Log.d(TAG, "unlockUser progress " + progress);
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06001196 }
1197
1198 @Override
1199 public void onFinished(int id, Bundle extras) throws RemoteException {
Jeff Sharkeyfd241082016-04-19 15:58:24 -06001200 Log.d(TAG, "unlockUser finished");
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06001201 latch.countDown();
1202 }
1203 };
1204
Jeff Sharkey8924e872015-11-30 12:52:10 -07001205 try {
Rubin Xu0cbc19e2016-12-09 14:00:21 +00001206 mActivityManager.unlockUser(userId, token, secret, listener);
Jeff Sharkey8924e872015-11-30 12:52:10 -07001207 } catch (RemoteException e) {
1208 throw e.rethrowAsRuntimeException();
1209 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06001210
1211 try {
1212 latch.await(15, TimeUnit.SECONDS);
1213 } catch (InterruptedException e) {
1214 Thread.currentThread().interrupt();
1215 }
Ricky Waidc283a82016-03-24 19:55:08 +00001216 try {
1217 if (!mUserManager.getUserInfo(userId).isManagedProfile()) {
1218 final List<UserInfo> profiles = mUserManager.getProfiles(userId);
1219 for (UserInfo pi : profiles) {
1220 // Unlock managed profile with unified lock
Pavel Grafov0acc4bf2017-08-23 12:20:54 +01001221 if (tiedManagedProfileReadyToUnlock(pi)) {
1222 unlockChildProfile(pi.id, false /* ignoreUserNotAuthenticated */);
Ricky Waidc283a82016-03-24 19:55:08 +00001223 }
1224 }
1225 }
1226 } catch (RemoteException e) {
1227 Log.d(TAG, "Failed to unlock child profile", e);
1228 }
Jeff Sharkey8924e872015-11-30 12:52:10 -07001229 }
Amith Yamasani52c489c2012-03-28 11:42:42 -07001230
Pavel Grafov0acc4bf2017-08-23 12:20:54 +01001231 private boolean tiedManagedProfileReadyToUnlock(UserInfo userInfo) {
1232 return userInfo.isManagedProfile()
1233 && !mLockPatternUtils.isSeparateProfileChallengeEnabled(userInfo.id)
1234 && mStorage.hasChildProfileLock(userInfo.id)
1235 && mUserManager.isUserRunning(userInfo.id);
1236 }
1237
Rich Canningsf64ec632019-02-21 12:40:36 -08001238 private Map<Integer, byte[]> getDecryptedPasswordsForAllTiedProfiles(int userId) {
Rubin Xua55b1682017-01-31 10:06:56 +00001239 if (mUserManager.getUserInfo(userId).isManagedProfile()) {
1240 return null;
Andres Morales8fa56652015-03-31 09:19:50 -07001241 }
Rich Canningsf64ec632019-02-21 12:40:36 -08001242 Map<Integer, byte[]> result = new ArrayMap<Integer, byte[]>();
Rubin Xua55b1682017-01-31 10:06:56 +00001243 final List<UserInfo> profiles = mUserManager.getProfiles(userId);
1244 final int size = profiles.size();
1245 for (int i = 0; i < size; i++) {
1246 final UserInfo profile = profiles.get(i);
1247 if (!profile.isManagedProfile()) {
1248 continue;
1249 }
1250 final int managedUserId = profile.id;
1251 if (mLockPatternUtils.isSeparateProfileChallengeEnabled(managedUserId)) {
1252 continue;
1253 }
1254 try {
Rubin Xu4f988c92017-09-12 16:25:26 +01001255 result.put(managedUserId, getDecryptedPasswordForTiedProfile(managedUserId));
Rubin Xua55b1682017-01-31 10:06:56 +00001256 } catch (KeyStoreException | UnrecoverableKeyException | NoSuchAlgorithmException
1257 | NoSuchPaddingException | InvalidKeyException
1258 | InvalidAlgorithmParameterException | IllegalBlockSizeException
1259 | BadPaddingException | CertificateException | IOException e) {
Rubin Xu4f988c92017-09-12 16:25:26 +01001260 Slog.e(TAG, "getDecryptedPasswordsForAllTiedProfiles failed for user " +
1261 managedUserId, e);
Rubin Xua55b1682017-01-31 10:06:56 +00001262 }
1263 }
1264 return result;
Amith Yamasani52c489c2012-03-28 11:42:42 -07001265 }
1266
Rubin Xua55b1682017-01-31 10:06:56 +00001267 /**
1268 * Synchronize all profile's work challenge of the given user if it's unified: tie or clear them
1269 * depending on the parent user's secure state.
1270 *
1271 * When clearing tied work challenges, a pre-computed password table for profiles are required,
1272 * since changing password for profiles requires existing password, and existing passwords can
1273 * only be computed before the parent user's password is cleared.
1274 *
1275 * Strictly this is a recursive function, since setLockCredentialInternal ends up calling this
1276 * method again on profiles. However the recursion is guaranteed to terminate as this method
1277 * terminates when the user is a managed profile.
1278 */
1279 private void synchronizeUnifiedWorkChallengeForProfiles(int userId,
Rich Canningsf64ec632019-02-21 12:40:36 -08001280 Map<Integer, byte[]> profilePasswordMap) throws RemoteException {
Ricky Waidc283a82016-03-24 19:55:08 +00001281 if (mUserManager.getUserInfo(userId).isManagedProfile()) {
1282 return;
1283 }
Rubin Xua55b1682017-01-31 10:06:56 +00001284 final boolean isSecure = isUserSecure(userId);
Ricky Waidc283a82016-03-24 19:55:08 +00001285 final List<UserInfo> profiles = mUserManager.getProfiles(userId);
1286 final int size = profiles.size();
1287 for (int i = 0; i < size; i++) {
1288 final UserInfo profile = profiles.get(i);
1289 if (profile.isManagedProfile()) {
1290 final int managedUserId = profile.id;
1291 if (mLockPatternUtils.isSeparateProfileChallengeEnabled(managedUserId)) {
1292 continue;
1293 }
1294 if (isSecure) {
1295 tieManagedProfileLockIfNecessary(managedUserId, null);
1296 } else {
Rubin Xua55b1682017-01-31 10:06:56 +00001297 // We use cached work profile password computed before clearing the parent's
1298 // credential, otherwise they get lost
1299 if (profilePasswordMap != null && profilePasswordMap.containsKey(managedUserId)) {
1300 setLockCredentialInternal(null, LockPatternUtils.CREDENTIAL_TYPE_NONE,
Adrian Roos7374d3a2017-03-31 14:14:53 -07001301 profilePasswordMap.get(managedUserId),
1302 DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED, managedUserId);
Rubin Xua55b1682017-01-31 10:06:56 +00001303 } else {
1304 Slog.wtf(TAG, "clear tied profile challenges, but no password supplied.");
1305 // Supplying null here would lead to untrusted credential change
1306 setLockCredentialInternal(null, LockPatternUtils.CREDENTIAL_TYPE_NONE, null,
Adrian Roos7374d3a2017-03-31 14:14:53 -07001307 DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED, managedUserId);
Rubin Xua55b1682017-01-31 10:06:56 +00001308 }
Ricky Waidc283a82016-03-24 19:55:08 +00001309 mStorage.removeChildProfileLock(managedUserId);
1310 removeKeystoreProfileKey(managedUserId);
1311 }
1312 }
1313 }
1314 }
Andres Morales8fa56652015-03-31 09:19:50 -07001315
Ricky Waidc283a82016-03-24 19:55:08 +00001316 private boolean isManagedProfileWithUnifiedLock(int userId) {
1317 return mUserManager.getUserInfo(userId).isManagedProfile()
1318 && !mLockPatternUtils.isSeparateProfileChallengeEnabled(userId);
1319 }
1320
1321 private boolean isManagedProfileWithSeparatedLock(int userId) {
1322 return mUserManager.getUserInfo(userId).isManagedProfile()
1323 && mLockPatternUtils.isSeparateProfileChallengeEnabled(userId);
1324 }
1325
1326 // This method should be called by LockPatternUtil only, all internal methods in this class
Rubin Xu1de89b32016-11-30 20:03:13 +00001327 // should call setLockCredentialInternal.
Amith Yamasani52c489c2012-03-28 11:42:42 -07001328 @Override
Rich Canningsf64ec632019-02-21 12:40:36 -08001329 public void setLockCredential(byte[] credential, int type,
1330 byte[] savedCredential, int requestedQuality, int userId)
Andres Morales8fa56652015-03-31 09:19:50 -07001331 throws RemoteException {
Rich Canningsf64ec632019-02-21 12:40:36 -08001332
Lenka Trochtova66c492a2018-12-06 11:29:21 +01001333 if (!mLockPatternUtils.hasSecureLockScreen()) {
1334 throw new UnsupportedOperationException(
1335 "This operation requires secure lock screen feature");
1336 }
Jim Millere484eaf2016-04-13 16:35:36 -07001337 checkWritePermission(userId);
Ricky Waidc283a82016-03-24 19:55:08 +00001338 synchronized (mSeparateChallengeLock) {
Adrian Roos7374d3a2017-03-31 14:14:53 -07001339 setLockCredentialInternal(credential, type, savedCredential, requestedQuality, userId);
Pavel Grafov28939982017-10-03 15:11:52 +01001340 setSeparateProfileChallengeEnabledLocked(userId, true, null);
Andrew Scull5daf2732016-11-14 15:02:45 +00001341 notifyPasswordChanged(userId);
Ricky Waidc283a82016-03-24 19:55:08 +00001342 }
Pavel Grafov28939982017-10-03 15:11:52 +01001343 notifySeparateProfileChallengeChanged(userId);
Ricky Waidc283a82016-03-24 19:55:08 +00001344 }
1345
Rich Canningsf64ec632019-02-21 12:40:36 -08001346 private void setLockCredentialInternal(byte[] credential, int credentialType,
1347 byte[] savedCredential, int requestedQuality, int userId) throws RemoteException {
Rubin Xudf406d82017-02-16 16:49:43 +00001348 // Normalize savedCredential and credential such that empty string is always represented
1349 // as null.
Rich Canningsf64ec632019-02-21 12:40:36 -08001350 if (savedCredential == null || savedCredential.length == 0) {
Rubin Xudf406d82017-02-16 16:49:43 +00001351 savedCredential = null;
1352 }
Rich Canningsf64ec632019-02-21 12:40:36 -08001353 if (credential == null || credential.length == 0) {
Rubin Xudf406d82017-02-16 16:49:43 +00001354 credential = null;
1355 }
Rubin Xu3bf722a2016-12-15 16:07:38 +00001356 synchronized (mSpManager) {
1357 if (isSyntheticPasswordBasedCredentialLocked(userId)) {
1358 spBasedSetLockCredentialInternalLocked(credential, credentialType, savedCredential,
Adrian Roos7374d3a2017-03-31 14:14:53 -07001359 requestedQuality, userId);
Rubin Xu3bf722a2016-12-15 16:07:38 +00001360 return;
1361 }
1362 }
Adrian Roos7374d3a2017-03-31 14:14:53 -07001363
Rubin Xu1de89b32016-11-30 20:03:13 +00001364 if (credentialType == LockPatternUtils.CREDENTIAL_TYPE_NONE) {
1365 if (credential != null) {
1366 Slog.wtf(TAG, "CredentialType is none, but credential is non-null.");
1367 }
Paul Crowleycc701552016-05-17 14:18:49 -07001368 clearUserKeyProtection(userId);
Andres Moralescfb61602015-04-16 16:31:15 -07001369 getGateKeeperService().clearSecureUserId(userId);
Rubin Xu1de89b32016-11-30 20:03:13 +00001370 mStorage.writeCredentialHash(CredentialHash.createEmptyHash(), userId);
Chad Brubakera91a8502015-05-07 10:02:22 -07001371 setKeystorePassword(null, userId);
Paul Crowleycc701552016-05-17 14:18:49 -07001372 fixateNewestUserKeyAuth(userId);
Rubin Xua55b1682017-01-31 10:06:56 +00001373 synchronizeUnifiedWorkChallengeForProfiles(userId, null);
Andrew Scull5daf2732016-11-14 15:02:45 +00001374 notifyActivePasswordMetricsAvailable(null, userId);
Dmitry Dementyev77183ef2018-01-05 15:46:00 -08001375 mRecoverableKeyStoreManager.lockScreenSecretChanged(credentialType, credential, userId);
Andres Moralesd9fc85a2015-04-09 19:14:42 -07001376 return;
1377 }
Rubin Xu1de89b32016-11-30 20:03:13 +00001378 if (credential == null) {
1379 throw new RemoteException("Null credential with mismatched credential type");
Andres Morales8fa56652015-03-31 09:19:50 -07001380 }
Rubin Xua55b1682017-01-31 10:06:56 +00001381
1382 CredentialHash currentHandle = mStorage.readCredentialHash(userId);
Ricky Waidc283a82016-03-24 19:55:08 +00001383 if (isManagedProfileWithUnifiedLock(userId)) {
1384 // get credential from keystore when managed profile has unified lock
Rubin Xua55b1682017-01-31 10:06:56 +00001385 if (savedCredential == null) {
1386 try {
1387 savedCredential = getDecryptedPasswordForTiedProfile(userId);
1388 } catch (FileNotFoundException e) {
1389 Slog.i(TAG, "Child profile key not found");
1390 } catch (UnrecoverableKeyException | InvalidKeyException | KeyStoreException
1391 | NoSuchAlgorithmException | NoSuchPaddingException
1392 | InvalidAlgorithmParameterException | IllegalBlockSizeException
1393 | BadPaddingException | CertificateException | IOException e) {
1394 Slog.e(TAG, "Failed to decrypt child profile key", e);
1395 }
Andres Morales8fa56652015-03-31 09:19:50 -07001396 }
Ricky Waidc283a82016-03-24 19:55:08 +00001397 } else {
Rubin Xua55b1682017-01-31 10:06:56 +00001398 if (currentHandle.hash == null) {
Ricky Waidc283a82016-03-24 19:55:08 +00001399 if (savedCredential != null) {
1400 Slog.w(TAG, "Saved credential provided, but none stored");
1401 }
1402 savedCredential = null;
1403 }
Andres Morales8fa56652015-03-31 09:19:50 -07001404 }
Rubin Xu3bf722a2016-12-15 16:07:38 +00001405 synchronized (mSpManager) {
1406 if (shouldMigrateToSyntheticPasswordLocked(userId)) {
1407 initializeSyntheticPasswordLocked(currentHandle.hash, savedCredential,
Adrian Roos7374d3a2017-03-31 14:14:53 -07001408 currentHandle.type, requestedQuality, userId);
Rubin Xu3bf722a2016-12-15 16:07:38 +00001409 spBasedSetLockCredentialInternalLocked(credential, credentialType, savedCredential,
Adrian Roos7374d3a2017-03-31 14:14:53 -07001410 requestedQuality, userId);
Rubin Xu3bf722a2016-12-15 16:07:38 +00001411 return;
1412 }
1413 }
1414 if (DEBUG) Slog.d(TAG, "setLockCredentialInternal: user=" + userId);
Rubin Xua55b1682017-01-31 10:06:56 +00001415 byte[] enrolledHandle = enrollCredential(currentHandle.hash, savedCredential, credential,
Rubin Xu1de89b32016-11-30 20:03:13 +00001416 userId);
Andres Morales8fa56652015-03-31 09:19:50 -07001417 if (enrolledHandle != null) {
Rubin Xu1de89b32016-11-30 20:03:13 +00001418 CredentialHash willStore = CredentialHash.create(enrolledHandle, credentialType);
1419 mStorage.writeCredentialHash(willStore, userId);
Rubin Xua55b1682017-01-31 10:06:56 +00001420 // push new secret and auth token to vold
1421 GateKeeperResponse gkResponse = getGateKeeperService()
Rich Canningsf64ec632019-02-21 12:40:36 -08001422 .verifyChallenge(userId, 0, willStore.hash, credential);
Rubin Xua55b1682017-01-31 10:06:56 +00001423 setUserKeyProtection(userId, credential, convertResponse(gkResponse));
Paul Crowleycc701552016-05-17 14:18:49 -07001424 fixateNewestUserKeyAuth(userId);
Rubin Xua55b1682017-01-31 10:06:56 +00001425 // Refresh the auth token
1426 doVerifyCredential(credential, credentialType, true, 0, userId, null /* progressCallback */);
1427 synchronizeUnifiedWorkChallengeForProfiles(userId, null);
Dmitry Dementyev6e167242018-01-25 15:29:50 -08001428 mRecoverableKeyStoreManager.lockScreenSecretChanged(credentialType, credential,
1429 userId);
Andres Morales8fa56652015-03-31 09:19:50 -07001430 } else {
Rubin Xu1de89b32016-11-30 20:03:13 +00001431 throw new RemoteException("Failed to enroll " +
1432 (credentialType == LockPatternUtils.CREDENTIAL_TYPE_PASSWORD ? "password"
1433 : "pattern"));
Andres Morales8fa56652015-03-31 09:19:50 -07001434 }
1435 }
1436
Rubin Xua55b1682017-01-31 10:06:56 +00001437 private VerifyCredentialResponse convertResponse(GateKeeperResponse gateKeeperResponse) {
Adrian Roos7374d3a2017-03-31 14:14:53 -07001438 return VerifyCredentialResponse.fromGateKeeperResponse(gateKeeperResponse);
Rubin Xua55b1682017-01-31 10:06:56 +00001439 }
1440
Rubin Xu0cbc19e2016-12-09 14:00:21 +00001441 @VisibleForTesting
Rich Canningsf64ec632019-02-21 12:40:36 -08001442 protected void tieProfileLockToParent(int userId, byte[] password) {
Ricky Waidc283a82016-03-24 19:55:08 +00001443 if (DEBUG) Slog.v(TAG, "tieProfileLockToParent for user: " + userId);
Ricky Waidc283a82016-03-24 19:55:08 +00001444 byte[] encryptionResult;
1445 byte[] iv;
1446 try {
1447 KeyGenerator keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES);
1448 keyGenerator.init(new SecureRandom());
1449 SecretKey secretKey = keyGenerator.generateKey();
Ricky Waidc283a82016-03-24 19:55:08 +00001450 java.security.KeyStore keyStore = java.security.KeyStore.getInstance("AndroidKeyStore");
1451 keyStore.load(null);
Ricky Wai97c8f8d2016-07-13 17:57:45 +01001452 try {
1453 keyStore.setEntry(
1454 LockPatternUtils.PROFILE_KEY_NAME_ENCRYPT + userId,
1455 new java.security.KeyStore.SecretKeyEntry(secretKey),
1456 new KeyProtection.Builder(KeyProperties.PURPOSE_ENCRYPT)
1457 .setBlockModes(KeyProperties.BLOCK_MODE_GCM)
1458 .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
1459 .build());
1460 keyStore.setEntry(
1461 LockPatternUtils.PROFILE_KEY_NAME_DECRYPT + userId,
1462 new java.security.KeyStore.SecretKeyEntry(secretKey),
1463 new KeyProtection.Builder(KeyProperties.PURPOSE_DECRYPT)
1464 .setBlockModes(KeyProperties.BLOCK_MODE_GCM)
1465 .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
1466 .setUserAuthenticationRequired(true)
1467 .setUserAuthenticationValidityDurationSeconds(30)
Pavel Grafove053c1e2017-08-08 16:53:32 +01001468 .setCriticalToDeviceEncryption(true)
Ricky Wai97c8f8d2016-07-13 17:57:45 +01001469 .build());
1470 // Key imported, obtain a reference to it.
1471 SecretKey keyStoreEncryptionKey = (SecretKey) keyStore.getKey(
1472 LockPatternUtils.PROFILE_KEY_NAME_ENCRYPT + userId, null);
1473 Cipher cipher = Cipher.getInstance(
1474 KeyProperties.KEY_ALGORITHM_AES + "/" + KeyProperties.BLOCK_MODE_GCM + "/"
1475 + KeyProperties.ENCRYPTION_PADDING_NONE);
1476 cipher.init(Cipher.ENCRYPT_MODE, keyStoreEncryptionKey);
Rich Canningsf64ec632019-02-21 12:40:36 -08001477 encryptionResult = cipher.doFinal(password);
Ricky Wai97c8f8d2016-07-13 17:57:45 +01001478 iv = cipher.getIV();
1479 } finally {
1480 // The original key can now be discarded.
1481 keyStore.deleteEntry(LockPatternUtils.PROFILE_KEY_NAME_ENCRYPT + userId);
1482 }
Ricky Waidc283a82016-03-24 19:55:08 +00001483 } catch (CertificateException | UnrecoverableKeyException
Zach Jange61672a2016-11-22 17:47:18 +00001484 | IOException | BadPaddingException | IllegalBlockSizeException | KeyStoreException
Ricky Waidc283a82016-03-24 19:55:08 +00001485 | NoSuchPaddingException | NoSuchAlgorithmException | InvalidKeyException e) {
1486 throw new RuntimeException("Failed to encrypt key", e);
1487 }
1488 ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
1489 try {
1490 if (iv.length != PROFILE_KEY_IV_SIZE) {
1491 throw new RuntimeException("Invalid iv length: " + iv.length);
1492 }
1493 outputStream.write(iv);
1494 outputStream.write(encryptionResult);
1495 } catch (IOException e) {
1496 throw new RuntimeException("Failed to concatenate byte arrays", e);
1497 }
1498 mStorage.writeChildProfileLock(userId, outputStream.toByteArray());
1499 }
1500
Andres Morales8fa56652015-03-31 09:19:50 -07001501 private byte[] enrollCredential(byte[] enrolledHandle,
Rich Canningsf64ec632019-02-21 12:40:36 -08001502 byte[] enrolledCredential, byte[] toEnroll, int userId)
Andres Morales8fa56652015-03-31 09:19:50 -07001503 throws RemoteException {
Jim Millerde1af082013-09-11 14:58:26 -07001504 checkWritePermission(userId);
Andres Morales23974272015-05-14 22:42:26 -07001505 GateKeeperResponse response = getGateKeeperService().enroll(userId, enrolledHandle,
Rich Canningsf64ec632019-02-21 12:40:36 -08001506 enrolledCredential, toEnroll);
Jim Millerde1af082013-09-11 14:58:26 -07001507
Andres Morales23974272015-05-14 22:42:26 -07001508 if (response == null) {
1509 return null;
Andres Morales8fa56652015-03-31 09:19:50 -07001510 }
Jim Millerde1af082013-09-11 14:58:26 -07001511
Andres Morales23974272015-05-14 22:42:26 -07001512 byte[] hash = response.getPayload();
1513 if (hash != null) {
1514 setKeystorePassword(toEnroll, userId);
1515 } else {
1516 // Should not happen
1517 Slog.e(TAG, "Throttled while enrolling a password");
1518 }
Andres Morales8fa56652015-03-31 09:19:50 -07001519 return hash;
Jim Millerde1af082013-09-11 14:58:26 -07001520 }
1521
Rubin Xu3bf722a2016-12-15 16:07:38 +00001522 private void setAuthlessUserKeyProtection(int userId, byte[] key) throws RemoteException {
1523 if (DEBUG) Slog.d(TAG, "setAuthlessUserKeyProtectiond: user=" + userId);
1524 addUserKeyAuth(userId, null, key);
1525 }
1526
Rich Canningsf64ec632019-02-21 12:40:36 -08001527 private void setUserKeyProtection(int userId, byte[] credential, VerifyCredentialResponse vcr)
Paul Crowleyfaeb3eb2016-02-08 15:58:29 +00001528 throws RemoteException {
Rubin Xua55b1682017-01-31 10:06:56 +00001529 if (DEBUG) Slog.d(TAG, "setUserKeyProtection: user=" + userId);
Paul Crowleyfaeb3eb2016-02-08 15:58:29 +00001530 if (vcr == null) {
1531 throw new RemoteException("Null response verifying a credential we just set");
1532 }
1533 if (vcr.getResponseCode() != VerifyCredentialResponse.RESPONSE_OK) {
1534 throw new RemoteException("Non-OK response verifying a credential we just set: "
Rubin Xu1de89b32016-11-30 20:03:13 +00001535 + vcr.getResponseCode());
Paul Crowleyfaeb3eb2016-02-08 15:58:29 +00001536 }
1537 byte[] token = vcr.getPayload();
1538 if (token == null) {
1539 throw new RemoteException("Empty payload verifying a credential we just set");
1540 }
Paul Crowleycc701552016-05-17 14:18:49 -07001541 addUserKeyAuth(userId, token, secretFromCredential(credential));
Paul Crowleyfaeb3eb2016-02-08 15:58:29 +00001542 }
1543
1544 private void clearUserKeyProtection(int userId) throws RemoteException {
Rubin Xua55b1682017-01-31 10:06:56 +00001545 if (DEBUG) Slog.d(TAG, "clearUserKeyProtection user=" + userId);
Paul Crowleycc701552016-05-17 14:18:49 -07001546 addUserKeyAuth(userId, null, null);
Paul Crowleyfaeb3eb2016-02-08 15:58:29 +00001547 }
1548
Rich Canningsf64ec632019-02-21 12:40:36 -08001549 private static byte[] secretFromCredential(byte[] credential) throws RemoteException {
Paul Crowleyfaeb3eb2016-02-08 15:58:29 +00001550 try {
1551 MessageDigest digest = MessageDigest.getInstance("SHA-512");
1552 // Personalize the hash
Rich Canningsf64ec632019-02-21 12:40:36 -08001553 byte[] personalization = "Android FBE credential hash".getBytes();
Paul Crowleyfaeb3eb2016-02-08 15:58:29 +00001554 // Pad it to the block size of the hash function
1555 personalization = Arrays.copyOf(personalization, 128);
1556 digest.update(personalization);
Rich Canningsf64ec632019-02-21 12:40:36 -08001557 digest.update(credential);
Paul Crowleyfaeb3eb2016-02-08 15:58:29 +00001558 return digest.digest();
1559 } catch (NoSuchAlgorithmException e) {
1560 throw new RuntimeException("NoSuchAlgorithmException for SHA-512");
1561 }
1562 }
1563
Paul Crowleycc701552016-05-17 14:18:49 -07001564 private void addUserKeyAuth(int userId, byte[] token, byte[] secret)
Paul Crowleyfaeb3eb2016-02-08 15:58:29 +00001565 throws RemoteException {
Rubin Xu0cbc19e2016-12-09 14:00:21 +00001566 final UserInfo userInfo = mUserManager.getUserInfo(userId);
1567 final IStorageManager storageManager = mInjector.getStorageManager();
Paul Crowley815036f2016-03-29 14:14:48 -07001568 final long callingId = Binder.clearCallingIdentity();
1569 try {
Sudheer Shanka2250d562016-11-07 15:41:02 -08001570 storageManager.addUserKeyAuth(userId, userInfo.serialNumber, token, secret);
Paul Crowley815036f2016-03-29 14:14:48 -07001571 } finally {
1572 Binder.restoreCallingIdentity(callingId);
1573 }
Paul Crowleyfaeb3eb2016-02-08 15:58:29 +00001574 }
1575
Paul Crowleycc701552016-05-17 14:18:49 -07001576 private void fixateNewestUserKeyAuth(int userId)
1577 throws RemoteException {
Rubin Xua55b1682017-01-31 10:06:56 +00001578 if (DEBUG) Slog.d(TAG, "fixateNewestUserKeyAuth: user=" + userId);
Rubin Xu0cbc19e2016-12-09 14:00:21 +00001579 final IStorageManager storageManager = mInjector.getStorageManager();
Toni Barzic6c818722016-05-27 09:18:39 -07001580 final long callingId = Binder.clearCallingIdentity();
1581 try {
Sudheer Shanka2250d562016-11-07 15:41:02 -08001582 storageManager.fixateNewestUserKeyAuth(userId);
Toni Barzic6c818722016-05-27 09:18:39 -07001583 } finally {
1584 Binder.restoreCallingIdentity(callingId);
1585 }
Paul Crowleycc701552016-05-17 14:18:49 -07001586 }
1587
Jim Millerde1af082013-09-11 14:58:26 -07001588 @Override
Ricky Wai4613fe42016-05-24 11:11:42 +01001589 public void resetKeyStore(int userId) throws RemoteException {
Ricky Wai7f405f12016-05-31 12:05:05 +01001590 checkWritePermission(userId);
Ricky Wai4613fe42016-05-24 11:11:42 +01001591 if (DEBUG) Slog.v(TAG, "Reset keystore for user: " + userId);
1592 int managedUserId = -1;
Rich Canningsf64ec632019-02-21 12:40:36 -08001593 byte[] managedUserDecryptedPassword = null;
Ricky Wai4613fe42016-05-24 11:11:42 +01001594 final List<UserInfo> profiles = mUserManager.getProfiles(userId);
1595 for (UserInfo pi : profiles) {
1596 // Unlock managed profile with unified lock
1597 if (pi.isManagedProfile()
1598 && !mLockPatternUtils.isSeparateProfileChallengeEnabled(pi.id)
1599 && mStorage.hasChildProfileLock(pi.id)) {
1600 try {
1601 if (managedUserId == -1) {
1602 managedUserDecryptedPassword = getDecryptedPasswordForTiedProfile(pi.id);
1603 managedUserId = pi.id;
1604 } else {
1605 // Should not happen
1606 Slog.e(TAG, "More than one managed profile, uid1:" + managedUserId
1607 + ", uid2:" + pi.id);
1608 }
1609 } catch (UnrecoverableKeyException | InvalidKeyException | KeyStoreException
1610 | NoSuchAlgorithmException | NoSuchPaddingException
1611 | InvalidAlgorithmParameterException | IllegalBlockSizeException
1612 | BadPaddingException | CertificateException | IOException e) {
1613 Slog.e(TAG, "Failed to decrypt child profile key", e);
1614 }
1615 }
1616 }
1617 try {
1618 // Clear all the users credentials could have been installed in for this user.
1619 for (int profileId : mUserManager.getProfileIdsWithDisabled(userId)) {
1620 for (int uid : SYSTEM_CREDENTIAL_UIDS) {
1621 mKeyStore.clearUid(UserHandle.getUid(profileId, uid));
1622 }
1623 }
1624 } finally {
1625 if (managedUserId != -1 && managedUserDecryptedPassword != null) {
1626 if (DEBUG) Slog.v(TAG, "Restore tied profile lock");
Zach Jange61672a2016-11-22 17:47:18 +00001627 tieProfileLockToParent(managedUserId, managedUserDecryptedPassword);
Ricky Wai4613fe42016-05-24 11:11:42 +01001628 }
1629 }
Rich Canningsf64ec632019-02-21 12:40:36 -08001630 if (managedUserDecryptedPassword != null && managedUserDecryptedPassword.length > 0) {
1631 Arrays.fill(managedUserDecryptedPassword, (byte) 0);
1632 }
Ricky Wai4613fe42016-05-24 11:11:42 +01001633 }
1634
1635 @Override
Rich Canningsf64ec632019-02-21 12:40:36 -08001636 public VerifyCredentialResponse checkCredential(byte[] credential, int type, int userId,
Jorim Jaggie8fde5d2016-06-30 23:41:37 -07001637 ICheckCredentialProgressCallback progressCallback) throws RemoteException {
Rubin Xu1de89b32016-11-30 20:03:13 +00001638 checkPasswordReadPermission(userId);
1639 return doVerifyCredential(credential, type, false, 0, userId, progressCallback);
Andres Moralesd9fc85a2015-04-09 19:14:42 -07001640 }
Adrian Roos261d5ab2014-10-29 14:42:38 +01001641
Andres Moralesd9fc85a2015-04-09 19:14:42 -07001642 @Override
Rich Canningsf64ec632019-02-21 12:40:36 -08001643 public VerifyCredentialResponse verifyCredential(byte[] credential, int type, long challenge,
Rubin Xu1de89b32016-11-30 20:03:13 +00001644 int userId) throws RemoteException {
1645 checkPasswordReadPermission(userId);
1646 return doVerifyCredential(credential, type, true, challenge, userId,
1647 null /* progressCallback */);
Andres Moralesd9fc85a2015-04-09 19:14:42 -07001648 }
1649
Rubin Xu1de89b32016-11-30 20:03:13 +00001650 /**
1651 * Verify user credential and unlock the user. Fix pattern bug by deprecating the old base zero
1652 * format.
1653 */
Rich Canningsf64ec632019-02-21 12:40:36 -08001654 private VerifyCredentialResponse doVerifyCredential(byte[] credential, int credentialType,
Jorim Jaggie8fde5d2016-06-30 23:41:37 -07001655 boolean hasChallenge, long challenge, int userId,
1656 ICheckCredentialProgressCallback progressCallback) throws RemoteException {
Rich Canningsf64ec632019-02-21 12:40:36 -08001657 if (credential == null || credential.length == 0) {
Rubin Xu1de89b32016-11-30 20:03:13 +00001658 throw new IllegalArgumentException("Credential can't be null or empty");
1659 }
Adrian Roos7374d3a2017-03-31 14:14:53 -07001660 if (userId == USER_FRP && Settings.Global.getInt(mContext.getContentResolver(),
1661 Settings.Global.DEVICE_PROVISIONED, 0) != 0) {
1662 Slog.e(TAG, "FRP credential can only be verified prior to provisioning.");
1663 return VerifyCredentialResponse.ERROR;
1664 }
Rubin Xue94a7702017-06-20 17:29:57 +01001665 VerifyCredentialResponse response = null;
1666 response = spBasedDoVerifyCredential(credential, credentialType, hasChallenge, challenge,
1667 userId, progressCallback);
1668 // The user employs synthetic password based credential.
1669 if (response != null) {
Robert Berry40386df2018-01-22 21:16:58 +00001670 if (response.getResponseCode() == VerifyCredentialResponse.RESPONSE_OK) {
1671 mRecoverableKeyStoreManager.lockScreenSecretAvailable(credentialType, credential,
1672 userId);
1673 }
Rubin Xue94a7702017-06-20 17:29:57 +01001674 return response;
Rubin Xu3bf722a2016-12-15 16:07:38 +00001675 }
Rubin Xue94a7702017-06-20 17:29:57 +01001676
Adrian Roos7374d3a2017-03-31 14:14:53 -07001677 if (userId == USER_FRP) {
Andrew Scull971f2942017-07-12 15:09:45 +01001678 Slog.wtf(TAG, "Unexpected FRP credential type, should be SP based.");
1679 return VerifyCredentialResponse.ERROR;
Adrian Roos7374d3a2017-03-31 14:14:53 -07001680 }
1681
Andrew Scull971f2942017-07-12 15:09:45 +01001682 final CredentialHash storedHash = mStorage.readCredentialHash(userId);
Rubin Xu1de89b32016-11-30 20:03:13 +00001683 if (storedHash.type != credentialType) {
1684 Slog.wtf(TAG, "doVerifyCredential type mismatch with stored credential??"
1685 + " stored: " + storedHash.type + " passed in: " + credentialType);
1686 return VerifyCredentialResponse.ERROR;
1687 }
Andres Moralese40bad82015-05-28 14:21:36 -07001688
Rubin Xu1de89b32016-11-30 20:03:13 +00001689 boolean shouldReEnrollBaseZero = storedHash.type == LockPatternUtils.CREDENTIAL_TYPE_PATTERN
1690 && storedHash.isBaseZeroPattern;
Andres Moralese40bad82015-05-28 14:21:36 -07001691
Rich Canningsf64ec632019-02-21 12:40:36 -08001692 byte[] credentialToVerify;
Rubin Xu1de89b32016-11-30 20:03:13 +00001693 if (shouldReEnrollBaseZero) {
Rich Canningsf64ec632019-02-21 12:40:36 -08001694 credentialToVerify = LockPatternUtils.patternByteArrayToBaseZero(credential);
Rubin Xu1de89b32016-11-30 20:03:13 +00001695 } else {
1696 credentialToVerify = credential;
1697 }
Andres Moralesd9fc85a2015-04-09 19:14:42 -07001698
Rubin Xue94a7702017-06-20 17:29:57 +01001699 response = verifyCredential(userId, storedHash, credentialToVerify,
Rubin Xu1de89b32016-11-30 20:03:13 +00001700 hasChallenge, challenge, progressCallback);
Andres Morales59ef1262015-06-26 13:56:39 -07001701
Michal Karpinskie71f5832017-01-13 18:18:49 +00001702 if (response.getResponseCode() == VerifyCredentialResponse.RESPONSE_OK) {
1703 mStrongAuth.reportSuccessfulStrongAuthUnlock(userId);
1704 if (shouldReEnrollBaseZero) {
Adrian Roos7374d3a2017-03-31 14:14:53 -07001705 setLockCredentialInternal(credential, storedHash.type, credentialToVerify,
1706 DevicePolicyManager.PASSWORD_QUALITY_SOMETHING, userId);
Michal Karpinskie71f5832017-01-13 18:18:49 +00001707 }
Rubin Xu1de89b32016-11-30 20:03:13 +00001708 }
Andres Moralese40bad82015-05-28 14:21:36 -07001709
Rubin Xu1de89b32016-11-30 20:03:13 +00001710 return response;
Amith Yamasani52c489c2012-03-28 11:42:42 -07001711 }
1712
1713 @Override
Rich Canningsf64ec632019-02-21 12:40:36 -08001714 public VerifyCredentialResponse verifyTiedProfileChallenge(byte[] credential, int type,
Ricky Wai53940d42016-04-05 15:29:24 +01001715 long challenge, int userId) throws RemoteException {
1716 checkPasswordReadPermission(userId);
1717 if (!isManagedProfileWithUnifiedLock(userId)) {
1718 throw new RemoteException("User id must be managed profile with unified lock");
1719 }
1720 final int parentProfileId = mUserManager.getProfileParent(userId).id;
1721 // Unlock parent by using parent's challenge
Rubin Xu1de89b32016-11-30 20:03:13 +00001722 final VerifyCredentialResponse parentResponse = doVerifyCredential(
1723 credential,
1724 type,
1725 true /* hasChallenge */,
1726 challenge,
1727 parentProfileId,
1728 null /* progressCallback */);
Ricky Wai53940d42016-04-05 15:29:24 +01001729 if (parentResponse.getResponseCode() != VerifyCredentialResponse.RESPONSE_OK) {
1730 // Failed, just return parent's response
1731 return parentResponse;
1732 }
1733
1734 try {
1735 // Unlock work profile, and work profile with unified lock must use password only
Rubin Xu1de89b32016-11-30 20:03:13 +00001736 return doVerifyCredential(getDecryptedPasswordForTiedProfile(userId),
1737 LockPatternUtils.CREDENTIAL_TYPE_PASSWORD,
1738 true,
Ricky Wai53940d42016-04-05 15:29:24 +01001739 challenge,
Jorim Jaggie8fde5d2016-06-30 23:41:37 -07001740 userId, null /* progressCallback */);
Ricky Wai53940d42016-04-05 15:29:24 +01001741 } catch (UnrecoverableKeyException | InvalidKeyException | KeyStoreException
1742 | NoSuchAlgorithmException | NoSuchPaddingException
1743 | InvalidAlgorithmParameterException | IllegalBlockSizeException
1744 | BadPaddingException | CertificateException | IOException e) {
1745 Slog.e(TAG, "Failed to decrypt child profile key", e);
1746 throw new RemoteException("Unable to get tied profile token");
1747 }
1748 }
1749
Rubin Xu1de89b32016-11-30 20:03:13 +00001750 /**
1751 * Lowest-level credential verification routine that talks to GateKeeper. If verification
1752 * passes, unlock the corresponding user and keystore. Also handles the migration from legacy
1753 * hash to GK.
1754 */
Andres Morales23974272015-05-14 22:42:26 -07001755 private VerifyCredentialResponse verifyCredential(int userId, CredentialHash storedHash,
Rich Canningsf64ec632019-02-21 12:40:36 -08001756 byte[] credential, boolean hasChallenge, long challenge,
Rubin Xu1de89b32016-11-30 20:03:13 +00001757 ICheckCredentialProgressCallback progressCallback) throws RemoteException {
Rich Canningsf64ec632019-02-21 12:40:36 -08001758 if ((storedHash == null || storedHash.hash.length == 0)
1759 && (credential == null || credential.length == 0)) {
Andres Morales23974272015-05-14 22:42:26 -07001760 // don't need to pass empty credentials to GateKeeper
1761 return VerifyCredentialResponse.OK;
Andres Moralesd9fc85a2015-04-09 19:14:42 -07001762 }
1763
Rich Canningsf64ec632019-02-21 12:40:36 -08001764 if (storedHash == null || credential == null || credential.length == 0) {
Andres Morales23974272015-05-14 22:42:26 -07001765 return VerifyCredentialResponse.ERROR;
Amith Yamasani52c489c2012-03-28 11:42:42 -07001766 }
Adrian Roos261d5ab2014-10-29 14:42:38 +01001767
Jeff Sharkeyeddf5182016-08-09 16:36:08 -06001768 // We're potentially going to be doing a bunch of disk I/O below as part
1769 // of unlocking the user, so yell if calling from the main thread.
1770 StrictMode.noteDiskRead();
1771
Andres Morales8fa56652015-03-31 09:19:50 -07001772 if (storedHash.version == CredentialHash.VERSION_LEGACY) {
Rubin Xu1de89b32016-11-30 20:03:13 +00001773 final byte[] hash;
1774 if (storedHash.type == LockPatternUtils.CREDENTIAL_TYPE_PATTERN) {
Rich Canningsf64ec632019-02-21 12:40:36 -08001775 hash = LockPatternUtils.patternToHash(
1776 LockPatternUtils.byteArrayToPattern(credential));
Rubin Xu1de89b32016-11-30 20:03:13 +00001777 } else {
Rich Canningsf64ec632019-02-21 12:40:36 -08001778 hash = mLockPatternUtils.legacyPasswordToHash(credential, userId).getBytes();
Rubin Xu1de89b32016-11-30 20:03:13 +00001779 }
Andres Moralesd9fc85a2015-04-09 19:14:42 -07001780 if (Arrays.equals(hash, storedHash.hash)) {
Rubin Xu1de89b32016-11-30 20:03:13 +00001781 if (storedHash.type == LockPatternUtils.CREDENTIAL_TYPE_PATTERN) {
Rich Canningsf64ec632019-02-21 12:40:36 -08001782 unlockKeystore(LockPatternUtils.patternByteArrayToBaseZero(credential), userId);
Rubin Xu1de89b32016-11-30 20:03:13 +00001783 } else {
1784 unlockKeystore(credential, userId);
1785 }
Paul Crowleyfaeb3eb2016-02-08 15:58:29 +00001786 // Users with legacy credentials don't have credential-backed
1787 // FBE keys, so just pass through a fake token/secret
1788 Slog.i(TAG, "Unlocking user with fake token: " + userId);
1789 final byte[] fakeToken = String.valueOf(userId).getBytes();
1790 unlockUser(userId, fakeToken, fakeToken);
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -07001791
Andres Morales23974272015-05-14 22:42:26 -07001792 // migrate credential to GateKeeper
Adrian Roos7374d3a2017-03-31 14:14:53 -07001793 setLockCredentialInternal(credential, storedHash.type, null,
1794 storedHash.type == LockPatternUtils.CREDENTIAL_TYPE_PATTERN
1795 ? DevicePolicyManager.PASSWORD_QUALITY_SOMETHING
1796 : DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC
1797 /* TODO(roosa): keep the same password quality */, userId);
Andres Moralesd9fc85a2015-04-09 19:14:42 -07001798 if (!hasChallenge) {
Andrew Scull5daf2732016-11-14 15:02:45 +00001799 notifyActivePasswordMetricsAvailable(credential, userId);
Robert Berryf899bff2017-12-28 17:34:38 +00001800 // Use credentials to create recoverable keystore snapshot.
1801 mRecoverableKeyStoreManager.lockScreenSecretAvailable(
1802 storedHash.type, credential, userId);
Andres Morales23974272015-05-14 22:42:26 -07001803 return VerifyCredentialResponse.OK;
Andres Moralesd9fc85a2015-04-09 19:14:42 -07001804 }
1805 // Fall through to get the auth token. Technically this should never happen,
Andres Morales23974272015-05-14 22:42:26 -07001806 // as a user that had a legacy credential would have to unlock their device
Andres Moralesd9fc85a2015-04-09 19:14:42 -07001807 // before getting to a flow with a challenge, but supporting for consistency.
1808 } else {
Andres Morales23974272015-05-14 22:42:26 -07001809 return VerifyCredentialResponse.ERROR;
Andres Morales8fa56652015-03-31 09:19:50 -07001810 }
Andres Morales8fa56652015-03-31 09:19:50 -07001811 }
Paul Crowley98e0a262016-02-04 09:41:53 +00001812 GateKeeperResponse gateKeeperResponse = getGateKeeperService()
Rich Canningsf64ec632019-02-21 12:40:36 -08001813 .verifyChallenge(userId, challenge, storedHash.hash, credential);
Rubin Xua55b1682017-01-31 10:06:56 +00001814 VerifyCredentialResponse response = convertResponse(gateKeeperResponse);
1815 boolean shouldReEnroll = gateKeeperResponse.getShouldReEnroll();
Andres Morales8fa56652015-03-31 09:19:50 -07001816
Andres Morales23974272015-05-14 22:42:26 -07001817 if (response.getResponseCode() == VerifyCredentialResponse.RESPONSE_OK) {
Jorim Jaggie31f6b82016-07-01 16:15:09 -07001818
Andres Morales23974272015-05-14 22:42:26 -07001819 // credential has matched
Jorim Jaggie8fde5d2016-06-30 23:41:37 -07001820
1821 if (progressCallback != null) {
1822 progressCallback.onCredentialVerified();
1823 }
Andrew Scull5daf2732016-11-14 15:02:45 +00001824 notifyActivePasswordMetricsAvailable(credential, userId);
Andres Morales23974272015-05-14 22:42:26 -07001825 unlockKeystore(credential, userId);
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -07001826
Rubin Xu3bf722a2016-12-15 16:07:38 +00001827 Slog.i(TAG, "Unlocking user " + userId + " with token length "
1828 + response.getPayload().length);
Paul Crowleyfaeb3eb2016-02-08 15:58:29 +00001829 unlockUser(userId, response.getPayload(), secretFromCredential(credential));
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -07001830
Ricky Waidc283a82016-03-24 19:55:08 +00001831 if (isManagedProfileWithSeparatedLock(userId)) {
Clara Bayarri56878a92015-10-29 15:43:55 +00001832 TrustManager trustManager =
1833 (TrustManager) mContext.getSystemService(Context.TRUST_SERVICE);
1834 trustManager.setDeviceLockedForUser(userId, false);
1835 }
Adrian Roos7374d3a2017-03-31 14:14:53 -07001836 int reEnrollQuality = storedHash.type == LockPatternUtils.CREDENTIAL_TYPE_PATTERN
1837 ? DevicePolicyManager.PASSWORD_QUALITY_SOMETHING
1838 : DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC
1839 /* TODO(roosa): keep the same password quality */;
Andres Morales23974272015-05-14 22:42:26 -07001840 if (shouldReEnroll) {
Adrian Roos7374d3a2017-03-31 14:14:53 -07001841 setLockCredentialInternal(credential, storedHash.type, credential,
1842 reEnrollQuality, userId);
Rubin Xu3bf722a2016-12-15 16:07:38 +00001843 } else {
1844 // Now that we've cleared of all required GK migration, let's do the final
1845 // migration to synthetic password.
1846 synchronized (mSpManager) {
1847 if (shouldMigrateToSyntheticPasswordLocked(userId)) {
Rubin Xu128180b2017-04-12 18:02:44 +01001848 AuthenticationToken auth = initializeSyntheticPasswordLocked(
Adrian Roos7374d3a2017-03-31 14:14:53 -07001849 storedHash.hash, credential, storedHash.type, reEnrollQuality,
1850 userId);
Rubin Xu128180b2017-04-12 18:02:44 +01001851 activateEscrowTokens(auth, userId);
Rubin Xu3bf722a2016-12-15 16:07:38 +00001852 }
1853 }
Andres Morales23974272015-05-14 22:42:26 -07001854 }
Dmitry Dementyev6a509e42017-12-19 14:47:26 -08001855 // Use credentials to create recoverable keystore snapshot.
1856 mRecoverableKeyStoreManager.lockScreenSecretAvailable(storedHash.type, credential,
1857 userId);
1858
Adrian Roos873010d2015-08-25 15:59:00 -07001859 } else if (response.getResponseCode() == VerifyCredentialResponse.RESPONSE_RETRY) {
1860 if (response.getTimeout() > 0) {
1861 requireStrongAuth(STRONG_AUTH_REQUIRED_AFTER_LOCKOUT, userId);
1862 }
Andres Morales23974272015-05-14 22:42:26 -07001863 }
Amith Yamasani52c489c2012-03-28 11:42:42 -07001864
Andres Morales23974272015-05-14 22:42:26 -07001865 return response;
1866 }
Andres Moralesd9fc85a2015-04-09 19:14:42 -07001867
Rubin Xu7cf45092017-08-28 11:47:35 +01001868 /**
1869 * Call this method to notify DPMS regarding the latest password metric. This should be called
1870 * when the user is authenticating or when a new password is being set.
1871 */
Rich Canningsf64ec632019-02-21 12:40:36 -08001872 private void notifyActivePasswordMetricsAvailable(byte[] password, @UserIdInt int userId) {
Andrew Scull5daf2732016-11-14 15:02:45 +00001873 final PasswordMetrics metrics;
1874 if (password == null) {
1875 metrics = new PasswordMetrics();
1876 } else {
1877 metrics = PasswordMetrics.computeForPassword(password);
1878 metrics.quality = mLockPatternUtils.getKeyguardStoredPasswordQuality(userId);
1879 }
1880
1881 // Asynchronous to avoid dead lock
1882 mHandler.post(() -> {
1883 DevicePolicyManager dpm = (DevicePolicyManager)
1884 mContext.getSystemService(Context.DEVICE_POLICY_SERVICE);
1885 dpm.setActivePasswordState(metrics, userId);
1886 });
1887 }
1888
1889 /**
1890 * Call after {@link #notifyActivePasswordMetricsAvailable} so metrics are updated before
1891 * reporting the password changed.
1892 */
1893 private void notifyPasswordChanged(@UserIdInt int userId) {
1894 // Same handler as notifyActivePasswordMetricsAvailable to ensure correct ordering
1895 mHandler.post(() -> {
1896 DevicePolicyManager dpm = (DevicePolicyManager)
1897 mContext.getSystemService(Context.DEVICE_POLICY_SERVICE);
1898 dpm.reportPasswordChanged(userId);
Adrian Roos1c8e3c02018-11-20 20:07:55 +01001899 LocalServices.getService(WindowManagerInternal.class).reportPasswordChanged(userId);
Andrew Scull5daf2732016-11-14 15:02:45 +00001900 });
1901 }
1902
Amith Yamasani52c489c2012-03-28 11:42:42 -07001903 @Override
Adrian Roos261d5ab2014-10-29 14:42:38 +01001904 public boolean checkVoldPassword(int userId) throws RemoteException {
Paul Lawrence945490c2014-03-27 16:37:28 +00001905 if (!mFirstCallToVold) {
1906 return false;
1907 }
1908 mFirstCallToVold = false;
1909
1910 checkPasswordReadPermission(userId);
1911
1912 // There's no guarantee that this will safely connect, but if it fails
1913 // we will simply show the lock screen when we shouldn't, so relatively
1914 // benign. There is an outside chance something nasty would happen if
1915 // this service restarted before vold stales out the password in this
1916 // case. The nastiness is limited to not showing the lock screen when
1917 // we should, within the first minute of decrypting the phone if this
1918 // service can't connect to vold, it restarts, and then the new instance
1919 // does successfully connect.
Rubin Xu0cbc19e2016-12-09 14:00:21 +00001920 final IStorageManager service = mInjector.getStorageManager();
Rich Canningsf64ec632019-02-21 12:40:36 -08001921 // TODO(b/120484642): Update vold to return a password as a byte array
Paul Lawrence0bbd1082016-04-26 15:21:02 -07001922 String password;
1923 long identity = Binder.clearCallingIdentity();
1924 try {
1925 password = service.getPassword();
1926 service.clearPassword();
1927 } finally {
1928 Binder.restoreCallingIdentity(identity);
1929 }
Paul Lawrence945490c2014-03-27 16:37:28 +00001930 if (password == null) {
1931 return false;
1932 }
1933
1934 try {
Adrian Roos9dd16eb2015-01-08 16:20:49 +01001935 if (mLockPatternUtils.isLockPatternEnabled(userId)) {
Rich Canningsf64ec632019-02-21 12:40:36 -08001936 if (checkCredential(password.getBytes(), LockPatternUtils.CREDENTIAL_TYPE_PATTERN,
1937 userId, null /* progressCallback */)
Rubin Xu1de89b32016-11-30 20:03:13 +00001938 .getResponseCode() == GateKeeperResponse.RESPONSE_OK) {
Paul Lawrence945490c2014-03-27 16:37:28 +00001939 return true;
1940 }
1941 }
1942 } catch (Exception e) {
1943 }
1944
1945 try {
Adrian Roos9dd16eb2015-01-08 16:20:49 +01001946 if (mLockPatternUtils.isLockPasswordEnabled(userId)) {
Rich Canningsf64ec632019-02-21 12:40:36 -08001947 if (checkCredential(password.getBytes(), LockPatternUtils.CREDENTIAL_TYPE_PASSWORD,
1948 userId, null /* progressCallback */)
Rubin Xu1de89b32016-11-30 20:03:13 +00001949 .getResponseCode() == GateKeeperResponse.RESPONSE_OK) {
Paul Lawrence945490c2014-03-27 16:37:28 +00001950 return true;
1951 }
1952 }
1953 } catch (Exception e) {
1954 }
1955
1956 return false;
1957 }
1958
Amith Yamasanif11a5742016-06-16 08:20:07 -07001959 private void removeUser(int userId, boolean unknownUser) {
Rubin Xu7b7424b2017-03-31 18:03:20 +01001960 mSpManager.removeUser(userId);
Adrian Roos261d5ab2014-10-29 14:42:38 +01001961 mStorage.removeUser(userId);
Adrian Roosb5e47222015-08-14 15:53:06 -07001962 mStrongAuth.removeUser(userId);
Andrew Scullede482d2018-01-30 13:54:29 +00001963 tryRemoveUserFromSpCacheLater(userId);
Robin Lee49d810c2014-09-23 13:50:22 +01001964
1965 final KeyStore ks = KeyStore.getInstance();
Chad Brubaker83ce0952015-05-12 13:00:02 -07001966 ks.onUserRemoved(userId);
Andres Morales070fe632015-06-24 10:37:10 -07001967
1968 try {
1969 final IGateKeeperService gk = getGateKeeperService();
1970 if (gk != null) {
Rubin Xu1de89b32016-11-30 20:03:13 +00001971 gk.clearSecureUserId(userId);
Andres Morales070fe632015-06-24 10:37:10 -07001972 }
1973 } catch (RemoteException ex) {
1974 Slog.w(TAG, "unable to clear GK secure user id");
1975 }
Irina Dumitrescue83f512552019-02-22 18:05:32 +00001976 UserInfo userInfo = mUserManager.getUserInfo(userId);
1977 if (unknownUser || userInfo == null || userInfo.isManagedProfile()) {
Ricky Waidc283a82016-03-24 19:55:08 +00001978 removeKeystoreProfileKey(userId);
1979 }
1980 }
1981
1982 private void removeKeystoreProfileKey(int targetUserId) {
1983 if (DEBUG) Slog.v(TAG, "Remove keystore profile key for user: " + targetUserId);
1984 try {
1985 java.security.KeyStore keyStore = java.security.KeyStore.getInstance("AndroidKeyStore");
1986 keyStore.load(null);
Ricky Waid3982442016-05-24 19:27:08 +01001987 keyStore.deleteEntry(LockPatternUtils.PROFILE_KEY_NAME_ENCRYPT + targetUserId);
1988 keyStore.deleteEntry(LockPatternUtils.PROFILE_KEY_NAME_DECRYPT + targetUserId);
Ricky Waidc283a82016-03-24 19:55:08 +00001989 } catch (KeyStoreException | NoSuchAlgorithmException | CertificateException
1990 | IOException e) {
1991 // We have tried our best to remove all keys
1992 Slog.e(TAG, "Unable to remove keystore profile key for user:" + targetUserId, e);
1993 }
Amith Yamasani52c489c2012-03-28 11:42:42 -07001994 }
1995
Adrian Roosb5e47222015-08-14 15:53:06 -07001996 @Override
1997 public void registerStrongAuthTracker(IStrongAuthTracker tracker) {
1998 checkPasswordReadPermission(UserHandle.USER_ALL);
1999 mStrongAuth.registerStrongAuthTracker(tracker);
2000 }
2001
2002 @Override
2003 public void unregisterStrongAuthTracker(IStrongAuthTracker tracker) {
2004 checkPasswordReadPermission(UserHandle.USER_ALL);
2005 mStrongAuth.unregisterStrongAuthTracker(tracker);
2006 }
2007
2008 @Override
2009 public void requireStrongAuth(int strongAuthReason, int userId) {
2010 checkWritePermission(userId);
2011 mStrongAuth.requireStrongAuth(strongAuthReason, userId);
2012 }
2013
Adrian Roos4ab7e592016-04-13 15:38:13 -07002014 @Override
2015 public void userPresent(int userId) {
2016 checkWritePermission(userId);
2017 mStrongAuth.reportUnlock(userId);
2018 }
2019
Victor Changa0940d32016-05-16 19:36:08 +01002020 @Override
2021 public int getStrongAuthForUser(int userId) {
2022 checkPasswordReadPermission(userId);
2023 return mStrongAuthTracker.getStrongAuthForUser(userId);
2024 }
2025
Jorim Jaggi2fef6f72016-11-01 19:06:25 -07002026 private boolean isCallerShell() {
2027 final int callingUid = Binder.getCallingUid();
2028 return callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID;
2029 }
2030
2031 private void enforceShell() {
2032 if (!isCallerShell()) {
2033 throw new SecurityException("Caller must be shell");
2034 }
2035 }
2036
2037 @Override
2038 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
2039 String[] args, ShellCallback callback, ResultReceiver resultReceiver)
2040 throws RemoteException {
2041 enforceShell();
2042 final long origId = Binder.clearCallingIdentity();
2043 try {
Felipe Leme1fc9c812018-07-11 10:02:23 -07002044 (new LockSettingsShellCommand(new LockPatternUtils(mContext))).exec(
Jorim Jaggi2fef6f72016-11-01 19:06:25 -07002045 this, in, out, err, args, callback, resultReceiver);
2046 } finally {
2047 Binder.restoreCallingIdentity(origId);
2048 }
2049 }
2050
Dmitry Dementyev1aa96132017-12-11 11:33:12 -08002051 @Override
Bo Zhu7f414d92018-02-28 09:28:19 -08002052 public void initRecoveryServiceWithSigFile(@NonNull String rootCertificateAlias,
2053 @NonNull byte[] recoveryServiceCertFile, @NonNull byte[] recoveryServiceSigFile)
2054 throws RemoteException {
2055 mRecoverableKeyStoreManager.initRecoveryServiceWithSigFile(rootCertificateAlias,
2056 recoveryServiceCertFile, recoveryServiceSigFile);
2057 }
2058
2059 @Override
Dmitry Dementyev4da14e02018-03-23 15:18:33 -07002060 public @NonNull KeyChainSnapshot getKeyChainSnapshot() throws RemoteException {
Dmitry Dementyevb4fb9872018-01-26 11:49:34 -08002061 return mRecoverableKeyStoreManager.getKeyChainSnapshot();
Dmitry Dementyev1aa96132017-12-11 11:33:12 -08002062 }
2063
Dmitry Dementyev4da14e02018-03-23 15:18:33 -07002064 @Override
Dmitry Dementyev14298312018-01-04 15:19:19 -08002065 public void setSnapshotCreatedPendingIntent(@Nullable PendingIntent intent)
Dmitry Dementyevb8b030b2017-12-19 11:02:54 -08002066 throws RemoteException {
Dmitry Dementyev14298312018-01-04 15:19:19 -08002067 mRecoverableKeyStoreManager.setSnapshotCreatedPendingIntent(intent);
Dmitry Dementyevb8b030b2017-12-19 11:02:54 -08002068 }
2069
Dmitry Dementyev1aa96132017-12-11 11:33:12 -08002070 @Override
Dmitry Dementyev7d8c78a2018-01-12 19:14:07 -08002071 public void setServerParams(byte[] serverParams) throws RemoteException {
2072 mRecoverableKeyStoreManager.setServerParams(serverParams);
Dmitry Dementyev1aa96132017-12-11 11:33:12 -08002073 }
2074
2075 @Override
Robert Berrybbe02ae2018-02-20 19:47:43 +00002076 public void setRecoveryStatus(String alias, int status) throws RemoteException {
2077 mRecoverableKeyStoreManager.setRecoveryStatus(alias, status);
Dmitry Dementyev1aa96132017-12-11 11:33:12 -08002078 }
2079
Dmitry Dementyev4da14e02018-03-23 15:18:33 -07002080 @Override
2081 public @NonNull Map getRecoveryStatus() throws RemoteException {
Robert Berry56f06b42018-02-23 13:31:32 +00002082 return mRecoverableKeyStoreManager.getRecoveryStatus();
Dmitry Dementyevb8b030b2017-12-19 11:02:54 -08002083 }
2084
Dmitry Dementyev1aa96132017-12-11 11:33:12 -08002085 @Override
Dmitry Dementyev0916e7c2018-01-23 13:02:08 -08002086 public void setRecoverySecretTypes(@NonNull @KeyChainProtectionParams.UserSecretType
Dmitry Dementyev14298312018-01-04 15:19:19 -08002087 int[] secretTypes) throws RemoteException {
2088 mRecoverableKeyStoreManager.setRecoverySecretTypes(secretTypes);
Dmitry Dementyev1aa96132017-12-11 11:33:12 -08002089 }
2090
2091 @Override
Dmitry Dementyev4da14e02018-03-23 15:18:33 -07002092 public @NonNull int[] getRecoverySecretTypes() throws RemoteException {
Dmitry Dementyev14298312018-01-04 15:19:19 -08002093 return mRecoverableKeyStoreManager.getRecoverySecretTypes();
Dmitry Dementyev1aa96132017-12-11 11:33:12 -08002094
2095 }
2096
2097 @Override
Dmitry Dementyev4da14e02018-03-23 15:18:33 -07002098 public @NonNull byte[] startRecoverySessionWithCertPath(@NonNull String sessionId,
Bo Zhub31ab672018-03-20 22:44:18 -07002099 @NonNull String rootCertificateAlias, @NonNull RecoveryCertPath verifierCertPath,
2100 @NonNull byte[] vaultParams, @NonNull byte[] vaultChallenge,
2101 @NonNull List<KeyChainProtectionParams> secrets)
Bo Zhu7c1972f2018-02-22 21:43:52 -08002102 throws RemoteException {
2103 return mRecoverableKeyStoreManager.startRecoverySessionWithCertPath(
Bo Zhub31ab672018-03-20 22:44:18 -07002104 sessionId, rootCertificateAlias, verifierCertPath, vaultParams, vaultChallenge,
2105 secrets);
Bo Zhu7c1972f2018-02-22 21:43:52 -08002106 }
2107
Dmitry Dementyev4da14e02018-03-23 15:18:33 -07002108 @Override
Robert Berry4a5c87d2018-03-19 18:00:46 +00002109 public Map<String, String> recoverKeyChainSnapshot(
2110 @NonNull String sessionId,
2111 @NonNull byte[] recoveryKeyBlob,
2112 @NonNull List<WrappedApplicationKey> applicationKeys) throws RemoteException {
2113 return mRecoverableKeyStoreManager.recoverKeyChainSnapshot(
2114 sessionId, recoveryKeyBlob, applicationKeys);
2115 }
2116
2117 @Override
Dmitry Dementyev745d2c92018-04-13 14:10:05 -07002118 public void closeSession(@NonNull String sessionId) throws RemoteException {
2119 mRecoverableKeyStoreManager.closeSession(sessionId);
Dmitry Dementyev1aa96132017-12-11 11:33:12 -08002120 }
2121
Robert Berrycfc990a2017-12-22 15:54:30 +00002122 @Override
Robert Berry5daccec2018-01-06 19:16:25 +00002123 public void removeKey(@NonNull String alias) throws RemoteException {
2124 mRecoverableKeyStoreManager.removeKey(alias);
2125 }
2126
2127 @Override
Dmitry Dementyev4da14e02018-03-23 15:18:33 -07002128 public @Nullable String generateKey(@NonNull String alias) throws RemoteException {
Robert Berrya3b99472018-02-23 15:59:02 +00002129 return mRecoverableKeyStoreManager.generateKey(alias);
Dmitry Dementyev29b9de52018-01-31 16:09:32 -08002130 }
2131
2132 @Override
Bo Zhuc7048342019-01-03 14:04:58 -08002133 public @Nullable String generateKeyWithMetadata(
2134 @NonNull String alias, @Nullable byte[] metadata) throws RemoteException {
2135 return mRecoverableKeyStoreManager.generateKeyWithMetadata(alias, metadata);
2136 }
2137
2138 @Override
2139 public @Nullable String importKey(@NonNull String alias, @NonNull byte[] keyBytes)
2140 throws RemoteException {
Bo Zhu2c8e5382018-02-26 15:54:25 -08002141 return mRecoverableKeyStoreManager.importKey(alias, keyBytes);
2142 }
2143
2144 @Override
Bo Zhuc7048342019-01-03 14:04:58 -08002145 public @Nullable String importKeyWithMetadata(@NonNull String alias, @NonNull byte[] keyBytes,
2146 @Nullable byte[] metadata) throws RemoteException {
2147 return mRecoverableKeyStoreManager.importKeyWithMetadata(alias, keyBytes, metadata);
2148 }
2149
2150 @Override
Dmitry Dementyev4da14e02018-03-23 15:18:33 -07002151 public @Nullable String getKey(@NonNull String alias) throws RemoteException {
Dmitry Dementyev29b9de52018-01-31 16:09:32 -08002152 return mRecoverableKeyStoreManager.getKey(alias);
2153 }
2154
Amith Yamasani52c489c2012-03-28 11:42:42 -07002155 private static final String[] VALID_SETTINGS = new String[] {
Rubin Xu1de89b32016-11-30 20:03:13 +00002156 LockPatternUtils.LOCKOUT_PERMANENT_KEY,
Rubin Xu1de89b32016-11-30 20:03:13 +00002157 LockPatternUtils.PATTERN_EVER_CHOSEN_KEY,
2158 LockPatternUtils.PASSWORD_TYPE_KEY,
2159 LockPatternUtils.PASSWORD_TYPE_ALTERNATE_KEY,
2160 LockPatternUtils.LOCK_PASSWORD_SALT_KEY,
2161 LockPatternUtils.DISABLE_LOCKSCREEN_KEY,
2162 LockPatternUtils.LOCKSCREEN_OPTIONS,
2163 LockPatternUtils.LOCKSCREEN_BIOMETRIC_WEAK_FALLBACK,
2164 LockPatternUtils.BIOMETRIC_WEAK_EVER_CHOSEN_KEY,
2165 LockPatternUtils.LOCKSCREEN_POWER_BUTTON_INSTANTLY_LOCKS,
2166 LockPatternUtils.PASSWORD_HISTORY_KEY,
2167 Secure.LOCK_PATTERN_ENABLED,
2168 Secure.LOCK_BIOMETRIC_WEAK_FLAGS,
2169 Secure.LOCK_PATTERN_VISIBLE,
2170 Secure.LOCK_PATTERN_TACTILE_FEEDBACK_ENABLED
Jim Miller187ec582013-04-15 18:27:54 -07002171 };
2172
Svetoslav Ganov6d2c0e52015-06-23 16:33:36 +00002173 // Reading these settings needs the contacts permission
2174 private static final String[] READ_CONTACTS_PROTECTED_SETTINGS = new String[] {
Rubin Xu1de89b32016-11-30 20:03:13 +00002175 Secure.LOCK_SCREEN_OWNER_INFO_ENABLED,
2176 Secure.LOCK_SCREEN_OWNER_INFO
Jim Miller187ec582013-04-15 18:27:54 -07002177 };
Paul Lawrence945490c2014-03-27 16:37:28 +00002178
Adrian Roos001b00d2015-02-24 17:08:48 +01002179 // Reading these settings needs the same permission as checking the password
2180 private static final String[] READ_PASSWORD_PROTECTED_SETTINGS = new String[] {
2181 LockPatternUtils.LOCK_PASSWORD_SALT_KEY,
2182 LockPatternUtils.PASSWORD_HISTORY_KEY,
Adrian Roos855fa302015-04-02 16:01:12 +02002183 LockPatternUtils.PASSWORD_TYPE_KEY,
Ricky Wai7f405f12016-05-31 12:05:05 +01002184 SEPARATE_PROFILE_CHALLENGE_KEY
Adrian Roos001b00d2015-02-24 17:08:48 +01002185 };
2186
Amith Yamasani072543f2015-02-13 11:09:45 -08002187 private static final String[] SETTINGS_TO_BACKUP = new String[] {
Rubin Xu1de89b32016-11-30 20:03:13 +00002188 Secure.LOCK_SCREEN_OWNER_INFO_ENABLED,
Bryan Mawhinneye483b562017-05-15 14:46:05 +01002189 Secure.LOCK_SCREEN_OWNER_INFO,
2190 Secure.LOCK_PATTERN_VISIBLE,
2191 LockPatternUtils.LOCKSCREEN_POWER_BUTTON_INSTANTLY_LOCKS
Amith Yamasani072543f2015-02-13 11:09:45 -08002192 };
2193
Andres Morales301ea442015-04-17 09:15:47 -07002194 private class GateKeeperDiedRecipient implements IBinder.DeathRecipient {
2195 @Override
2196 public void binderDied() {
2197 mGateKeeperService.asBinder().unlinkToDeath(this, 0);
2198 mGateKeeperService = null;
2199 }
2200 }
2201
Rubin Xu3bf722a2016-12-15 16:07:38 +00002202 protected synchronized IGateKeeperService getGateKeeperService()
Andres Morales301ea442015-04-17 09:15:47 -07002203 throws RemoteException {
Andres Morales8fa56652015-03-31 09:19:50 -07002204 if (mGateKeeperService != null) {
2205 return mGateKeeperService;
2206 }
2207
Rubin Xu1de89b32016-11-30 20:03:13 +00002208 final IBinder service = ServiceManager.getService(Context.GATEKEEPER_SERVICE);
Andres Morales8fa56652015-03-31 09:19:50 -07002209 if (service != null) {
Andres Morales301ea442015-04-17 09:15:47 -07002210 service.linkToDeath(new GateKeeperDiedRecipient(), 0);
Andres Morales8fa56652015-03-31 09:19:50 -07002211 mGateKeeperService = IGateKeeperService.Stub.asInterface(service);
2212 return mGateKeeperService;
2213 }
2214
2215 Slog.e(TAG, "Unable to acquire GateKeeperService");
2216 return null;
2217 }
Rubin Xu3bf722a2016-12-15 16:07:38 +00002218
2219 /**
Andrew Scull1416bd02018-01-05 18:33:58 +00002220 * A user's synthetic password does not change so it must be cached in certain circumstances to
2221 * enable untrusted credential reset.
2222 *
2223 * Untrusted credential reset will be removed in a future version (b/68036371) at which point
2224 * this cache is no longer needed as the SP will always be known when changing the user's
2225 * credential.
2226 */
2227 @GuardedBy("mSpManager")
2228 private SparseArray<AuthenticationToken> mSpCache = new SparseArray();
2229
2230 private void onAuthTokenKnownForUser(@UserIdInt int userId, AuthenticationToken auth) {
Andrew Scullede482d2018-01-30 13:54:29 +00002231 // Preemptively cache the SP and then try to remove it in a handler.
2232 Slog.i(TAG, "Caching SP for user " + userId);
2233 synchronized (mSpManager) {
2234 mSpCache.put(userId, auth);
2235 }
2236 tryRemoveUserFromSpCacheLater(userId);
2237
David Anderson6ebc25b2019-02-12 16:25:56 -08002238 if (mInjector.isGsiRunning()) {
2239 Slog.w(TAG, "AuthSecret disabled in GSI");
2240 return;
2241 }
2242
Andrew Sculle6527c12018-01-05 18:33:58 +00002243 // Pass the primary user's auth secret to the HAL
2244 if (mAuthSecretService != null && mUserManager.getUserInfo(userId).isPrimary()) {
2245 try {
2246 final byte[] rawSecret = auth.deriveVendorAuthSecret();
2247 final ArrayList<Byte> secret = new ArrayList<>(rawSecret.length);
2248 for (int i = 0; i < rawSecret.length; ++i) {
2249 secret.add(rawSecret[i]);
2250 }
2251 mAuthSecretService.primaryUserCredential(secret);
2252 } catch (RemoteException e) {
2253 Slog.w(TAG, "Failed to pass primary user secret to AuthSecret HAL", e);
2254 }
2255 }
Andrew Scull1416bd02018-01-05 18:33:58 +00002256 }
2257
Andrew Scullede482d2018-01-30 13:54:29 +00002258 private void tryRemoveUserFromSpCacheLater(@UserIdInt int userId) {
2259 mHandler.post(() -> {
2260 if (!shouldCacheSpForUser(userId)) {
2261 // The transition from 'should not cache' to 'should cache' can only happen if
2262 // certain admin apps are installed after provisioning e.g. via adb. This is not
2263 // a common case and we do not seamlessly support; it may result in the SP not
2264 // being cached when it is needed. The cache can be re-populated by verifying
2265 // the credential again.
2266 Slog.i(TAG, "Removing SP from cache for user " + userId);
2267 synchronized (mSpManager) {
2268 mSpCache.remove(userId);
Andrew Scull1416bd02018-01-05 18:33:58 +00002269 }
2270 }
Andrew Scullede482d2018-01-30 13:54:29 +00002271 });
Andrew Scull1416bd02018-01-05 18:33:58 +00002272 }
2273
Andrew Scullede482d2018-01-30 13:54:29 +00002274 /** Do not hold any of the locks from this service when calling. */
Andrew Scull1416bd02018-01-05 18:33:58 +00002275 private boolean shouldCacheSpForUser(@UserIdInt int userId) {
2276 // Before the user setup has completed, an admin could be installed that requires the SP to
2277 // be cached (see below).
2278 if (Settings.Secure.getIntForUser(mContext.getContentResolver(),
2279 Settings.Secure.USER_SETUP_COMPLETE, 0, userId) == 0) {
2280 return true;
2281 }
2282
2283 // If the user has an admin which can perform an untrusted credential reset, the SP needs to
2284 // be cached. If there isn't a DevicePolicyManager then there can't be an admin in the first
2285 // place so caching is not necessary.
2286 final DevicePolicyManagerInternal dpmi = LocalServices.getService(
2287 DevicePolicyManagerInternal.class);
2288 if (dpmi == null) {
2289 return false;
2290 }
2291 return dpmi.canUserHaveUntrustedCredentialReset(userId);
2292 }
2293
2294 /**
Rubin Xu3bf722a2016-12-15 16:07:38 +00002295 * Precondition: vold and keystore unlocked.
2296 *
2297 * Create new synthetic password, set up synthetic password blob protected by the supplied
2298 * user credential, and make the newly-created SP blob active.
2299 *
2300 * The invariant under a synthetic password is:
2301 * 1. If user credential exists, then both vold and keystore and protected with keys derived
2302 * from the synthetic password.
2303 * 2. If user credential does not exist, vold and keystore protection are cleared. This is to
2304 * make it consistent with current behaviour. It also allows ActivityManager to call
2305 * unlockUser() with empty secret.
2306 * 3. Once a user is migrated to have synthetic password, its value will never change, no matter
2307 * whether the user changes his lockscreen PIN or clear/reset it. When the user clears its
2308 * lockscreen PIN, we still maintain the existing synthetic password in a password blob
Andrew Scull1416bd02018-01-05 18:33:58 +00002309 * protected by a default PIN.
Rubin Xu3bf722a2016-12-15 16:07:38 +00002310 * 4. The user SID is linked with synthetic password, but its cleared/re-created when the user
2311 * clears/re-creates his lockscreen PIN.
2312 *
2313 *
2314 * Different cases of calling this method:
2315 * 1. credentialHash != null
2316 * This implies credential != null, a new SP blob will be provisioned, and existing SID
2317 * migrated to associate with the new SP.
2318 * This happens during a normal migration case when the user currently has password.
2319 *
2320 * 2. credentialhash == null and credential == null
Rubin Xu9a6d39a52018-02-07 08:52:34 +00002321 * A new SP blob and will be created, while the user has no credentials.
Rubin Xu3bf722a2016-12-15 16:07:38 +00002322 * This can happens when we are activating an escrow token on a unsecured device, during
2323 * which we want to create the SP structure with an empty user credential.
Rubin Xu9a6d39a52018-02-07 08:52:34 +00002324 * This could also happen during an untrusted reset to clear password.
Rubin Xu3bf722a2016-12-15 16:07:38 +00002325 *
2326 * 3. credentialhash == null and credential != null
2327 * This is the untrusted credential reset, OR the user sets a new lockscreen password
2328 * FOR THE FIRST TIME on a SP-enabled device. New credential and new SID will be created
2329 */
Andrew Scull1416bd02018-01-05 18:33:58 +00002330 @GuardedBy("mSpManager")
Rubin Xu16c823e2017-06-27 14:44:58 +01002331 @VisibleForTesting
2332 protected AuthenticationToken initializeSyntheticPasswordLocked(byte[] credentialHash,
Rich Canningsf64ec632019-02-21 12:40:36 -08002333 byte[] credential, int credentialType, int requestedQuality,
Adrian Roos7374d3a2017-03-31 14:14:53 -07002334 int userId) throws RemoteException {
Rubin Xu3bf722a2016-12-15 16:07:38 +00002335 Slog.i(TAG, "Initialize SyntheticPassword for user: " + userId);
Rubin Xu9a6d39a52018-02-07 08:52:34 +00002336 final AuthenticationToken auth = mSpManager.newSyntheticPasswordAndSid(
2337 getGateKeeperService(), credentialHash, credential, userId);
Andrew Scull1416bd02018-01-05 18:33:58 +00002338 onAuthTokenKnownForUser(userId, auth);
Rubin Xu3bf722a2016-12-15 16:07:38 +00002339 if (auth == null) {
2340 Slog.wtf(TAG, "initializeSyntheticPasswordLocked returns null auth token");
2341 return null;
2342 }
2343 long handle = mSpManager.createPasswordBasedSyntheticPassword(getGateKeeperService(),
Adrian Roos7374d3a2017-03-31 14:14:53 -07002344 credential, credentialType, auth, requestedQuality, userId);
Rubin Xu3bf722a2016-12-15 16:07:38 +00002345 if (credential != null) {
2346 if (credentialHash == null) {
2347 // Since when initializing SP, we didn't provide an existing password handle
2348 // for it to migrate SID, we need to create a new SID for the user.
2349 mSpManager.newSidForUser(getGateKeeperService(), auth, userId);
2350 }
2351 mSpManager.verifyChallenge(getGateKeeperService(), auth, 0L, userId);
2352 setAuthlessUserKeyProtection(userId, auth.deriveDiskEncryptionKey());
2353 setKeystorePassword(auth.deriveKeyStorePassword(), userId);
2354 } else {
2355 clearUserKeyProtection(userId);
2356 setKeystorePassword(null, userId);
2357 getGateKeeperService().clearSecureUserId(userId);
2358 }
2359 fixateNewestUserKeyAuth(userId);
2360 setLong(SYNTHETIC_PASSWORD_HANDLE_KEY, handle, userId);
2361 return auth;
2362 }
2363
2364 private long getSyntheticPasswordHandleLocked(int userId) {
Adrian Roos60dcbbf2017-08-08 16:19:33 +02002365 return getLong(SYNTHETIC_PASSWORD_HANDLE_KEY,
2366 SyntheticPasswordManager.DEFAULT_HANDLE, userId);
Rubin Xu3bf722a2016-12-15 16:07:38 +00002367 }
2368
Rubin Xufcd49f92017-08-24 18:21:52 +01002369 private boolean isSyntheticPasswordBasedCredentialLocked(int userId) {
Adrian Roos7374d3a2017-03-31 14:14:53 -07002370 if (userId == USER_FRP) {
2371 final int type = mStorage.readPersistentDataBlock().type;
2372 return type == PersistentData.TYPE_SP || type == PersistentData.TYPE_SP_WEAVER;
2373 }
Rubin Xu3bf722a2016-12-15 16:07:38 +00002374 long handle = getSyntheticPasswordHandleLocked(userId);
2375 // This is a global setting
Paul Crowley7a0cc0a2017-05-31 22:12:57 +00002376 long enabled = getLong(SYNTHETIC_PASSWORD_ENABLED_KEY,
2377 SYNTHETIC_PASSWORD_ENABLED_BY_DEFAULT, UserHandle.USER_SYSTEM);
Rubin Xu3bf722a2016-12-15 16:07:38 +00002378 return enabled != 0 && handle != SyntheticPasswordManager.DEFAULT_HANDLE;
2379 }
2380
Rubin Xu16c823e2017-06-27 14:44:58 +01002381 @VisibleForTesting
Rubin Xufcd49f92017-08-24 18:21:52 +01002382 protected boolean shouldMigrateToSyntheticPasswordLocked(int userId) {
Rubin Xu3bf722a2016-12-15 16:07:38 +00002383 long handle = getSyntheticPasswordHandleLocked(userId);
2384 // This is a global setting
Paul Crowley7a0cc0a2017-05-31 22:12:57 +00002385 long enabled = getLong(SYNTHETIC_PASSWORD_ENABLED_KEY,
2386 SYNTHETIC_PASSWORD_ENABLED_BY_DEFAULT, UserHandle.USER_SYSTEM);
Rubin Xu3bf722a2016-12-15 16:07:38 +00002387 return enabled != 0 && handle == SyntheticPasswordManager.DEFAULT_HANDLE;
2388 }
2389
Rubin Xufcd49f92017-08-24 18:21:52 +01002390 private void enableSyntheticPasswordLocked() {
Rubin Xu3bf722a2016-12-15 16:07:38 +00002391 setLong(SYNTHETIC_PASSWORD_ENABLED_KEY, 1, UserHandle.USER_SYSTEM);
2392 }
2393
Rich Canningsf64ec632019-02-21 12:40:36 -08002394 private VerifyCredentialResponse spBasedDoVerifyCredential(byte[] userCredential, int
Rubin Xu3bf722a2016-12-15 16:07:38 +00002395 credentialType, boolean hasChallenge, long challenge, int userId,
2396 ICheckCredentialProgressCallback progressCallback) throws RemoteException {
Rubin Xue94a7702017-06-20 17:29:57 +01002397 if (DEBUG) Slog.d(TAG, "spBasedDoVerifyCredential: user=" + userId);
Rubin Xu3bf722a2016-12-15 16:07:38 +00002398 if (credentialType == LockPatternUtils.CREDENTIAL_TYPE_NONE) {
2399 userCredential = null;
2400 }
Rubin Xue94a7702017-06-20 17:29:57 +01002401
Kevin Chyna38653c2019-02-11 17:46:21 -08002402 final PackageManager pm = mContext.getPackageManager();
2403 // TODO: When lockout is handled under the HAL for all biometrics (fingerprint),
2404 // we need to generate challenge for each one, have it signed by GK and reset lockout
2405 // for each modality.
2406 if (!hasChallenge && pm.hasSystemFeature(PackageManager.FEATURE_FACE)) {
2407 challenge = mContext.getSystemService(FaceManager.class).generateChallenge();
2408 }
2409
Rubin Xue94a7702017-06-20 17:29:57 +01002410 final AuthenticationResult authResult;
2411 VerifyCredentialResponse response;
2412 synchronized (mSpManager) {
2413 if (!isSyntheticPasswordBasedCredentialLocked(userId)) {
2414 return null;
2415 }
2416 if (userId == USER_FRP) {
2417 return mSpManager.verifyFrpCredential(getGateKeeperService(),
2418 userCredential, credentialType, progressCallback);
2419 }
2420
2421 long handle = getSyntheticPasswordHandleLocked(userId);
2422 authResult = mSpManager.unwrapPasswordBasedSyntheticPassword(
Rubin Xucf326f12017-11-15 11:55:35 +00002423 getGateKeeperService(), handle, userCredential, userId, progressCallback);
Rubin Xue94a7702017-06-20 17:29:57 +01002424
Rubin Xu16c823e2017-06-27 14:44:58 +01002425 if (authResult.credentialType != credentialType) {
2426 Slog.e(TAG, "Credential type mismatch.");
2427 return VerifyCredentialResponse.ERROR;
2428 }
Rubin Xue94a7702017-06-20 17:29:57 +01002429 response = authResult.gkResponse;
2430 // credential has matched
2431 if (response.getResponseCode() == VerifyCredentialResponse.RESPONSE_OK) {
2432 // perform verifyChallenge with synthetic password which generates the real GK auth
2433 // token and response for the current user
2434 response = mSpManager.verifyChallenge(getGateKeeperService(), authResult.authToken,
2435 challenge, userId);
2436 if (response.getResponseCode() != VerifyCredentialResponse.RESPONSE_OK) {
2437 // This shouldn't really happen: the unwrapping of SP succeeds, but SP doesn't
2438 // match the recorded GK password handle.
2439 Slog.wtf(TAG, "verifyChallenge with SP failed.");
2440 return VerifyCredentialResponse.ERROR;
2441 }
2442 }
Adrian Roos7374d3a2017-03-31 14:14:53 -07002443 }
2444
Rubin Xu3bf722a2016-12-15 16:07:38 +00002445 if (response.getResponseCode() == VerifyCredentialResponse.RESPONSE_OK) {
Rubin Xu3bf722a2016-12-15 16:07:38 +00002446 notifyActivePasswordMetricsAvailable(userCredential, userId);
2447 unlockKeystore(authResult.authToken.deriveKeyStorePassword(), userId);
Kevin Chyna38653c2019-02-11 17:46:21 -08002448 // Reset lockout
Kevin Chyncf1a62e2019-02-21 11:11:59 -08002449 if (mInjector.hasBiometrics()) {
Kevin Chyna38653c2019-02-11 17:46:21 -08002450 BiometricManager bm = mContext.getSystemService(BiometricManager.class);
2451 Slog.i(TAG, "Resetting lockout, length: "
2452 + authResult.gkResponse.getPayload().length);
2453 bm.resetLockout(authResult.gkResponse.getPayload());
2454
2455 if (!hasChallenge && pm.hasSystemFeature(PackageManager.FEATURE_FACE)) {
2456 mContext.getSystemService(FaceManager.class).revokeChallenge();
2457 }
2458 }
Rubin Xu3bf722a2016-12-15 16:07:38 +00002459
2460 final byte[] secret = authResult.authToken.deriveDiskEncryptionKey();
2461 Slog.i(TAG, "Unlocking user " + userId + " with secret only, length " + secret.length);
2462 unlockUser(userId, null, secret);
2463
Rubin Xue94a7702017-06-20 17:29:57 +01002464 activateEscrowTokens(authResult.authToken, userId);
2465
Rubin Xu3bf722a2016-12-15 16:07:38 +00002466 if (isManagedProfileWithSeparatedLock(userId)) {
2467 TrustManager trustManager =
2468 (TrustManager) mContext.getSystemService(Context.TRUST_SERVICE);
2469 trustManager.setDeviceLockedForUser(userId, false);
2470 }
Rubin Xue94a7702017-06-20 17:29:57 +01002471 mStrongAuth.reportSuccessfulStrongAuthUnlock(userId);
Andrew Scull1416bd02018-01-05 18:33:58 +00002472
2473 onAuthTokenKnownForUser(userId, authResult.authToken);
Rubin Xu3bf722a2016-12-15 16:07:38 +00002474 } else if (response.getResponseCode() == VerifyCredentialResponse.RESPONSE_RETRY) {
2475 if (response.getTimeout() > 0) {
2476 requireStrongAuth(STRONG_AUTH_REQUIRED_AFTER_LOCKOUT, userId);
2477 }
2478 }
2479
2480 return response;
2481 }
2482
2483 /**
2484 * Change the user's lockscreen password by creating a new SP blob and update the handle, based
2485 * on an existing authentication token. Even though a new SP blob is created, the underlying
2486 * synthetic password is never changed.
2487 *
2488 * When clearing credential, we keep the SP unchanged, but clear its password handle so its
2489 * SID is gone. We also clear password from (software-based) keystore and vold, which will be
2490 * added back when new password is set in future.
2491 */
Andrew Scull1416bd02018-01-05 18:33:58 +00002492 @GuardedBy("mSpManager")
Rich Canningsf64ec632019-02-21 12:40:36 -08002493 private long setLockCredentialWithAuthTokenLocked(byte[] credential, int credentialType,
Adrian Roos7374d3a2017-03-31 14:14:53 -07002494 AuthenticationToken auth, int requestedQuality, int userId) throws RemoteException {
Rubin Xu3bf722a2016-12-15 16:07:38 +00002495 if (DEBUG) Slog.d(TAG, "setLockCredentialWithAuthTokenLocked: user=" + userId);
2496 long newHandle = mSpManager.createPasswordBasedSyntheticPassword(getGateKeeperService(),
Adrian Roos7374d3a2017-03-31 14:14:53 -07002497 credential, credentialType, auth, requestedQuality, userId);
Rich Canningsf64ec632019-02-21 12:40:36 -08002498 final Map<Integer, byte[]> profilePasswords;
Rubin Xu3bf722a2016-12-15 16:07:38 +00002499 if (credential != null) {
2500 // // not needed by synchronizeUnifiedWorkChallengeForProfiles()
2501 profilePasswords = null;
2502
2503 if (mSpManager.hasSidForUser(userId)) {
2504 // We are changing password of a secured device, nothing more needed as
2505 // createPasswordBasedSyntheticPassword has already taken care of maintaining
2506 // the password handle and SID unchanged.
2507
2508 //refresh auth token
2509 mSpManager.verifyChallenge(getGateKeeperService(), auth, 0L, userId);
2510 } else {
2511 // A new password is set on a previously-unsecured device, we need to generate
2512 // a new SID, and re-add keys to vold and keystore.
2513 mSpManager.newSidForUser(getGateKeeperService(), auth, userId);
2514 mSpManager.verifyChallenge(getGateKeeperService(), auth, 0L, userId);
2515 setAuthlessUserKeyProtection(userId, auth.deriveDiskEncryptionKey());
2516 fixateNewestUserKeyAuth(userId);
2517 setKeystorePassword(auth.deriveKeyStorePassword(), userId);
2518 }
2519 } else {
2520 // Cache all profile password if they use unified work challenge. This will later be
2521 // used to clear the profile's password in synchronizeUnifiedWorkChallengeForProfiles()
2522 profilePasswords = getDecryptedPasswordsForAllTiedProfiles(userId);
2523
2524 // we are clearing password of a secured device, so need to nuke SID as well.
2525 mSpManager.clearSidForUser(userId);
2526 getGateKeeperService().clearSecureUserId(userId);
2527 // Clear key from vold so ActivityManager can just unlock the user with empty secret
2528 // during boot.
2529 clearUserKeyProtection(userId);
2530 fixateNewestUserKeyAuth(userId);
2531 setKeystorePassword(null, userId);
2532 }
2533 setLong(SYNTHETIC_PASSWORD_HANDLE_KEY, newHandle, userId);
2534 synchronizeUnifiedWorkChallengeForProfiles(userId, profilePasswords);
Rubin Xu7cf45092017-08-28 11:47:35 +01002535
2536 notifyActivePasswordMetricsAvailable(credential, userId);
Rich Canningsf64ec632019-02-21 12:40:36 -08002537
2538 if (profilePasswords != null) {
2539 for (Map.Entry<Integer, byte[]> entry : profilePasswords.entrySet()) {
2540 Arrays.fill(entry.getValue(), (byte) 0);
2541 }
2542 }
2543
Rubin Xu3bf722a2016-12-15 16:07:38 +00002544 return newHandle;
2545 }
2546
Andrew Scull1416bd02018-01-05 18:33:58 +00002547 @GuardedBy("mSpManager")
Rich Canningsf64ec632019-02-21 12:40:36 -08002548 private void spBasedSetLockCredentialInternalLocked(byte[] credential, int credentialType,
2549 byte[] savedCredential, int requestedQuality, int userId) throws RemoteException {
Rubin Xu3bf722a2016-12-15 16:07:38 +00002550 if (DEBUG) Slog.d(TAG, "spBasedSetLockCredentialInternalLocked: user=" + userId);
2551 if (isManagedProfileWithUnifiedLock(userId)) {
2552 // get credential from keystore when managed profile has unified lock
2553 try {
2554 savedCredential = getDecryptedPasswordForTiedProfile(userId);
2555 } catch (FileNotFoundException e) {
2556 Slog.i(TAG, "Child profile key not found");
2557 } catch (UnrecoverableKeyException | InvalidKeyException | KeyStoreException
2558 | NoSuchAlgorithmException | NoSuchPaddingException
2559 | InvalidAlgorithmParameterException | IllegalBlockSizeException
2560 | BadPaddingException | CertificateException | IOException e) {
2561 Slog.e(TAG, "Failed to decrypt child profile key", e);
2562 }
2563 }
2564 long handle = getSyntheticPasswordHandleLocked(userId);
Rubin Xu8b30ec32017-03-05 00:47:09 +00002565 AuthenticationResult authResult = mSpManager.unwrapPasswordBasedSyntheticPassword(
Rubin Xucf326f12017-11-15 11:55:35 +00002566 getGateKeeperService(), handle, savedCredential, userId, null);
Rubin Xu8b30ec32017-03-05 00:47:09 +00002567 VerifyCredentialResponse response = authResult.gkResponse;
2568 AuthenticationToken auth = authResult.authToken;
Rubin Xu16c823e2017-06-27 14:44:58 +01002569
2570 // If existing credential is provided, then it must match.
2571 if (savedCredential != null && auth == null) {
2572 throw new RemoteException("Failed to enroll " +
2573 (credentialType == LockPatternUtils.CREDENTIAL_TYPE_PASSWORD ? "password"
2574 : "pattern"));
2575 }
2576
Rubin Xu9a6d39a52018-02-07 08:52:34 +00002577 boolean untrustedReset = false;
Rubin Xu3bf722a2016-12-15 16:07:38 +00002578 if (auth != null) {
Andrew Scull1416bd02018-01-05 18:33:58 +00002579 onAuthTokenKnownForUser(userId, auth);
Rubin Xu8b30ec32017-03-05 00:47:09 +00002580 } else if (response != null
Andrew Scull1416bd02018-01-05 18:33:58 +00002581 && response.getResponseCode() == VerifyCredentialResponse.RESPONSE_ERROR) {
Rubin Xu9a6d39a52018-02-07 08:52:34 +00002582 // We are performing an untrusted credential change, by DevicePolicyManager or other
2583 // internal callers that don't provide the existing credential
Rubin Xu3bf722a2016-12-15 16:07:38 +00002584 Slog.w(TAG, "Untrusted credential change invoked");
Rubin Xu9a6d39a52018-02-07 08:52:34 +00002585 // Try to get a cached auth token, so we can keep SP unchanged.
2586 auth = mSpCache.get(userId);
2587 untrustedReset = true;
Rubin Xu8b30ec32017-03-05 00:47:09 +00002588 } else /* response == null || responseCode == VerifyCredentialResponse.RESPONSE_RETRY */ {
2589 Slog.w(TAG, "spBasedSetLockCredentialInternalLocked: " +
2590 (response != null ? "rate limit exceeded" : "failed"));
2591 return;
Rubin Xu3bf722a2016-12-15 16:07:38 +00002592 }
Rubin Xu9a6d39a52018-02-07 08:52:34 +00002593
2594 if (auth != null) {
2595 if (untrustedReset) {
2596 // Force change the current SID to mantain existing behaviour that an untrusted
2597 // reset leads to a change of SID. If the untrusted reset is for clearing the
2598 // current password, the nuking of the SID will be done in
2599 // setLockCredentialWithAuthTokenLocked next
2600 mSpManager.newSidForUser(getGateKeeperService(), auth, userId);
2601 }
2602 setLockCredentialWithAuthTokenLocked(credential, credentialType, auth, requestedQuality,
2603 userId);
2604 mSpManager.destroyPasswordBasedSyntheticPassword(handle, userId);
2605 } else {
2606 throw new IllegalStateException(
2607 "Untrusted credential reset not possible without cached SP");
2608 // Could call initializeSyntheticPasswordLocked(null, credential, credentialType,
2609 // requestedQuality, userId) instead if we still allow untrusted reset that changes
2610 // synthetic password. That would invalidate existing escrow tokens though.
2611 }
Dmitry Dementyev6e167242018-01-25 15:29:50 -08002612 mRecoverableKeyStoreManager.lockScreenSecretChanged(credentialType, credential, userId);
Rubin Xuf095f832017-01-31 15:23:34 +00002613 }
2614
Rubin Xuf01e9072018-03-30 20:59:28 +01002615 /**
2616 * Returns a fixed pseudorandom byte string derived from the user's synthetic password.
2617 * This is used to salt the password history hash to protect the hash against offline
2618 * bruteforcing, since rederiving this value requires a successful authentication.
Rubin Xu4ed98982018-05-23 14:27:53 +01002619 * If user is a managed profile with unified challenge, currentCredential is ignored.
Rubin Xuf01e9072018-03-30 20:59:28 +01002620 */
2621 @Override
Rich Canningsf64ec632019-02-21 12:40:36 -08002622 public byte[] getHashFactor(byte[] currentCredential, int userId) throws RemoteException {
Rubin Xuf01e9072018-03-30 20:59:28 +01002623 checkPasswordReadPermission(userId);
Rich Canningsf64ec632019-02-21 12:40:36 -08002624 if (currentCredential == null || currentCredential.length == 0) {
Rubin Xuf01e9072018-03-30 20:59:28 +01002625 currentCredential = null;
2626 }
Rubin Xu4ed98982018-05-23 14:27:53 +01002627 if (isManagedProfileWithUnifiedLock(userId)) {
2628 try {
2629 currentCredential = getDecryptedPasswordForTiedProfile(userId);
2630 } catch (Exception e) {
2631 Slog.e(TAG, "Failed to get work profile credential", e);
2632 return null;
2633 }
2634 }
Rubin Xuf01e9072018-03-30 20:59:28 +01002635 synchronized (mSpManager) {
2636 if (!isSyntheticPasswordBasedCredentialLocked(userId)) {
2637 Slog.w(TAG, "Synthetic password not enabled");
2638 return null;
2639 }
2640 long handle = getSyntheticPasswordHandleLocked(userId);
2641 AuthenticationResult auth = mSpManager.unwrapPasswordBasedSyntheticPassword(
2642 getGateKeeperService(), handle, currentCredential, userId, null);
2643 if (auth.authToken == null) {
2644 Slog.w(TAG, "Current credential is incorrect");
2645 return null;
2646 }
2647 return auth.authToken.derivePasswordHashFactor();
2648 }
2649 }
2650
Rubin Xufcd49f92017-08-24 18:21:52 +01002651 private long addEscrowToken(byte[] token, int userId) throws RemoteException {
Rubin Xuf095f832017-01-31 15:23:34 +00002652 if (DEBUG) Slog.d(TAG, "addEscrowToken: user=" + userId);
2653 synchronized (mSpManager) {
2654 enableSyntheticPasswordLocked();
Rubin Xu8b30ec32017-03-05 00:47:09 +00002655 // Migrate to synthetic password based credentials if the user has no password,
Rubin Xuf095f832017-01-31 15:23:34 +00002656 // the token can then be activated immediately.
2657 AuthenticationToken auth = null;
2658 if (!isUserSecure(userId)) {
2659 if (shouldMigrateToSyntheticPasswordLocked(userId)) {
2660 auth = initializeSyntheticPasswordLocked(null, null,
Adrian Roos7374d3a2017-03-31 14:14:53 -07002661 LockPatternUtils.CREDENTIAL_TYPE_NONE,
2662 DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED, userId);
Rubin Xuf095f832017-01-31 15:23:34 +00002663 } else /* isSyntheticPasswordBasedCredentialLocked(userId) */ {
2664 long pwdHandle = getSyntheticPasswordHandleLocked(userId);
2665 auth = mSpManager.unwrapPasswordBasedSyntheticPassword(getGateKeeperService(),
Rubin Xucf326f12017-11-15 11:55:35 +00002666 pwdHandle, null, userId, null).authToken;
Rubin Xuf095f832017-01-31 15:23:34 +00002667 }
2668 }
Rubin Xu128180b2017-04-12 18:02:44 +01002669 if (isSyntheticPasswordBasedCredentialLocked(userId)) {
2670 disableEscrowTokenOnNonManagedDevicesIfNeeded(userId);
2671 if (!mSpManager.hasEscrowData(userId)) {
2672 throw new SecurityException("Escrow token is disabled on the current user");
2673 }
Rubin Xuf095f832017-01-31 15:23:34 +00002674 }
2675 long handle = mSpManager.createTokenBasedSyntheticPassword(token, userId);
2676 if (auth != null) {
2677 mSpManager.activateTokenBasedSyntheticPassword(handle, auth, userId);
2678 }
2679 return handle;
2680 }
2681 }
2682
Rubin Xufcd49f92017-08-24 18:21:52 +01002683 private void activateEscrowTokens(AuthenticationToken auth, int userId) {
Rubin Xuf095f832017-01-31 15:23:34 +00002684 if (DEBUG) Slog.d(TAG, "activateEscrowTokens: user=" + userId);
2685 synchronized (mSpManager) {
Rubin Xue94a7702017-06-20 17:29:57 +01002686 disableEscrowTokenOnNonManagedDevicesIfNeeded(userId);
Rubin Xuf095f832017-01-31 15:23:34 +00002687 for (long handle : mSpManager.getPendingTokensForUser(userId)) {
2688 Slog.i(TAG, String.format("activateEscrowTokens: %x %d ", handle, userId));
2689 mSpManager.activateTokenBasedSyntheticPassword(handle, auth, userId);
2690 }
2691 }
2692 }
2693
Rubin Xufcd49f92017-08-24 18:21:52 +01002694 private boolean isEscrowTokenActive(long handle, int userId) {
Rubin Xuf095f832017-01-31 15:23:34 +00002695 synchronized (mSpManager) {
2696 return mSpManager.existsHandle(handle, userId);
2697 }
2698 }
2699
Rubin Xufcd49f92017-08-24 18:21:52 +01002700 private boolean removeEscrowToken(long handle, int userId) {
Rubin Xuf095f832017-01-31 15:23:34 +00002701 synchronized (mSpManager) {
2702 if (handle == getSyntheticPasswordHandleLocked(userId)) {
2703 Slog.w(TAG, "Cannot remove password handle");
2704 return false;
2705 }
2706 if (mSpManager.removePendingToken(handle, userId)) {
2707 return true;
2708 }
2709 if (mSpManager.existsHandle(handle, userId)) {
2710 mSpManager.destroyTokenBasedSyntheticPassword(handle, userId);
2711 return true;
2712 } else {
2713 return false;
2714 }
2715 }
2716 }
2717
Rich Canningsf64ec632019-02-21 12:40:36 -08002718 private boolean setLockCredentialWithToken(byte[] credential, int type, long tokenHandle,
Adrian Roos7374d3a2017-03-31 14:14:53 -07002719 byte[] token, int requestedQuality, int userId) throws RemoteException {
Rubin Xuf095f832017-01-31 15:23:34 +00002720 boolean result;
2721 synchronized (mSpManager) {
2722 if (!mSpManager.hasEscrowData(userId)) {
2723 throw new SecurityException("Escrow token is disabled on the current user");
2724 }
2725 result = setLockCredentialWithTokenInternal(credential, type, tokenHandle, token,
Adrian Roos7374d3a2017-03-31 14:14:53 -07002726 requestedQuality, userId);
Rubin Xuf095f832017-01-31 15:23:34 +00002727 }
2728 if (result) {
2729 synchronized (mSeparateChallengeLock) {
Pavel Grafov28939982017-10-03 15:11:52 +01002730 setSeparateProfileChallengeEnabledLocked(userId, true, null);
Rubin Xuf095f832017-01-31 15:23:34 +00002731 }
2732 notifyPasswordChanged(userId);
Pavel Grafov28939982017-10-03 15:11:52 +01002733 notifySeparateProfileChallengeChanged(userId);
Rubin Xuf095f832017-01-31 15:23:34 +00002734 }
2735 return result;
2736 }
2737
Rich Canningsf64ec632019-02-21 12:40:36 -08002738 private boolean setLockCredentialWithTokenInternal(byte[] credential, int type,
Adrian Roos7374d3a2017-03-31 14:14:53 -07002739 long tokenHandle, byte[] token, int requestedQuality, int userId) throws RemoteException {
Andrew Scull1416bd02018-01-05 18:33:58 +00002740 final AuthenticationResult result;
Rubin Xuf095f832017-01-31 15:23:34 +00002741 synchronized (mSpManager) {
Andrew Scull1416bd02018-01-05 18:33:58 +00002742 result = mSpManager.unwrapTokenBasedSyntheticPassword(
Rubin Xuf095f832017-01-31 15:23:34 +00002743 getGateKeeperService(), tokenHandle, token, userId);
2744 if (result.authToken == null) {
2745 Slog.w(TAG, "Invalid escrow token supplied");
2746 return false;
2747 }
Rubin Xu24570e42017-09-19 15:27:21 +01002748 if (result.gkResponse.getResponseCode() != VerifyCredentialResponse.RESPONSE_OK) {
2749 // Most likely, an untrusted credential reset happened in the past which
2750 // changed the synthetic password
2751 Slog.e(TAG, "Obsolete token: synthetic password derived but it fails GK "
2752 + "verification.");
2753 return false;
2754 }
Rubin Xu7cf45092017-08-28 11:47:35 +01002755 // Update PASSWORD_TYPE_KEY since it's needed by notifyActivePasswordMetricsAvailable()
2756 // called by setLockCredentialWithAuthTokenLocked().
2757 // TODO: refactor usage of PASSWORD_TYPE_KEY b/65239740
2758 setLong(LockPatternUtils.PASSWORD_TYPE_KEY, requestedQuality, userId);
Rubin Xuf095f832017-01-31 15:23:34 +00002759 long oldHandle = getSyntheticPasswordHandleLocked(userId);
Adrian Roos7374d3a2017-03-31 14:14:53 -07002760 setLockCredentialWithAuthTokenLocked(credential, type, result.authToken,
2761 requestedQuality, userId);
Rubin Xuf095f832017-01-31 15:23:34 +00002762 mSpManager.destroyPasswordBasedSyntheticPassword(oldHandle, userId);
Rubin Xuf095f832017-01-31 15:23:34 +00002763 }
Andrew Scull1416bd02018-01-05 18:33:58 +00002764 onAuthTokenKnownForUser(userId, result.authToken);
2765 return true;
Rubin Xuf095f832017-01-31 15:23:34 +00002766 }
2767
Rubin Xufcd49f92017-08-24 18:21:52 +01002768 private boolean unlockUserWithToken(long tokenHandle, byte[] token, int userId)
Rubin Xuf095f832017-01-31 15:23:34 +00002769 throws RemoteException {
Rubin Xuf095f832017-01-31 15:23:34 +00002770 AuthenticationResult authResult;
2771 synchronized (mSpManager) {
2772 if (!mSpManager.hasEscrowData(userId)) {
2773 throw new SecurityException("Escrow token is disabled on the current user");
2774 }
2775 authResult = mSpManager.unwrapTokenBasedSyntheticPassword(getGateKeeperService(),
2776 tokenHandle, token, userId);
2777 if (authResult.authToken == null) {
2778 Slog.w(TAG, "Invalid escrow token supplied");
Rubin Xufcd49f92017-08-24 18:21:52 +01002779 return false;
Rubin Xuf095f832017-01-31 15:23:34 +00002780 }
2781 }
2782 unlockUser(userId, null, authResult.authToken.deriveDiskEncryptionKey());
Andrew Scull1416bd02018-01-05 18:33:58 +00002783 onAuthTokenKnownForUser(userId, authResult.authToken);
Rubin Xufcd49f92017-08-24 18:21:52 +01002784 return true;
Rubin Xu3bf722a2016-12-15 16:07:38 +00002785 }
2786
2787 @Override
2788 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args){
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06002789 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
Rubin Xu3bf722a2016-12-15 16:07:38 +00002790
Rubin Xua0a0d352017-05-15 16:18:01 +00002791 pw.println("Current lock settings service state:");
2792 pw.println(String.format("SP Enabled = %b",
2793 mLockPatternUtils.isSyntheticPasswordEnabled()));
Rubin Xu3bf722a2016-12-15 16:07:38 +00002794
Rubin Xua0a0d352017-05-15 16:18:01 +00002795 List<UserInfo> users = mUserManager.getUsers();
2796 for (int user = 0; user < users.size(); user++) {
2797 final int userId = users.get(user).id;
2798 pw.println(" User " + userId);
2799 synchronized (mSpManager) {
Rubin Xu3bf722a2016-12-15 16:07:38 +00002800 pw.println(String.format(" SP Handle = %x",
2801 getSyntheticPasswordHandleLocked(userId)));
Rubin Xua0a0d352017-05-15 16:18:01 +00002802 }
2803 try {
2804 pw.println(String.format(" SID = %x",
2805 getGateKeeperService().getSecureUserId(userId)));
2806 } catch (RemoteException e) {
2807 // ignore.
Rubin Xu3bf722a2016-12-15 16:07:38 +00002808 }
2809 }
2810 }
2811
Rubin Xuf095f832017-01-31 15:23:34 +00002812 private void disableEscrowTokenOnNonManagedDevicesIfNeeded(int userId) {
2813 long ident = Binder.clearCallingIdentity();
2814 try {
2815 // Managed profile should have escrow enabled
2816 if (mUserManager.getUserInfo(userId).isManagedProfile()) {
Rubin Xubc7a47c2017-02-22 20:31:57 +00002817 Slog.i(TAG, "Managed profile can have escrow token");
Rubin Xuf095f832017-01-31 15:23:34 +00002818 return;
2819 }
Rubin Xuf34d2f62017-03-20 12:36:35 +00002820 DevicePolicyManager dpm = mInjector.getDevicePolicyManager();
Rubin Xuf095f832017-01-31 15:23:34 +00002821 // Devices with Device Owner should have escrow enabled on all users.
Rubin Xuf34d2f62017-03-20 12:36:35 +00002822 if (dpm.getDeviceOwnerComponentOnAnyUser() != null) {
Rubin Xubc7a47c2017-02-22 20:31:57 +00002823 Slog.i(TAG, "Corp-owned device can have escrow token");
2824 return;
2825 }
2826 // We could also have a profile owner on the given (non-managed) user for unicorn cases
Rubin Xuf34d2f62017-03-20 12:36:35 +00002827 if (dpm.getProfileOwnerAsUser(userId) != null) {
Rubin Xubc7a47c2017-02-22 20:31:57 +00002828 Slog.i(TAG, "User with profile owner can have escrow token");
Rubin Xuf095f832017-01-31 15:23:34 +00002829 return;
2830 }
2831 // If the device is yet to be provisioned (still in SUW), there is still
2832 // a chance that Device Owner will be set on the device later, so postpone
2833 // disabling escrow token for now.
Rubin Xuf34d2f62017-03-20 12:36:35 +00002834 if (!dpm.isDeviceProvisioned()) {
Rubin Xubc7a47c2017-02-22 20:31:57 +00002835 Slog.i(TAG, "Postpone disabling escrow tokens until device is provisioned");
Rubin Xuf095f832017-01-31 15:23:34 +00002836 return;
2837 }
Rakesh Iyercb18d562017-03-06 18:05:53 -08002838
2839 // Escrow tokens are enabled on automotive builds.
2840 if (mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE)) {
2841 return;
2842 }
2843
Rubin Xuf095f832017-01-31 15:23:34 +00002844 // Disable escrow token permanently on all other device/user types.
2845 Slog.i(TAG, "Disabling escrow token on user " + userId);
2846 if (isSyntheticPasswordBasedCredentialLocked(userId)) {
2847 mSpManager.destroyEscrowData(userId);
2848 }
Rubin Xuf095f832017-01-31 15:23:34 +00002849 } finally {
2850 Binder.restoreCallingIdentity(ident);
2851 }
2852 }
2853
Adrian Roos7374d3a2017-03-31 14:14:53 -07002854 private class DeviceProvisionedObserver extends ContentObserver {
2855 private final Uri mDeviceProvisionedUri = Settings.Global.getUriFor(
2856 Settings.Global.DEVICE_PROVISIONED);
Andrew Scull1416bd02018-01-05 18:33:58 +00002857 private final Uri mUserSetupCompleteUri = Settings.Secure.getUriFor(
2858 Settings.Secure.USER_SETUP_COMPLETE);
Adrian Roos7374d3a2017-03-31 14:14:53 -07002859
2860 private boolean mRegistered;
2861
2862 public DeviceProvisionedObserver() {
2863 super(null);
2864 }
2865
2866 @Override
Andrew Scullede482d2018-01-30 13:54:29 +00002867 public void onChange(boolean selfChange, Uri uri, @UserIdInt int userId) {
Adrian Roos7374d3a2017-03-31 14:14:53 -07002868 if (mDeviceProvisionedUri.equals(uri)) {
2869 updateRegistration();
2870
2871 if (isProvisioned()) {
2872 Slog.i(TAG, "Reporting device setup complete to IGateKeeperService");
2873 reportDeviceSetupComplete();
Adrian Roos454f53f2017-08-08 14:56:42 +02002874 clearFrpCredentialIfOwnerNotSecure();
Adrian Roos7374d3a2017-03-31 14:14:53 -07002875 }
Andrew Scull1416bd02018-01-05 18:33:58 +00002876 } else if (mUserSetupCompleteUri.equals(uri)) {
Andrew Scullede482d2018-01-30 13:54:29 +00002877 tryRemoveUserFromSpCacheLater(userId);
Adrian Roos7374d3a2017-03-31 14:14:53 -07002878 }
2879 }
2880
2881 public void onSystemReady() {
Adrian Roos2adc2632017-09-05 17:01:42 +02002882 if (frpCredentialEnabled(mContext)) {
Adrian Roos7374d3a2017-03-31 14:14:53 -07002883 updateRegistration();
2884 } else {
2885 // If we don't intend to use frpCredentials and we're not provisioned yet, send
2886 // deviceSetupComplete immediately, so gatekeeper can discard any lingering
2887 // credentials immediately.
2888 if (!isProvisioned()) {
2889 Slog.i(TAG, "FRP credential disabled, reporting device setup complete "
2890 + "to Gatekeeper immediately");
2891 reportDeviceSetupComplete();
2892 }
2893 }
2894 }
2895
2896 private void reportDeviceSetupComplete() {
2897 try {
2898 getGateKeeperService().reportDeviceSetupComplete();
2899 } catch (RemoteException e) {
2900 Slog.e(TAG, "Failure reporting to IGateKeeperService", e);
2901 }
2902 }
2903
Adrian Roos454f53f2017-08-08 14:56:42 +02002904 /**
2905 * Clears the FRP credential if the user that controls it does not have a secure
2906 * lockscreen.
2907 */
2908 private void clearFrpCredentialIfOwnerNotSecure() {
2909 List<UserInfo> users = mUserManager.getUsers();
2910 for (UserInfo user : users) {
Adrian Roos2adc2632017-09-05 17:01:42 +02002911 if (userOwnsFrpCredential(mContext, user)) {
Adrian Roos454f53f2017-08-08 14:56:42 +02002912 if (!isUserSecure(user.id)) {
2913 mStorage.writePersistentDataBlock(PersistentData.TYPE_NONE, user.id,
2914 0, null);
2915 }
2916 return;
2917 }
2918 }
2919 }
2920
Adrian Roos7374d3a2017-03-31 14:14:53 -07002921 private void updateRegistration() {
2922 boolean register = !isProvisioned();
2923 if (register == mRegistered) {
2924 return;
2925 }
2926 if (register) {
2927 mContext.getContentResolver().registerContentObserver(mDeviceProvisionedUri,
2928 false, this);
Andrew Scull1416bd02018-01-05 18:33:58 +00002929 mContext.getContentResolver().registerContentObserver(mUserSetupCompleteUri,
2930 false, this, UserHandle.USER_ALL);
Adrian Roos7374d3a2017-03-31 14:14:53 -07002931 } else {
2932 mContext.getContentResolver().unregisterContentObserver(this);
2933 }
2934 mRegistered = register;
2935 }
2936
2937 private boolean isProvisioned() {
2938 return Settings.Global.getInt(mContext.getContentResolver(),
2939 Settings.Global.DEVICE_PROVISIONED, 0) != 0;
2940 }
2941 }
Rubin Xufcd49f92017-08-24 18:21:52 +01002942
2943 private final class LocalService extends LockSettingsInternal {
2944
2945 @Override
2946 public long addEscrowToken(byte[] token, int userId) {
2947 try {
2948 return LockSettingsService.this.addEscrowToken(token, userId);
2949 } catch (RemoteException re) {
2950 throw re.rethrowFromSystemServer();
2951 }
2952 }
2953
2954 @Override
2955 public boolean removeEscrowToken(long handle, int userId) {
2956 return LockSettingsService.this.removeEscrowToken(handle, userId);
2957 }
2958
2959 @Override
2960 public boolean isEscrowTokenActive(long handle, int userId) {
2961 return LockSettingsService.this.isEscrowTokenActive(handle, userId);
2962 }
2963
2964 @Override
Rich Canningsf64ec632019-02-21 12:40:36 -08002965 public boolean setLockCredentialWithToken(byte[] credential, int type,
2966 long tokenHandle, byte[] token, int requestedQuality, int userId) {
Lenka Trochtova66c492a2018-12-06 11:29:21 +01002967 if (!mLockPatternUtils.hasSecureLockScreen()) {
2968 throw new UnsupportedOperationException(
2969 "This operation requires secure lock screen feature.");
2970 }
Rubin Xufcd49f92017-08-24 18:21:52 +01002971 try {
2972 return LockSettingsService.this.setLockCredentialWithToken(credential, type,
2973 tokenHandle, token, requestedQuality, userId);
2974 } catch (RemoteException re) {
2975 throw re.rethrowFromSystemServer();
2976 }
2977 }
2978
2979 @Override
2980 public boolean unlockUserWithToken(long tokenHandle, byte[] token, int userId) {
2981 try {
2982 return LockSettingsService.this.unlockUserWithToken(tokenHandle, token, userId);
2983 } catch (RemoteException re) {
2984 throw re.rethrowFromSystemServer();
2985 }
2986 }
2987 }
Amith Yamasani52c489c2012-03-28 11:42:42 -07002988}