blob: a53ab84f733ea41220986821d64c4f138409b9aa [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
Ram Periathiruvadi32d53552019-02-19 13:25:46 -080024import static com.android.internal.widget.LockPatternUtils.EscrowTokenStateChangeCallback;
Rubin Xu3bf722a2016-12-15 16:07:38 +000025import static com.android.internal.widget.LockPatternUtils.SYNTHETIC_PASSWORD_ENABLED_KEY;
26import static com.android.internal.widget.LockPatternUtils.SYNTHETIC_PASSWORD_HANDLE_KEY;
Bo Zhuc7048342019-01-03 14:04:58 -080027import static com.android.internal.widget.LockPatternUtils.StrongAuthTracker.STRONG_AUTH_REQUIRED_AFTER_BOOT;
28import static com.android.internal.widget.LockPatternUtils.StrongAuthTracker.STRONG_AUTH_REQUIRED_AFTER_LOCKOUT;
Adrian Roos7374d3a2017-03-31 14:14:53 -070029import static com.android.internal.widget.LockPatternUtils.USER_FRP;
30import static com.android.internal.widget.LockPatternUtils.frpCredentialEnabled;
Adrian Roos454f53f2017-08-08 14:56:42 +020031import static com.android.internal.widget.LockPatternUtils.userOwnsFrpCredential;
Rubin Xu1de89b32016-11-30 20:03:13 +000032
Dmitry Dementyev1aa96132017-12-11 11:33:12 -080033import android.annotation.NonNull;
34import android.annotation.Nullable;
Andrew Scull5daf2732016-11-14 15:02:45 +000035import android.annotation.UserIdInt;
Sudheer Shankadc589ac2016-11-10 15:30:17 -080036import android.app.ActivityManager;
Rubin Xu0cbc19e2016-12-09 14:00:21 +000037import android.app.IActivityManager;
Kenny Guyb1b30262016-02-09 16:02:35 +000038import android.app.KeyguardManager;
Jim Miller4f93c582016-01-27 19:05:43 -080039import android.app.Notification;
40import android.app.NotificationManager;
41import android.app.PendingIntent;
Adrian Roos230635e2015-01-07 20:50:29 +010042import android.app.admin.DevicePolicyManager;
Pavel Grafov28939982017-10-03 15:11:52 +010043import android.app.admin.DevicePolicyManagerInternal;
Andrew Scull5daf2732016-11-14 15:02:45 +000044import android.app.admin.PasswordMetrics;
Amith Yamasani072543f2015-02-13 11:09:45 -080045import android.app.backup.BackupManager;
Adrian Roosb5e47222015-08-14 15:53:06 -070046import android.app.trust.IStrongAuthTracker;
Clara Bayarri56878a92015-10-29 15:43:55 +000047import android.app.trust.TrustManager;
Robin Leef0246a82014-08-13 09:50:25 +010048import android.content.BroadcastReceiver;
Amith Yamasani52c489c2012-03-28 11:42:42 -070049import android.content.ContentResolver;
Amith Yamasani52c489c2012-03-28 11:42:42 -070050import android.content.Context;
Robin Leef0246a82014-08-13 09:50:25 +010051import android.content.Intent;
52import android.content.IntentFilter;
Jim Miller158fe192013-04-17 15:23:55 -070053import android.content.pm.PackageManager;
Jim Miller187ec582013-04-15 18:27:54 -070054import android.content.pm.UserInfo;
Jim Miller4f93c582016-01-27 19:05:43 -080055import android.content.res.Resources;
Adrian Roos7374d3a2017-03-31 14:14:53 -070056import android.database.ContentObserver;
Amith Yamasani52c489c2012-03-28 11:42:42 -070057import android.database.sqlite.SQLiteDatabase;
Andrew Sculle6527c12018-01-05 18:33:58 +000058import android.hardware.authsecret.V1_0.IAuthSecret;
Kevin Chyna38653c2019-02-11 17:46:21 -080059import android.hardware.biometrics.BiometricManager;
60import android.hardware.face.FaceManager;
Adrian Roos7374d3a2017-03-31 14:14:53 -070061import android.net.Uri;
Amith Yamasani52c489c2012-03-28 11:42:42 -070062import android.os.Binder;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -060063import android.os.Bundle;
Ricky Waib0cdf382016-05-16 17:28:04 +010064import android.os.Handler;
Paul Lawrence945490c2014-03-27 16:37:28 +000065import android.os.IBinder;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -060066import android.os.IProgressListener;
Ricky Wai4613fe42016-05-24 11:11:42 +010067import android.os.Process;
Amith Yamasani52c489c2012-03-28 11:42:42 -070068import android.os.RemoteException;
Jorim Jaggi2fef6f72016-11-01 19:06:25 -070069import android.os.ResultReceiver;
Paul Lawrence945490c2014-03-27 16:37:28 +000070import android.os.ServiceManager;
Rubin Xu1de89b32016-11-30 20:03:13 +000071import android.os.ShellCallback;
Jeff Sharkeyeddf5182016-08-09 16:36:08 -060072import android.os.StrictMode;
Amith Yamasanid1645f82012-06-12 11:53:26 -070073import android.os.SystemProperties;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070074import android.os.UserHandle;
Jim Miller187ec582013-04-15 18:27:54 -070075import android.os.UserManager;
Rubin Xu1de89b32016-11-30 20:03:13 +000076import android.os.storage.IStorageManager;
77import android.os.storage.StorageManager;
Amith Yamasani52c489c2012-03-28 11:42:42 -070078import android.provider.Settings;
79import android.provider.Settings.Secure;
Jim Miller187ec582013-04-15 18:27:54 -070080import android.provider.Settings.SettingNotFoundException;
Jim Millerde1af082013-09-11 14:58:26 -070081import android.security.KeyStore;
Ricky Waidc283a82016-03-24 19:55:08 +000082import android.security.keystore.AndroidKeyStoreProvider;
83import android.security.keystore.KeyProperties;
84import android.security.keystore.KeyProtection;
Pavel Grafov0acc4bf2017-08-23 12:20:54 +010085import android.security.keystore.UserNotAuthenticatedException;
Dmitry Dementyev0916e7c2018-01-23 13:02:08 -080086import android.security.keystore.recovery.KeyChainProtectionParams;
Bo Zhuc7048342019-01-03 14:04:58 -080087import android.security.keystore.recovery.KeyChainSnapshot;
Bo Zhu7c1972f2018-02-22 21:43:52 -080088import android.security.keystore.recovery.RecoveryCertPath;
Robert Berry81ee34b2018-01-23 11:59:59 +000089import android.security.keystore.recovery.WrappedApplicationKey;
Andres Morales23974272015-05-14 22:42:26 -070090import android.service.gatekeeper.GateKeeperResponse;
Andres Morales8fa56652015-03-31 09:19:50 -070091import android.service.gatekeeper.IGateKeeperService;
Amith Yamasani52c489c2012-03-28 11:42:42 -070092import android.text.TextUtils;
Rubin Xua55b1682017-01-31 10:06:56 +000093import android.util.ArrayMap;
Adrian Roosb953e182017-08-17 17:58:26 +020094import android.util.EventLog;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -060095import android.util.Log;
Amith Yamasani52c489c2012-03-28 11:42:42 -070096import android.util.Slog;
Andrew Scull1416bd02018-01-05 18:33:58 +000097import android.util.SparseArray;
Amith Yamasani52c489c2012-03-28 11:42:42 -070098
Pavel Grafov28939982017-10-03 15:11:52 +010099import com.android.internal.annotations.GuardedBy;
Rubin Xu0cbc19e2016-12-09 14:00:21 +0000100import com.android.internal.annotations.VisibleForTesting;
Chris Wren282cfef2017-03-27 15:01:44 -0400101import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
Geoffrey Pitschaf759c52017-02-15 09:35:38 -0500102import com.android.internal.notification.SystemNotificationChannels;
Amith Yamasani072543f2015-02-13 11:09:45 -0800103import com.android.internal.util.ArrayUtils;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -0600104import com.android.internal.util.DumpUtils;
Adrian Roos7374d3a2017-03-31 14:14:53 -0700105import com.android.internal.util.Preconditions;
Jorim Jaggie8fde5d2016-06-30 23:41:37 -0700106import com.android.internal.widget.ICheckCredentialProgressCallback;
Jeff Sharkey7a96c392012-11-15 14:01:46 -0800107import com.android.internal.widget.ILockSettings;
108import com.android.internal.widget.LockPatternUtils;
Rubin Xufcd49f92017-08-24 18:21:52 +0100109import com.android.internal.widget.LockSettingsInternal;
Andres Morales23974272015-05-14 22:42:26 -0700110import com.android.internal.widget.VerifyCredentialResponse;
Pavel Grafov28939982017-10-03 15:11:52 +0100111import com.android.server.LocalServices;
Andrew Scull507d11c2017-05-03 17:19:01 +0100112import com.android.server.SystemService;
113import com.android.server.locksettings.LockSettingsStorage.CredentialHash;
Dmitry Dementyev1aa96132017-12-11 11:33:12 -0800114import com.android.server.locksettings.LockSettingsStorage.PersistentData;
Andrew Scull507d11c2017-05-03 17:19:01 +0100115import com.android.server.locksettings.SyntheticPasswordManager.AuthenticationResult;
116import com.android.server.locksettings.SyntheticPasswordManager.AuthenticationToken;
Bo Zhuc7048342019-01-03 14:04:58 -0800117import com.android.server.locksettings.recoverablekeystore.RecoverableKeyStoreManager;
Adrian Roos1c8e3c02018-11-20 20:07:55 +0100118import com.android.server.wm.WindowManagerInternal;
Jeff Sharkey7a96c392012-11-15 14:01:46 -0800119
Ricky Waidc283a82016-03-24 19:55:08 +0000120import libcore.util.HexEncoding;
121
122import java.io.ByteArrayOutputStream;
Jorim Jaggi2fef6f72016-11-01 19:06:25 -0700123import java.io.FileDescriptor;
Ricky Waidc283a82016-03-24 19:55:08 +0000124import java.io.FileNotFoundException;
125import java.io.IOException;
Rubin Xu3bf722a2016-12-15 16:07:38 +0000126import java.io.PrintWriter;
Ricky Waidc283a82016-03-24 19:55:08 +0000127import java.security.InvalidAlgorithmParameterException;
128import java.security.InvalidKeyException;
129import java.security.KeyStoreException;
Paul Crowleyfaeb3eb2016-02-08 15:58:29 +0000130import java.security.MessageDigest;
131import java.security.NoSuchAlgorithmException;
Ricky Waidc283a82016-03-24 19:55:08 +0000132import java.security.SecureRandom;
133import java.security.UnrecoverableKeyException;
134import java.security.cert.CertificateException;
Andrew Sculle6527c12018-01-05 18:33:58 +0000135import java.util.ArrayList;
Bo Zhuc7048342019-01-03 14:04:58 -0800136import java.util.Arrays;
Jim Miller187ec582013-04-15 18:27:54 -0700137import java.util.List;
Rubin Xua55b1682017-01-31 10:06:56 +0000138import java.util.Map;
Andrew Sculle6527c12018-01-05 18:33:58 +0000139import java.util.NoSuchElementException;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -0600140import java.util.concurrent.CountDownLatch;
141import java.util.concurrent.TimeUnit;
Amith Yamasani52c489c2012-03-28 11:42:42 -0700142
Ricky Waidc283a82016-03-24 19:55:08 +0000143import javax.crypto.BadPaddingException;
144import javax.crypto.Cipher;
145import javax.crypto.IllegalBlockSizeException;
146import javax.crypto.KeyGenerator;
147import javax.crypto.NoSuchPaddingException;
148import javax.crypto.SecretKey;
149import javax.crypto.spec.GCMParameterSpec;
150
Amith Yamasani52c489c2012-03-28 11:42:42 -0700151/**
Rubin Xu1de89b32016-11-30 20:03:13 +0000152 * Keeps the lock pattern/password data and related settings for each user. Used by
153 * LockPatternUtils. Needs to be a service because Settings app also needs to be able to save
154 * lockscreen information for secondary users.
155 *
Amith Yamasani52c489c2012-03-28 11:42:42 -0700156 * @hide
157 */
158public class LockSettingsService extends ILockSettings.Stub {
Amith Yamasani52c489c2012-03-28 11:42:42 -0700159 private static final String TAG = "LockSettingsService";
Jim Miller4f93c582016-01-27 19:05:43 -0800160 private static final String PERMISSION = ACCESS_KEYGUARD_SECURE_STORAGE;
Jim Miller4f93c582016-01-27 19:05:43 -0800161 private static final boolean DEBUG = false;
Amith Yamasani52c489c2012-03-28 11:42:42 -0700162
Ricky Waidc283a82016-03-24 19:55:08 +0000163 private static final int PROFILE_KEY_IV_SIZE = 12;
164 private static final String SEPARATE_PROFILE_CHALLENGE_KEY = "lockscreen.profilechallenge";
Paul Crowley7a0cc0a2017-05-31 22:12:57 +0000165 private static final int SYNTHETIC_PASSWORD_ENABLED_BY_DEFAULT = 1;
Rubin Xu1de89b32016-11-30 20:03:13 +0000166
Rubin Xua0a0d352017-05-15 16:18:01 +0000167 // Order of holding lock: mSeparateChallengeLock -> mSpManager -> this
Rubin Xue94a7702017-06-20 17:29:57 +0100168 // Do not call into ActivityManager while holding mSpManager lock.
Ricky Waidc283a82016-03-24 19:55:08 +0000169 private final Object mSeparateChallengeLock = new Object();
170
Adrian Roos7374d3a2017-03-31 14:14:53 -0700171 private final DeviceProvisionedObserver mDeviceProvisionedObserver =
172 new DeviceProvisionedObserver();
173
Rubin Xu0cbc19e2016-12-09 14:00:21 +0000174 private final Injector mInjector;
Amith Yamasani52c489c2012-03-28 11:42:42 -0700175 private final Context mContext;
Rubin Xu7cf45092017-08-28 11:47:35 +0100176 @VisibleForTesting
177 protected final Handler mHandler;
Rubin Xu0cbc19e2016-12-09 14:00:21 +0000178 @VisibleForTesting
179 protected final LockSettingsStorage mStorage;
Rakesh Iyera7aa4d62016-01-19 17:27:23 -0800180 private final LockSettingsStrongAuth mStrongAuth;
Victor Changa0940d32016-05-16 19:36:08 +0100181 private final SynchronizedStrongAuthTracker mStrongAuthTracker;
Adrian Roos261d5ab2014-10-29 14:42:38 +0100182
Rubin Xu0cbc19e2016-12-09 14:00:21 +0000183 private final LockPatternUtils mLockPatternUtils;
184 private final NotificationManager mNotificationManager;
185 private final UserManager mUserManager;
186 private final IActivityManager mActivityManager;
Andrew Scull8fc2ec82017-05-19 10:50:36 +0100187 private final SyntheticPasswordManager mSpManager;
Rubin Xu0cbc19e2016-12-09 14:00:21 +0000188
189 private final KeyStore mKeyStore;
190
Dmitry Dementyev1aa96132017-12-11 11:33:12 -0800191 private final RecoverableKeyStoreManager mRecoverableKeyStoreManager;
192
Paul Lawrence945490c2014-03-27 16:37:28 +0000193 private boolean mFirstCallToVold;
Rubin Xu0cbc19e2016-12-09 14:00:21 +0000194 protected IGateKeeperService mGateKeeperService;
Andrew Sculle6527c12018-01-05 18:33:58 +0000195 protected IAuthSecret mAuthSecretService;
Rubin Xu3bf722a2016-12-15 16:07:38 +0000196
David Anderson6ebc25b2019-02-12 16:25:56 -0800197 private static final String GSI_RUNNING_PROP = "ro.gsid.image_running";
198
Ricky Wai4613fe42016-05-24 11:11:42 +0100199 /**
200 * The UIDs that are used for system credential storage in keystore.
201 */
Rubin Xu1de89b32016-11-30 20:03:13 +0000202 private static final int[] SYSTEM_CREDENTIAL_UIDS = {
203 Process.WIFI_UID, Process.VPN_UID,
Rubin Xu24b89b12017-04-26 19:44:16 +0100204 Process.ROOT_UID, Process.SYSTEM_UID };
Andres Morales23974272015-05-14 22:42:26 -0700205
Jim Miller4f93c582016-01-27 19:05:43 -0800206 // This class manages life cycle events for encrypted users on File Based Encryption (FBE)
207 // devices. The most basic of these is to show/hide notifications about missing features until
208 // the user unlocks the account and credential-encrypted storage is available.
209 public static final class Lifecycle extends SystemService {
210 private LockSettingsService mLockSettingsService;
211
212 public Lifecycle(Context context) {
213 super(context);
214 }
215
216 @Override
217 public void onStart() {
Ricky Waidc283a82016-03-24 19:55:08 +0000218 AndroidKeyStoreProvider.install();
Jim Miller4f93c582016-01-27 19:05:43 -0800219 mLockSettingsService = new LockSettingsService(getContext());
220 publishBinderService("lock_settings", mLockSettingsService);
221 }
222
223 @Override
Adrian Roos60dcbbf2017-08-08 16:19:33 +0200224 public void onBootPhase(int phase) {
225 super.onBootPhase(phase);
226 if (phase == PHASE_ACTIVITY_MANAGER_READY) {
227 mLockSettingsService.migrateOldDataAfterSystemReady();
228 }
229 }
230
231 @Override
Andrew Scull85a63bc2016-10-24 13:47:47 +0100232 public void onStartUser(int userHandle) {
233 mLockSettingsService.onStartUser(userHandle);
Jim Miller4f93c582016-01-27 19:05:43 -0800234 }
235
236 @Override
237 public void onUnlockUser(int userHandle) {
238 mLockSettingsService.onUnlockUser(userHandle);
239 }
240
241 @Override
242 public void onCleanupUser(int userHandle) {
243 mLockSettingsService.onCleanupUser(userHandle);
244 }
245 }
246
Rubin Xu0cbc19e2016-12-09 14:00:21 +0000247 @VisibleForTesting
248 protected static class SynchronizedStrongAuthTracker
249 extends LockPatternUtils.StrongAuthTracker {
Victor Changa0940d32016-05-16 19:36:08 +0100250 public SynchronizedStrongAuthTracker(Context context) {
251 super(context);
252 }
253
254 @Override
255 protected void handleStrongAuthRequiredChanged(int strongAuthFlags, int userId) {
256 synchronized (this) {
257 super.handleStrongAuthRequiredChanged(strongAuthFlags, userId);
258 }
259 }
260
261 @Override
262 public int getStrongAuthForUser(int userId) {
263 synchronized (this) {
264 return super.getStrongAuthForUser(userId);
265 }
266 }
267
Rubin Xu0cbc19e2016-12-09 14:00:21 +0000268 void register(LockSettingsStrongAuth strongAuth) {
269 strongAuth.registerStrongAuthTracker(this.mStub);
Victor Changa0940d32016-05-16 19:36:08 +0100270 }
271 }
272
Ricky Waidc283a82016-03-24 19:55:08 +0000273 /**
274 * Tie managed profile to primary profile if it is in unified mode and not tied before.
275 *
276 * @param managedUserId Managed profile user Id
277 * @param managedUserPassword Managed profile original password (when it has separated lock).
278 * NULL when it does not have a separated lock before.
279 */
Rich Canningsf64ec632019-02-21 12:40:36 -0800280 public void tieManagedProfileLockIfNecessary(int managedUserId, byte[] managedUserPassword) {
Ricky Waidc283a82016-03-24 19:55:08 +0000281 if (DEBUG) Slog.v(TAG, "Check child profile lock for user: " + managedUserId);
282 // Only for managed profile
Rubin Xu0cbc19e2016-12-09 14:00:21 +0000283 if (!mUserManager.getUserInfo(managedUserId).isManagedProfile()) {
Ricky Waidc283a82016-03-24 19:55:08 +0000284 return;
285 }
286 // Do not tie managed profile when work challenge is enabled
287 if (mLockPatternUtils.isSeparateProfileChallengeEnabled(managedUserId)) {
288 return;
289 }
290 // Do not tie managed profile to parent when it's done already
291 if (mStorage.hasChildProfileLock(managedUserId)) {
292 return;
293 }
294 // Do not tie it to parent when parent does not have a screen lock
295 final int parentId = mUserManager.getProfileParent(managedUserId).id;
Rubin Xua55b1682017-01-31 10:06:56 +0000296 if (!isUserSecure(parentId)) {
Ricky Waidc283a82016-03-24 19:55:08 +0000297 if (DEBUG) Slog.v(TAG, "Parent does not have a screen lock");
298 return;
299 }
Rubin Xubfc7faaf2016-11-22 15:18:32 +0000300 // Do not tie when the parent has no SID (but does have a screen lock).
301 // This can only happen during an upgrade path where SID is yet to be
302 // generated when the user unlocks for the first time.
303 try {
304 if (getGateKeeperService().getSecureUserId(parentId) == 0) {
305 return;
306 }
307 } catch (RemoteException e) {
308 Slog.e(TAG, "Failed to talk to GateKeeper service", e);
309 return;
310 }
Ricky Waidc283a82016-03-24 19:55:08 +0000311 if (DEBUG) Slog.v(TAG, "Tie managed profile to parent now!");
312 byte[] randomLockSeed = new byte[] {};
313 try {
314 randomLockSeed = SecureRandom.getInstance("SHA1PRNG").generateSeed(40);
Rich Canningsf64ec632019-02-21 12:40:36 -0800315 char[] newPasswordChars = HexEncoding.encode(randomLockSeed);
316 byte[] newPassword = new byte[newPasswordChars.length];
317 for (int i = 0; i < newPasswordChars.length; i++) {
318 newPassword[i] = (byte) newPasswordChars[i];
319 }
320 Arrays.fill(newPasswordChars, '\u0000');
Adrian Roos7374d3a2017-03-31 14:14:53 -0700321 final int quality = DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC;
Rubin Xu1de89b32016-11-30 20:03:13 +0000322 setLockCredentialInternal(newPassword, LockPatternUtils.CREDENTIAL_TYPE_PASSWORD,
Adrian Roos7374d3a2017-03-31 14:14:53 -0700323 managedUserPassword, quality, managedUserId);
Ricky Wai7b9eb412016-05-12 17:29:12 +0100324 // We store a private credential for the managed user that's unlocked by the primary
325 // account holder's credential. As such, the user will never be prompted to enter this
326 // password directly, so we always store a password.
Adrian Roos7374d3a2017-03-31 14:14:53 -0700327 setLong(LockPatternUtils.PASSWORD_TYPE_KEY, quality, managedUserId);
Zach Jange61672a2016-11-22 17:47:18 +0000328 tieProfileLockToParent(managedUserId, newPassword);
Rich Canningsf64ec632019-02-21 12:40:36 -0800329 Arrays.fill(newPassword, (byte) 0);
Ricky Waidc283a82016-03-24 19:55:08 +0000330 } catch (NoSuchAlgorithmException | RemoteException e) {
331 Slog.e(TAG, "Fail to tie managed profile", e);
332 // Nothing client can do to fix this issue, so we do not throw exception out
333 }
334 }
335
Rubin Xu0cbc19e2016-12-09 14:00:21 +0000336 static class Injector {
Jim Millerde1af082013-09-11 14:58:26 -0700337
Rubin Xu0cbc19e2016-12-09 14:00:21 +0000338 protected Context mContext;
339
340 public Injector(Context context) {
341 mContext = context;
342 }
343
344 public Context getContext() {
345 return mContext;
346 }
347
348 public Handler getHandler() {
349 return new Handler();
350 }
351
352 public LockSettingsStorage getStorage() {
353 final LockSettingsStorage storage = new LockSettingsStorage(mContext);
354 storage.setDatabaseOnCreateCallback(new LockSettingsStorage.Callback() {
355 @Override
356 public void initialize(SQLiteDatabase db) {
357 // Get the lockscreen default from a system property, if available
358 boolean lockScreenDisable = SystemProperties.getBoolean(
359 "ro.lockscreen.disable.default", false);
360 if (lockScreenDisable) {
361 storage.writeKeyValue(db, LockPatternUtils.DISABLE_LOCKSCREEN_KEY, "1", 0);
362 }
363 }
364 });
365 return storage;
366 }
367
368 public LockSettingsStrongAuth getStrongAuth() {
369 return new LockSettingsStrongAuth(mContext);
370 }
371
372 public SynchronizedStrongAuthTracker getStrongAuthTracker() {
373 return new SynchronizedStrongAuthTracker(mContext);
374 }
375
376 public IActivityManager getActivityManager() {
377 return ActivityManager.getService();
378 }
379
380 public LockPatternUtils getLockPatternUtils() {
381 return new LockPatternUtils(mContext);
382 }
383
384 public NotificationManager getNotificationManager() {
385 return (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
386 }
387
388 public UserManager getUserManager() {
389 return (UserManager) mContext.getSystemService(Context.USER_SERVICE);
390 }
391
Rubin Xu8b30ec32017-03-05 00:47:09 +0000392 public DevicePolicyManager getDevicePolicyManager() {
393 return (DevicePolicyManager) mContext.getSystemService(Context.DEVICE_POLICY_SERVICE);
394 }
395
Rubin Xu0cbc19e2016-12-09 14:00:21 +0000396 public KeyStore getKeyStore() {
397 return KeyStore.getInstance();
398 }
399
Dmitry Dementyev29b9de52018-01-31 16:09:32 -0800400 public RecoverableKeyStoreManager getRecoverableKeyStoreManager(KeyStore keyStore) {
401 return RecoverableKeyStoreManager.getInstance(mContext, keyStore);
Dmitry Dementyev1aa96132017-12-11 11:33:12 -0800402 }
403
Rubin Xu0cbc19e2016-12-09 14:00:21 +0000404 public IStorageManager getStorageManager() {
405 final IBinder service = ServiceManager.getService("mount");
406 if (service != null) {
407 return IStorageManager.Stub.asInterface(service);
408 }
409 return null;
410 }
Rubin Xu3bf722a2016-12-15 16:07:38 +0000411
412 public SyntheticPasswordManager getSyntheticPasswordManager(LockSettingsStorage storage) {
David Anderson28dea682019-02-20 13:37:51 -0800413 return new SyntheticPasswordManager(getContext(), storage, getUserManager(),
414 new PasswordSlotManager());
Rubin Xu3bf722a2016-12-15 16:07:38 +0000415 }
416
Kevin Chyncf1a62e2019-02-21 11:11:59 -0800417 public boolean hasBiometrics() {
418 return BiometricManager.hasBiometrics(mContext);
419 }
420
Rubin Xu3bf722a2016-12-15 16:07:38 +0000421 public int binderGetCallingUid() {
422 return Binder.getCallingUid();
423 }
David Anderson6ebc25b2019-02-12 16:25:56 -0800424
425 public boolean isGsiRunning() {
426 return SystemProperties.getInt(GSI_RUNNING_PROP, 0) > 0;
427 }
Rubin Xu0cbc19e2016-12-09 14:00:21 +0000428 }
429
430 public LockSettingsService(Context context) {
431 this(new Injector(context));
432 }
433
434 @VisibleForTesting
435 protected LockSettingsService(Injector injector) {
436 mInjector = injector;
437 mContext = injector.getContext();
438 mKeyStore = injector.getKeyStore();
Dmitry Dementyev29b9de52018-01-31 16:09:32 -0800439 mRecoverableKeyStoreManager = injector.getRecoverableKeyStoreManager(mKeyStore);
Rubin Xu0cbc19e2016-12-09 14:00:21 +0000440 mHandler = injector.getHandler();
441 mStrongAuth = injector.getStrongAuth();
442 mActivityManager = injector.getActivityManager();
443
444 mLockPatternUtils = injector.getLockPatternUtils();
Paul Lawrence945490c2014-03-27 16:37:28 +0000445 mFirstCallToVold = true;
Robin Leef0246a82014-08-13 09:50:25 +0100446
447 IntentFilter filter = new IntentFilter();
448 filter.addAction(Intent.ACTION_USER_ADDED);
Adrian Roos3dcae682014-10-29 14:43:56 +0100449 filter.addAction(Intent.ACTION_USER_STARTING);
Adrian Roosdb0f76e2015-01-07 22:19:38 +0100450 filter.addAction(Intent.ACTION_USER_REMOVED);
Rubin Xu0cbc19e2016-12-09 14:00:21 +0000451 injector.getContext().registerReceiverAsUser(mBroadcastReceiver, UserHandle.ALL, filter,
452 null, null);
Adrian Roos261d5ab2014-10-29 14:42:38 +0100453
Rubin Xu0cbc19e2016-12-09 14:00:21 +0000454 mStorage = injector.getStorage();
455 mNotificationManager = injector.getNotificationManager();
456 mUserManager = injector.getUserManager();
457 mStrongAuthTracker = injector.getStrongAuthTracker();
458 mStrongAuthTracker.register(mStrongAuth);
Rubin Xu3bf722a2016-12-15 16:07:38 +0000459
460 mSpManager = injector.getSyntheticPasswordManager(mStorage);
Rubin Xufcd49f92017-08-24 18:21:52 +0100461
462 LocalServices.addService(LockSettingsInternal.class, new LocalService());
Jim Miller4f93c582016-01-27 19:05:43 -0800463 }
464
465 /**
Rubin Xu1de89b32016-11-30 20:03:13 +0000466 * If the account is credential-encrypted, show notification requesting the user to unlock the
467 * device.
Jim Miller4f93c582016-01-27 19:05:43 -0800468 */
Andrew Scull85a63bc2016-10-24 13:47:47 +0100469 private void maybeShowEncryptionNotificationForUser(@UserIdInt int userId) {
470 final UserInfo user = mUserManager.getUserInfo(userId);
471 if (!user.isManagedProfile()) {
472 // When the user is locked, we communicate it loud-and-clear
473 // on the lockscreen; we only show a notification below for
474 // locked managed profiles.
475 return;
476 }
477
478 final UserHandle userHandle = user.getUserHandle();
Rubin Xua55b1682017-01-31 10:06:56 +0000479 final boolean isSecure = isUserSecure(userId);
Andrew Scull85a63bc2016-10-24 13:47:47 +0100480 if (isSecure && !mUserManager.isUserUnlockingOrUnlocked(userHandle)) {
481 UserInfo parent = mUserManager.getProfileParent(userId);
482 if (parent != null &&
483 mUserManager.isUserUnlockingOrUnlocked(parent.getUserHandle()) &&
484 !mUserManager.isQuietModeEnabled(userHandle)) {
485 // Only show notifications for managed profiles once their parent
486 // user is unlocked.
487 showEncryptionNotificationForProfile(userHandle);
Jim Miller4f93c582016-01-27 19:05:43 -0800488 }
Jim Miller4f93c582016-01-27 19:05:43 -0800489 }
490 }
491
Kenny Guyb1b30262016-02-09 16:02:35 +0000492 private void showEncryptionNotificationForProfile(UserHandle user) {
493 Resources r = mContext.getResources();
494 CharSequence title = r.getText(
495 com.android.internal.R.string.user_encrypted_title);
496 CharSequence message = r.getText(
497 com.android.internal.R.string.profile_encrypted_message);
498 CharSequence detail = r.getText(
499 com.android.internal.R.string.profile_encrypted_detail);
500
501 final KeyguardManager km = (KeyguardManager) mContext.getSystemService(KEYGUARD_SERVICE);
Rubin Xu1de89b32016-11-30 20:03:13 +0000502 final Intent unlockIntent = km.createConfirmDeviceCredentialIntent(null, null,
503 user.getIdentifier());
Kenny Guyb1b30262016-02-09 16:02:35 +0000504 if (unlockIntent == null) {
505 return;
506 }
Rubin Xu1de89b32016-11-30 20:03:13 +0000507 unlockIntent.setFlags(
508 Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
Kenny Guyb1b30262016-02-09 16:02:35 +0000509 PendingIntent intent = PendingIntent.getActivity(mContext, 0, unlockIntent,
510 PendingIntent.FLAG_UPDATE_CURRENT);
511
512 showEncryptionNotification(user, title, message, detail, intent);
513 }
514
Rubin Xu1de89b32016-11-30 20:03:13 +0000515 private void showEncryptionNotification(UserHandle user, CharSequence title,
516 CharSequence message, CharSequence detail, PendingIntent intent) {
Kenny Guyb1b30262016-02-09 16:02:35 +0000517 if (DEBUG) Slog.v(TAG, "showing encryption notification, user: " + user.getIdentifier());
Jeff Sharkey4a399362016-05-26 09:47:43 -0600518
519 // Suppress all notifications on non-FBE devices for now
520 if (!StorageManager.isFileEncryptedNativeOrEmulated()) return;
521
Geoffrey Pitschaf759c52017-02-15 09:35:38 -0500522 Notification notification =
523 new Notification.Builder(mContext, SystemNotificationChannels.SECURITY)
524 .setSmallIcon(com.android.internal.R.drawable.ic_user_secure)
525 .setWhen(0)
526 .setOngoing(true)
527 .setTicker(title)
528 .setColor(mContext.getColor(
529 com.android.internal.R.color.system_notification_accent_color))
530 .setContentTitle(title)
531 .setContentText(message)
532 .setSubText(detail)
533 .setVisibility(Notification.VISIBILITY_PUBLIC)
534 .setContentIntent(intent)
535 .build();
Chris Wren282cfef2017-03-27 15:01:44 -0400536 mNotificationManager.notifyAsUser(null, SystemMessage.NOTE_FBE_ENCRYPTED_NOTIFICATION,
537 notification, user);
Jim Miller4f93c582016-01-27 19:05:43 -0800538 }
539
Andrew Scull85a63bc2016-10-24 13:47:47 +0100540 private void hideEncryptionNotification(UserHandle userHandle) {
Rubin Xu1de89b32016-11-30 20:03:13 +0000541 if (DEBUG) Slog.v(TAG, "hide encryption notification, user: " + userHandle.getIdentifier());
Chris Wren282cfef2017-03-27 15:01:44 -0400542 mNotificationManager.cancelAsUser(null, SystemMessage.NOTE_FBE_ENCRYPTED_NOTIFICATION,
543 userHandle);
Jim Miller4f93c582016-01-27 19:05:43 -0800544 }
545
546 public void onCleanupUser(int userId) {
547 hideEncryptionNotification(new UserHandle(userId));
Rubin Xu0da89832018-03-26 14:35:34 +0100548 // User is stopped with its CE key evicted. Require strong auth next time to be able to
549 // unlock the user's storage. Use STRONG_AUTH_REQUIRED_AFTER_BOOT since stopping and
550 // restarting a user later is equivalent to rebooting the device.
551 requireStrongAuth(STRONG_AUTH_REQUIRED_AFTER_BOOT, userId);
Jim Miller4f93c582016-01-27 19:05:43 -0800552 }
553
Andrew Scull85a63bc2016-10-24 13:47:47 +0100554 public void onStartUser(final int userId) {
555 maybeShowEncryptionNotificationForUser(userId);
556 }
557
Pavel Grafov0acc4bf2017-08-23 12:20:54 +0100558 /**
559 * Check if profile got unlocked but the keystore is still locked. This happens on full disk
560 * encryption devices since the profile may not yet be running when we consider unlocking it
561 * during the normal flow. In this case unlock the keystore for the profile.
562 */
563 private void ensureProfileKeystoreUnlocked(int userId) {
564 final KeyStore ks = KeyStore.getInstance();
565 if (ks.state(userId) == KeyStore.State.LOCKED
566 && tiedManagedProfileReadyToUnlock(mUserManager.getUserInfo(userId))) {
567 Slog.i(TAG, "Managed profile got unlocked, will unlock its keystore");
568 try {
569 // If boot took too long and the password in vold got expired, parent keystore will
570 // be still locked, we ignore this case since the user will be prompted to unlock
571 // the device after boot.
572 unlockChildProfile(userId, true /* ignoreUserNotAuthenticated */);
573 } catch (RemoteException e) {
574 Slog.e(TAG, "Failed to unlock child profile");
575 }
576 }
577 }
578
Ricky Waib0cdf382016-05-16 17:28:04 +0100579 public void onUnlockUser(final int userId) {
Rubin Xua55b1682017-01-31 10:06:56 +0000580 // Perform tasks which require locks in LSS on a handler, as we are callbacks from
581 // ActivityManager.unlockUser()
582 mHandler.post(new Runnable() {
583 @Override
584 public void run() {
Pavel Grafov0acc4bf2017-08-23 12:20:54 +0100585 ensureProfileKeystoreUnlocked(userId);
Rubin Xua55b1682017-01-31 10:06:56 +0000586 // Hide notification first, as tie managed profile lock takes time
587 hideEncryptionNotification(new UserHandle(userId));
Ricky Waib0cdf382016-05-16 17:28:04 +0100588
Rubin Xua55b1682017-01-31 10:06:56 +0000589 // Now we have unlocked the parent user we should show notifications
590 // about any profiles that exist.
591 List<UserInfo> profiles = mUserManager.getProfiles(userId);
592 for (int i = 0; i < profiles.size(); i++) {
593 UserInfo profile = profiles.get(i);
594 final boolean isSecure = isUserSecure(profile.id);
595 if (isSecure && profile.isManagedProfile()) {
596 UserHandle userHandle = profile.getUserHandle();
597 if (!mUserManager.isUserUnlockingOrUnlocked(userHandle) &&
598 !mUserManager.isQuietModeEnabled(userHandle)) {
599 showEncryptionNotificationForProfile(userHandle);
600 }
601 }
602 }
603
604 if (mUserManager.getUserInfo(userId).isManagedProfile()) {
Ricky Waib0cdf382016-05-16 17:28:04 +0100605 tieManagedProfileLockIfNecessary(userId, null);
606 }
Andrew Scullf49794b2018-04-13 12:01:25 +0100607
608 // If the user doesn't have a credential, try and derive their secret for the
609 // AuthSecret HAL. The secret will have been enrolled if the user previously set a
610 // credential and still needs to be passed to the HAL once that credential is
611 // removed.
612 if (mUserManager.getUserInfo(userId).isPrimary() && !isUserSecure(userId)) {
613 tryDeriveAuthTokenForUnsecuredPrimaryUser(userId);
614 }
Kenny Guyb1b30262016-02-09 16:02:35 +0000615 }
Rubin Xua55b1682017-01-31 10:06:56 +0000616 });
Amith Yamasani52c489c2012-03-28 11:42:42 -0700617 }
618
Andrew Scullf49794b2018-04-13 12:01:25 +0100619 private void tryDeriveAuthTokenForUnsecuredPrimaryUser(@UserIdInt int userId) {
620 synchronized (mSpManager) {
621 // Make sure the user has a synthetic password to derive
622 if (!isSyntheticPasswordBasedCredentialLocked(userId)) {
623 return;
624 }
625
626 try {
627 final long handle = getSyntheticPasswordHandleLocked(userId);
Rich Canningsf64ec632019-02-21 12:40:36 -0800628 final byte[] noCredential = null;
Andrew Scullf49794b2018-04-13 12:01:25 +0100629 AuthenticationResult result =
630 mSpManager.unwrapPasswordBasedSyntheticPassword(
631 getGateKeeperService(), handle, noCredential, userId, null);
632 if (result.authToken != null) {
633 Slog.i(TAG, "Retrieved auth token for user " + userId);
634 onAuthTokenKnownForUser(userId, result.authToken);
635 } else {
636 Slog.e(TAG, "Auth token not available for user " + userId);
637 }
638 } catch (RemoteException e) {
639 Slog.e(TAG, "Failure retrieving auth token", e);
640 }
641 }
642 }
643
Robin Leef0246a82014-08-13 09:50:25 +0100644 private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
645 @Override
646 public void onReceive(Context context, Intent intent) {
Robin Lee1096cf82014-09-01 16:52:47 +0100647 if (Intent.ACTION_USER_ADDED.equals(intent.getAction())) {
Chad Brubaker83ce0952015-05-12 13:00:02 -0700648 // Notify keystore that a new user was added.
Robin Leef0246a82014-08-13 09:50:25 +0100649 final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, 0);
Amith Yamasanif11a5742016-06-16 08:20:07 -0700650 if (userHandle > UserHandle.USER_SYSTEM) {
651 removeUser(userHandle, /* unknownUser= */ true);
652 }
Robin Lee49d810c2014-09-23 13:50:22 +0100653 final KeyStore ks = KeyStore.getInstance();
Ricky Waidc283a82016-03-24 19:55:08 +0000654 final UserInfo parentInfo = mUserManager.getProfileParent(userHandle);
Chad Brubaker83ce0952015-05-12 13:00:02 -0700655 final int parentHandle = parentInfo != null ? parentInfo.id : -1;
656 ks.onUserAdded(userHandle, parentHandle);
Adrian Roos3dcae682014-10-29 14:43:56 +0100657 } else if (Intent.ACTION_USER_STARTING.equals(intent.getAction())) {
658 final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, 0);
659 mStorage.prefetchUser(userHandle);
Adrian Roosdb0f76e2015-01-07 22:19:38 +0100660 } else if (Intent.ACTION_USER_REMOVED.equals(intent.getAction())) {
661 final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, 0);
662 if (userHandle > 0) {
Amith Yamasanif11a5742016-06-16 08:20:07 -0700663 removeUser(userHandle, /* unknownUser= */ false);
Adrian Roosdb0f76e2015-01-07 22:19:38 +0100664 }
Robin Leef0246a82014-08-13 09:50:25 +0100665 }
666 }
667 };
668
Jim Miller4f93c582016-01-27 19:05:43 -0800669 @Override // binder interface
Amith Yamasani52c489c2012-03-28 11:42:42 -0700670 public void systemReady() {
Adrian Roosb953e182017-08-17 17:58:26 +0200671 if (mContext.checkCallingOrSelfPermission(PERMISSION) != PERMISSION_GRANTED) {
672 EventLog.writeEvent(0x534e4554, "28251513", getCallingUid(), ""); // SafetyNet
673 }
674 checkWritePermission(UserHandle.USER_SYSTEM);
Amith Yamasani52c489c2012-03-28 11:42:42 -0700675 migrateOldData();
Andres Morales301ea442015-04-17 09:15:47 -0700676 try {
677 getGateKeeperService();
Rubin Xu7b7424b2017-03-31 18:03:20 +0100678 mSpManager.initWeaverService();
Andres Morales301ea442015-04-17 09:15:47 -0700679 } catch (RemoteException e) {
680 Slog.e(TAG, "Failure retrieving IGateKeeperService", e);
681 }
Andrew Sculle6527c12018-01-05 18:33:58 +0000682 // Find the AuthSecret HAL
683 try {
684 mAuthSecretService = IAuthSecret.getService();
685 } catch (NoSuchElementException e) {
686 Slog.i(TAG, "Device doesn't implement AuthSecret HAL");
687 } catch (RemoteException e) {
688 Slog.w(TAG, "Failed to get AuthSecret HAL", e);
689 }
Adrian Roos7374d3a2017-03-31 14:14:53 -0700690 mDeviceProvisionedObserver.onSystemReady();
Xiaohui Chen7c696362015-09-16 09:56:14 -0700691 // TODO: maybe skip this for split system user mode.
692 mStorage.prefetchUser(UserHandle.USER_SYSTEM);
Amith Yamasani52c489c2012-03-28 11:42:42 -0700693 }
694
695 private void migrateOldData() {
Rubin Xufe354472017-11-21 12:05:06 +0000696 // These Settings moved before multi-user was enabled, so we only have to do it for the
697 // root user.
698 if (getString("migrated", null, 0) == null) {
699 final ContentResolver cr = mContext.getContentResolver();
700 for (String validSetting : VALID_SETTINGS) {
701 String value = Settings.Secure.getString(cr, validSetting);
702 if (value != null) {
703 setString(validSetting, value, 0);
Jim Miller187ec582013-04-15 18:27:54 -0700704 }
Amith Yamasani52c489c2012-03-28 11:42:42 -0700705 }
Rubin Xufe354472017-11-21 12:05:06 +0000706 // No need to move the password / pattern files. They're already in the right place.
707 setString("migrated", "true", 0);
708 Slog.i(TAG, "Migrated lock settings to new location");
709 }
Amith Yamasani52c489c2012-03-28 11:42:42 -0700710
Rubin Xufe354472017-11-21 12:05:06 +0000711 // These Settings changed after multi-user was enabled, hence need to be moved per user.
712 if (getString("migrated_user_specific", null, 0) == null) {
713 final ContentResolver cr = mContext.getContentResolver();
714 List<UserInfo> users = mUserManager.getUsers();
715 for (int user = 0; user < users.size(); user++) {
716 // Migrate owner info
717 final int userId = users.get(user).id;
718 final String OWNER_INFO = Secure.LOCK_SCREEN_OWNER_INFO;
719 String ownerInfo = Settings.Secure.getStringForUser(cr, OWNER_INFO, userId);
720 if (!TextUtils.isEmpty(ownerInfo)) {
721 setString(OWNER_INFO, ownerInfo, userId);
722 Settings.Secure.putStringForUser(cr, OWNER_INFO, "", userId);
Adrian Roos43830582015-04-21 16:04:43 -0700723 }
724
Rubin Xufe354472017-11-21 12:05:06 +0000725 // Migrate owner info enabled. Note there was a bug where older platforms only
726 // stored this value if the checkbox was toggled at least once. The code detects
727 // this case by handling the exception.
728 final String OWNER_INFO_ENABLED = Secure.LOCK_SCREEN_OWNER_INFO_ENABLED;
729 boolean enabled;
Ricky Wai97c8f8d2016-07-13 17:57:45 +0100730 try {
Rubin Xufe354472017-11-21 12:05:06 +0000731 int ivalue = Settings.Secure.getIntForUser(cr, OWNER_INFO_ENABLED, userId);
732 enabled = ivalue != 0;
733 setLong(OWNER_INFO_ENABLED, enabled ? 1 : 0, userId);
734 } catch (SettingNotFoundException e) {
735 // Setting was never stored. Store it if the string is not empty.
736 if (!TextUtils.isEmpty(ownerInfo)) {
737 setLong(OWNER_INFO_ENABLED, 1, userId);
Ricky Wai97c8f8d2016-07-13 17:57:45 +0100738 }
Rubin Xufe354472017-11-21 12:05:06 +0000739 }
740 Settings.Secure.putIntForUser(cr, OWNER_INFO_ENABLED, 0, userId);
741 }
742 // No need to move the password / pattern files. They're already in the right place.
743 setString("migrated_user_specific", "true", 0);
744 Slog.i(TAG, "Migrated per-user lock settings to new location");
745 }
746
747 // Migrates biometric weak such that the fallback mechanism becomes the primary.
748 if (getString("migrated_biometric_weak", null, 0) == null) {
749 List<UserInfo> users = mUserManager.getUsers();
750 for (int i = 0; i < users.size(); i++) {
751 int userId = users.get(i).id;
752 long type = getLong(LockPatternUtils.PASSWORD_TYPE_KEY,
753 DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED,
754 userId);
755 long alternateType = getLong(LockPatternUtils.PASSWORD_TYPE_ALTERNATE_KEY,
756 DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED,
757 userId);
758 if (type == DevicePolicyManager.PASSWORD_QUALITY_BIOMETRIC_WEAK) {
759 setLong(LockPatternUtils.PASSWORD_TYPE_KEY,
760 alternateType,
761 userId);
762 }
763 setLong(LockPatternUtils.PASSWORD_TYPE_ALTERNATE_KEY,
764 DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED,
765 userId);
766 }
767 setString("migrated_biometric_weak", "true", 0);
768 Slog.i(TAG, "Migrated biometric weak to use the fallback instead");
769 }
770
771 // Migrates lockscreen.disabled. Prior to M, the flag was ignored when more than one
772 // user was present on the system, so if we're upgrading to M and there is more than one
773 // user we disable the flag to remain consistent.
774 if (getString("migrated_lockscreen_disabled", null, 0) == null) {
775 final List<UserInfo> users = mUserManager.getUsers();
776 final int userCount = users.size();
777 int switchableUsers = 0;
778 for (int i = 0; i < userCount; i++) {
779 if (users.get(i).supportsSwitchTo()) {
780 switchableUsers++;
Ricky Wai97c8f8d2016-07-13 17:57:45 +0100781 }
Ricky Wai7b9eb412016-05-12 17:29:12 +0100782 }
Greg Plesureb2e4532016-11-02 17:10:27 -0400783
Rubin Xufe354472017-11-21 12:05:06 +0000784 if (switchableUsers > 1) {
Greg Plesureb2e4532016-11-02 17:10:27 -0400785 for (int i = 0; i < userCount; i++) {
786 int id = users.get(i).id;
Rubin Xufe354472017-11-21 12:05:06 +0000787
788 if (getBoolean(LockPatternUtils.DISABLE_LOCKSCREEN_KEY, false, id)) {
789 setBoolean(LockPatternUtils.DISABLE_LOCKSCREEN_KEY, false, id);
790 }
Greg Plesureb2e4532016-11-02 17:10:27 -0400791 }
Greg Plesureb2e4532016-11-02 17:10:27 -0400792 }
Rubin Xufe354472017-11-21 12:05:06 +0000793
794 setString("migrated_lockscreen_disabled", "true", 0);
795 Slog.i(TAG, "Migrated lockscreen disabled flag");
796 }
797
798 final List<UserInfo> users = mUserManager.getUsers();
799 for (int i = 0; i < users.size(); i++) {
800 final UserInfo userInfo = users.get(i);
801 if (userInfo.isManagedProfile() && mStorage.hasChildProfileLock(userInfo.id)) {
802 // When managed profile has a unified lock, the password quality stored has 2
803 // possibilities only.
804 // 1). PASSWORD_QUALITY_UNSPECIFIED, which is upgraded from dp2, and we are
805 // going to set it back to PASSWORD_QUALITY_ALPHANUMERIC.
806 // 2). PASSWORD_QUALITY_ALPHANUMERIC, which is the actual password quality for
807 // unified lock.
808 final long quality = getLong(LockPatternUtils.PASSWORD_TYPE_KEY,
809 DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED, userInfo.id);
810 if (quality == DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED) {
811 // Only possible when it's upgraded from nyc dp3
812 Slog.i(TAG, "Migrated tied profile lock type");
813 setLong(LockPatternUtils.PASSWORD_TYPE_KEY,
814 DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC, userInfo.id);
815 } else if (quality != DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC) {
816 // It should not happen
817 Slog.e(TAG, "Invalid tied profile lock type: " + quality);
818 }
819 }
820 try {
821 final String alias = LockPatternUtils.PROFILE_KEY_NAME_ENCRYPT + userInfo.id;
822 java.security.KeyStore keyStore =
823 java.security.KeyStore.getInstance("AndroidKeyStore");
824 keyStore.load(null);
825 if (keyStore.containsAlias(alias)) {
826 keyStore.deleteEntry(alias);
827 }
828 } catch (KeyStoreException | NoSuchAlgorithmException |
829 CertificateException | IOException e) {
830 Slog.e(TAG, "Unable to remove tied profile key", e);
831 }
832 }
833
834 boolean isWatch = mContext.getPackageManager().hasSystemFeature(
835 PackageManager.FEATURE_WATCH);
836 // Wear used to set DISABLE_LOCKSCREEN to 'true', but because Wear now allows accounts
837 // and device management the lockscreen must be re-enabled now for users that upgrade.
838 if (isWatch && getString("migrated_wear_lockscreen_disabled", null, 0) == null) {
839 final int userCount = users.size();
840 for (int i = 0; i < userCount; i++) {
841 int id = users.get(i).id;
842 setBoolean(LockPatternUtils.DISABLE_LOCKSCREEN_KEY, false, id);
843 }
844 setString("migrated_wear_lockscreen_disabled", "true", 0);
845 Slog.i(TAG, "Migrated lockscreen_disabled for Wear devices");
Amith Yamasani52c489c2012-03-28 11:42:42 -0700846 }
847 }
848
Adrian Roos60dcbbf2017-08-08 16:19:33 +0200849 private void migrateOldDataAfterSystemReady() {
850 try {
851 // Migrate the FRP credential to the persistent data block
Adrian Roos2adc2632017-09-05 17:01:42 +0200852 if (LockPatternUtils.frpCredentialEnabled(mContext)
853 && !getBoolean("migrated_frp", false, 0)) {
Adrian Roos60dcbbf2017-08-08 16:19:33 +0200854 migrateFrpCredential();
855 setBoolean("migrated_frp", true, 0);
856 Slog.i(TAG, "Migrated migrated_frp.");
857 }
858 } catch (RemoteException e) {
859 Slog.e(TAG, "Unable to migrateOldDataAfterSystemReady", e);
860 }
861 }
862
863 /**
864 * Migrate the credential for the FRP credential owner user if the following are satisfied:
865 * - the user has a secure credential
866 * - the FRP credential is not set up
867 * - the credential is based on a synthetic password.
868 */
869 private void migrateFrpCredential() throws RemoteException {
870 if (mStorage.readPersistentDataBlock() != PersistentData.NONE) {
871 return;
872 }
873 for (UserInfo userInfo : mUserManager.getUsers()) {
Adrian Roos2adc2632017-09-05 17:01:42 +0200874 if (userOwnsFrpCredential(mContext, userInfo) && isUserSecure(userInfo.id)) {
Adrian Roos60dcbbf2017-08-08 16:19:33 +0200875 synchronized (mSpManager) {
876 if (isSyntheticPasswordBasedCredentialLocked(userInfo.id)) {
877 int actualQuality = (int) getLong(LockPatternUtils.PASSWORD_TYPE_KEY,
878 DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED, userInfo.id);
879
880 mSpManager.migrateFrpPasswordLocked(
881 getSyntheticPasswordHandleLocked(userInfo.id),
882 userInfo,
883 redactActualQualityToMostLenientEquivalentQuality(actualQuality));
884 }
885 }
886 return;
887 }
888 }
889 }
890
891 /**
892 * Returns the lowest password quality that still presents the same UI for entering it.
893 *
894 * For the FRP credential, we do not want to leak the actual quality of the password, only what
895 * kind of UI it requires. However, when migrating, we only know the actual quality, not the
896 * originally requested quality; since this is only used to determine what input variant to
897 * present to the user, we just assume the lowest possible quality was requested.
898 */
899 private int redactActualQualityToMostLenientEquivalentQuality(int quality) {
900 switch (quality) {
901 case DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC:
902 case DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC:
903 case DevicePolicyManager.PASSWORD_QUALITY_COMPLEX:
904 return DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC;
905 case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC:
906 case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC_COMPLEX:
907 return DevicePolicyManager.PASSWORD_QUALITY_NUMERIC;
908 case DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED:
909 case DevicePolicyManager.PASSWORD_QUALITY_SOMETHING:
910 case DevicePolicyManager.PASSWORD_QUALITY_MANAGED:
911 case DevicePolicyManager.PASSWORD_QUALITY_BIOMETRIC_WEAK:
912 default:
913 return quality;
914 }
915 }
916
Jim Miller5ecd8112013-01-09 18:50:26 -0800917 private final void checkWritePermission(int userId) {
Jim Miller505329b2013-11-08 13:25:36 -0800918 mContext.enforceCallingOrSelfPermission(PERMISSION, "LockSettingsWrite");
Amith Yamasani52c489c2012-03-28 11:42:42 -0700919 }
920
Jim Miller5ecd8112013-01-09 18:50:26 -0800921 private final void checkPasswordReadPermission(int userId) {
Jim Miller505329b2013-11-08 13:25:36 -0800922 mContext.enforceCallingOrSelfPermission(PERMISSION, "LockSettingsRead");
Amith Yamasani52c489c2012-03-28 11:42:42 -0700923 }
924
Adrian Roosb953e182017-08-17 17:58:26 +0200925 private final void checkPasswordHavePermission(int userId) {
926 if (mContext.checkCallingOrSelfPermission(PERMISSION) != PERMISSION_GRANTED) {
927 EventLog.writeEvent(0x534e4554, "28251513", getCallingUid(), ""); // SafetyNet
928 }
929 mContext.enforceCallingOrSelfPermission(PERMISSION, "LockSettingsHave");
930 }
931
Jim Miller158fe192013-04-17 15:23:55 -0700932 private final void checkReadPermission(String requestedKey, int userId) {
Amith Yamasani52c489c2012-03-28 11:42:42 -0700933 final int callingUid = Binder.getCallingUid();
Adrian Roos001b00d2015-02-24 17:08:48 +0100934
Svetoslav Ganov6d2c0e52015-06-23 16:33:36 +0000935 for (int i = 0; i < READ_CONTACTS_PROTECTED_SETTINGS.length; i++) {
936 String key = READ_CONTACTS_PROTECTED_SETTINGS[i];
937 if (key.equals(requestedKey) && mContext.checkCallingOrSelfPermission(READ_CONTACTS)
Jim Miller158fe192013-04-17 15:23:55 -0700938 != PackageManager.PERMISSION_GRANTED) {
939 throw new SecurityException("uid=" + callingUid
Svetoslav Ganov6d2c0e52015-06-23 16:33:36 +0000940 + " needs permission " + READ_CONTACTS + " to read "
Jim Miller158fe192013-04-17 15:23:55 -0700941 + requestedKey + " for user " + userId);
942 }
Amith Yamasani52c489c2012-03-28 11:42:42 -0700943 }
Adrian Roos001b00d2015-02-24 17:08:48 +0100944
945 for (int i = 0; i < READ_PASSWORD_PROTECTED_SETTINGS.length; i++) {
946 String key = READ_PASSWORD_PROTECTED_SETTINGS[i];
947 if (key.equals(requestedKey) && mContext.checkCallingOrSelfPermission(PERMISSION)
948 != PackageManager.PERMISSION_GRANTED) {
949 throw new SecurityException("uid=" + callingUid
950 + " needs permission " + PERMISSION + " to read "
951 + requestedKey + " for user " + userId);
952 }
953 }
Amith Yamasani52c489c2012-03-28 11:42:42 -0700954 }
955
956 @Override
Rubin Xufe354472017-11-21 12:05:06 +0000957 public boolean getSeparateProfileChallengeEnabled(int userId) {
Ricky Wai7f405f12016-05-31 12:05:05 +0100958 checkReadPermission(SEPARATE_PROFILE_CHALLENGE_KEY, userId);
Ricky Waidc283a82016-03-24 19:55:08 +0000959 synchronized (mSeparateChallengeLock) {
960 return getBoolean(SEPARATE_PROFILE_CHALLENGE_KEY, false, userId);
961 }
962 }
963
964 @Override
965 public void setSeparateProfileChallengeEnabled(int userId, boolean enabled,
Rich Canningsf64ec632019-02-21 12:40:36 -0800966 byte[] managedUserPassword) {
Ricky Wai7f405f12016-05-31 12:05:05 +0100967 checkWritePermission(userId);
Lenka Trochtova66c492a2018-12-06 11:29:21 +0100968 if (!mLockPatternUtils.hasSecureLockScreen()) {
969 throw new UnsupportedOperationException(
970 "This operation requires secure lock screen feature.");
971 }
Ricky Waidc283a82016-03-24 19:55:08 +0000972 synchronized (mSeparateChallengeLock) {
Pavel Grafov28939982017-10-03 15:11:52 +0100973 setSeparateProfileChallengeEnabledLocked(userId, enabled, managedUserPassword);
Ricky Waidc283a82016-03-24 19:55:08 +0000974 }
Pavel Grafov28939982017-10-03 15:11:52 +0100975 notifySeparateProfileChallengeChanged(userId);
976 }
977
978 @GuardedBy("mSeparateChallengeLock")
Rich Canningsf64ec632019-02-21 12:40:36 -0800979 private void setSeparateProfileChallengeEnabledLocked(@UserIdInt int userId,
980 boolean enabled, byte[] managedUserPassword) {
Pavel Grafovf10ae7e2018-06-25 12:13:38 +0100981 final boolean old = getBoolean(SEPARATE_PROFILE_CHALLENGE_KEY, false, userId);
Pavel Grafov28939982017-10-03 15:11:52 +0100982 setBoolean(SEPARATE_PROFILE_CHALLENGE_KEY, enabled, userId);
Pavel Grafovf10ae7e2018-06-25 12:13:38 +0100983 try {
984 if (enabled) {
985 mStorage.removeChildProfileLock(userId);
986 removeKeystoreProfileKey(userId);
987 } else {
988 tieManagedProfileLockIfNecessary(userId, managedUserPassword);
989 }
990 } catch (IllegalStateException e) {
991 setBoolean(SEPARATE_PROFILE_CHALLENGE_KEY, old, userId);
992 throw e;
Pavel Grafov28939982017-10-03 15:11:52 +0100993 }
994 }
995
996 private void notifySeparateProfileChallengeChanged(int userId) {
Andrew Scull7f4ff4c2018-01-05 18:33:58 +0000997 final DevicePolicyManagerInternal dpmi = LocalServices.getService(
998 DevicePolicyManagerInternal.class);
999 if (dpmi != null) {
1000 dpmi.reportSeparateProfileChallengeChanged(userId);
1001 }
Ricky Waidc283a82016-03-24 19:55:08 +00001002 }
1003
1004 @Override
Rubin Xufe354472017-11-21 12:05:06 +00001005 public void setBoolean(String key, boolean value, int userId) {
Amith Yamasani52c489c2012-03-28 11:42:42 -07001006 checkWritePermission(userId);
Adrian Roos261d5ab2014-10-29 14:42:38 +01001007 setStringUnchecked(key, userId, value ? "1" : "0");
Amith Yamasani52c489c2012-03-28 11:42:42 -07001008 }
1009
1010 @Override
Rubin Xufe354472017-11-21 12:05:06 +00001011 public void setLong(String key, long value, int userId) {
Amith Yamasani52c489c2012-03-28 11:42:42 -07001012 checkWritePermission(userId);
Adrian Roos261d5ab2014-10-29 14:42:38 +01001013 setStringUnchecked(key, userId, Long.toString(value));
Amith Yamasani52c489c2012-03-28 11:42:42 -07001014 }
1015
1016 @Override
Rubin Xufe354472017-11-21 12:05:06 +00001017 public void setString(String key, String value, int userId) {
Amith Yamasani52c489c2012-03-28 11:42:42 -07001018 checkWritePermission(userId);
Adrian Roos261d5ab2014-10-29 14:42:38 +01001019 setStringUnchecked(key, userId, value);
1020 }
Amith Yamasani52c489c2012-03-28 11:42:42 -07001021
Adrian Roos261d5ab2014-10-29 14:42:38 +01001022 private void setStringUnchecked(String key, int userId, String value) {
Adrian Roos7374d3a2017-03-31 14:14:53 -07001023 Preconditions.checkArgument(userId != USER_FRP, "cannot store lock settings for FRP user");
1024
Adrian Roos261d5ab2014-10-29 14:42:38 +01001025 mStorage.writeKeyValue(key, value, userId);
Amith Yamasani072543f2015-02-13 11:09:45 -08001026 if (ArrayUtils.contains(SETTINGS_TO_BACKUP, key)) {
1027 BackupManager.dataChanged("com.android.providers.settings");
1028 }
Amith Yamasani52c489c2012-03-28 11:42:42 -07001029 }
1030
1031 @Override
Adrian Roos60dcbbf2017-08-08 16:19:33 +02001032 public boolean getBoolean(String key, boolean defaultValue, int userId) {
Jim Miller158fe192013-04-17 15:23:55 -07001033 checkReadPermission(key, userId);
Adrian Roos9dd16eb2015-01-08 16:20:49 +01001034 String value = getStringUnchecked(key, null, userId);
Amith Yamasani52c489c2012-03-28 11:42:42 -07001035 return TextUtils.isEmpty(value) ?
1036 defaultValue : (value.equals("1") || value.equals("true"));
1037 }
1038
1039 @Override
Adrian Roos60dcbbf2017-08-08 16:19:33 +02001040 public long getLong(String key, long defaultValue, int userId) {
Jim Miller158fe192013-04-17 15:23:55 -07001041 checkReadPermission(key, userId);
Adrian Roos9dd16eb2015-01-08 16:20:49 +01001042 String value = getStringUnchecked(key, null, userId);
Amith Yamasani52c489c2012-03-28 11:42:42 -07001043 return TextUtils.isEmpty(value) ? defaultValue : Long.parseLong(value);
1044 }
1045
1046 @Override
Adrian Roos60dcbbf2017-08-08 16:19:33 +02001047 public String getString(String key, String defaultValue, int userId) {
Jim Miller158fe192013-04-17 15:23:55 -07001048 checkReadPermission(key, userId);
Adrian Roos9dd16eb2015-01-08 16:20:49 +01001049 return getStringUnchecked(key, defaultValue, userId);
1050 }
1051
1052 public String getStringUnchecked(String key, String defaultValue, int userId) {
1053 if (Settings.Secure.LOCK_PATTERN_ENABLED.equals(key)) {
Adrian Roos7811d9f2015-07-27 15:10:13 -07001054 long ident = Binder.clearCallingIdentity();
1055 try {
1056 return mLockPatternUtils.isLockPatternEnabled(userId) ? "1" : "0";
1057 } finally {
1058 Binder.restoreCallingIdentity(ident);
1059 }
Adrian Roos9dd16eb2015-01-08 16:20:49 +01001060 }
1061
Adrian Roos7374d3a2017-03-31 14:14:53 -07001062 if (userId == USER_FRP) {
1063 return getFrpStringUnchecked(key);
1064 }
1065
Bryce Lee46145962015-12-14 14:39:10 -08001066 if (LockPatternUtils.LEGACY_LOCK_PATTERN_ENABLED.equals(key)) {
1067 key = Settings.Secure.LOCK_PATTERN_ENABLED;
1068 }
1069
Adrian Roos261d5ab2014-10-29 14:42:38 +01001070 return mStorage.readKeyValue(key, defaultValue, userId);
Amith Yamasani52c489c2012-03-28 11:42:42 -07001071 }
1072
Adrian Roos7374d3a2017-03-31 14:14:53 -07001073 private String getFrpStringUnchecked(String key) {
1074 if (LockPatternUtils.PASSWORD_TYPE_KEY.equals(key)) {
1075 return String.valueOf(readFrpPasswordQuality());
1076 }
1077 return null;
1078 }
1079
1080 private int readFrpPasswordQuality() {
1081 return mStorage.readPersistentDataBlock().qualityForUi;
1082 }
1083
Adrian Roos4f788452014-05-22 20:45:59 +02001084 @Override
Amith Yamasani52c489c2012-03-28 11:42:42 -07001085 public boolean havePassword(int userId) throws RemoteException {
Adrian Roosb953e182017-08-17 17:58:26 +02001086 checkPasswordHavePermission(userId);
Rubin Xu3bf722a2016-12-15 16:07:38 +00001087 synchronized (mSpManager) {
1088 if (isSyntheticPasswordBasedCredentialLocked(userId)) {
1089 long handle = getSyntheticPasswordHandleLocked(userId);
1090 return mSpManager.getCredentialType(handle, userId) ==
1091 LockPatternUtils.CREDENTIAL_TYPE_PASSWORD;
1092 }
1093 }
Amith Yamasani52c489c2012-03-28 11:42:42 -07001094 // Do we need a permissions check here?
Adrian Roos261d5ab2014-10-29 14:42:38 +01001095 return mStorage.hasPassword(userId);
Amith Yamasani52c489c2012-03-28 11:42:42 -07001096 }
1097
1098 @Override
1099 public boolean havePattern(int userId) throws RemoteException {
Adrian Roosb953e182017-08-17 17:58:26 +02001100 checkPasswordHavePermission(userId);
Rubin Xu3bf722a2016-12-15 16:07:38 +00001101 synchronized (mSpManager) {
1102 if (isSyntheticPasswordBasedCredentialLocked(userId)) {
1103 long handle = getSyntheticPasswordHandleLocked(userId);
1104 return mSpManager.getCredentialType(handle, userId) ==
1105 LockPatternUtils.CREDENTIAL_TYPE_PATTERN;
1106 }
1107 }
Amith Yamasani52c489c2012-03-28 11:42:42 -07001108 // Do we need a permissions check here?
Adrian Roos261d5ab2014-10-29 14:42:38 +01001109 return mStorage.hasPattern(userId);
Amith Yamasani52c489c2012-03-28 11:42:42 -07001110 }
1111
Rubin Xua55b1682017-01-31 10:06:56 +00001112 private boolean isUserSecure(int userId) {
Rubin Xu3bf722a2016-12-15 16:07:38 +00001113 synchronized (mSpManager) {
Rubin Xufcd49f92017-08-24 18:21:52 +01001114 if (isSyntheticPasswordBasedCredentialLocked(userId)) {
1115 long handle = getSyntheticPasswordHandleLocked(userId);
1116 return mSpManager.getCredentialType(handle, userId) !=
1117 LockPatternUtils.CREDENTIAL_TYPE_NONE;
Rubin Xu3bf722a2016-12-15 16:07:38 +00001118 }
1119 }
Rubin Xua55b1682017-01-31 10:06:56 +00001120 return mStorage.hasCredential(userId);
1121 }
1122
Rich Canningsf64ec632019-02-21 12:40:36 -08001123 private void setKeystorePassword(byte[] password, int userHandle) {
Robin Leef0246a82014-08-13 09:50:25 +01001124 final KeyStore ks = KeyStore.getInstance();
Rich Canningsf64ec632019-02-21 12:40:36 -08001125 // TODO(b/120484642): Update keystore to accept byte[] passwords
1126 String passwordString = password == null ? null : new String(password);
1127 ks.onUserPasswordChanged(userHandle, passwordString);
Chad Brubakera91a8502015-05-07 10:02:22 -07001128 }
1129
Rich Canningsf64ec632019-02-21 12:40:36 -08001130 private void unlockKeystore(byte[] password, int userHandle) {
Ricky Waidc283a82016-03-24 19:55:08 +00001131 if (DEBUG) Slog.v(TAG, "Unlock keystore for user: " + userHandle);
Rich Canningsf64ec632019-02-21 12:40:36 -08001132 // TODO(b/120484642): Update keystore to accept byte[] passwords
1133 String passwordString = password == null ? null : new String(password);
Chad Brubakera91a8502015-05-07 10:02:22 -07001134 final KeyStore ks = KeyStore.getInstance();
Rich Canningsf64ec632019-02-21 12:40:36 -08001135 ks.unlock(userHandle, passwordString);
Ricky Waidc283a82016-03-24 19:55:08 +00001136 }
Chad Brubakera91a8502015-05-07 10:02:22 -07001137
Rubin Xu0cbc19e2016-12-09 14:00:21 +00001138 @VisibleForTesting
Rich Canningsf64ec632019-02-21 12:40:36 -08001139 protected byte[] getDecryptedPasswordForTiedProfile(int userId)
Ricky Waidc283a82016-03-24 19:55:08 +00001140 throws KeyStoreException, UnrecoverableKeyException,
1141 NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
1142 InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException,
1143 CertificateException, IOException {
Rich Canningsf64ec632019-02-21 12:40:36 -08001144 if (DEBUG) Slog.v(TAG, "Get child profile decrypted key");
Ricky Waidc283a82016-03-24 19:55:08 +00001145 byte[] storedData = mStorage.readChildProfileLock(userId);
1146 if (storedData == null) {
1147 throw new FileNotFoundException("Child profile lock file not found");
1148 }
1149 byte[] iv = Arrays.copyOfRange(storedData, 0, PROFILE_KEY_IV_SIZE);
1150 byte[] encryptedPassword = Arrays.copyOfRange(storedData, PROFILE_KEY_IV_SIZE,
1151 storedData.length);
1152 byte[] decryptionResult;
1153 java.security.KeyStore keyStore = java.security.KeyStore.getInstance("AndroidKeyStore");
1154 keyStore.load(null);
1155 SecretKey decryptionKey = (SecretKey) keyStore.getKey(
Ricky Waid3982442016-05-24 19:27:08 +01001156 LockPatternUtils.PROFILE_KEY_NAME_DECRYPT + userId, null);
Ricky Waidc283a82016-03-24 19:55:08 +00001157
1158 Cipher cipher = Cipher.getInstance(KeyProperties.KEY_ALGORITHM_AES + "/"
1159 + KeyProperties.BLOCK_MODE_GCM + "/" + KeyProperties.ENCRYPTION_PADDING_NONE);
1160
1161 cipher.init(Cipher.DECRYPT_MODE, decryptionKey, new GCMParameterSpec(128, iv));
1162 decryptionResult = cipher.doFinal(encryptedPassword);
Rich Canningsf64ec632019-02-21 12:40:36 -08001163 return decryptionResult;
Ricky Waidc283a82016-03-24 19:55:08 +00001164 }
1165
Pavel Grafov0acc4bf2017-08-23 12:20:54 +01001166 private void unlockChildProfile(int profileHandle, boolean ignoreUserNotAuthenticated)
1167 throws RemoteException {
Ricky Waidc283a82016-03-24 19:55:08 +00001168 try {
Rubin Xu1de89b32016-11-30 20:03:13 +00001169 doVerifyCredential(getDecryptedPasswordForTiedProfile(profileHandle),
1170 LockPatternUtils.CREDENTIAL_TYPE_PASSWORD,
1171 false, 0 /* no challenge */, profileHandle, null /* progressCallback */);
Ricky Waidc283a82016-03-24 19:55:08 +00001172 } catch (UnrecoverableKeyException | InvalidKeyException | KeyStoreException
1173 | NoSuchAlgorithmException | NoSuchPaddingException
1174 | InvalidAlgorithmParameterException | IllegalBlockSizeException
1175 | BadPaddingException | CertificateException | IOException e) {
1176 if (e instanceof FileNotFoundException) {
1177 Slog.i(TAG, "Child profile key not found");
Pavel Grafov0acc4bf2017-08-23 12:20:54 +01001178 } else if (ignoreUserNotAuthenticated && e instanceof UserNotAuthenticatedException) {
1179 Slog.i(TAG, "Parent keystore seems locked, ignoring");
Clara Bayarri0a587d22016-02-23 14:49:41 -08001180 } else {
Ricky Waidc283a82016-03-24 19:55:08 +00001181 Slog.e(TAG, "Failed to decrypt child profile key", e);
Clara Bayarri0a587d22016-02-23 14:49:41 -08001182 }
Jim Millerde1af082013-09-11 14:58:26 -07001183 }
1184 }
1185
Paul Crowleyfaeb3eb2016-02-08 15:58:29 +00001186 private void unlockUser(int userId, byte[] token, byte[] secret) {
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06001187 // TODO: make this method fully async so we can update UI with progress strings
1188 final CountDownLatch latch = new CountDownLatch(1);
1189 final IProgressListener listener = new IProgressListener.Stub() {
1190 @Override
1191 public void onStarted(int id, Bundle extras) throws RemoteException {
Jeff Sharkeyfd241082016-04-19 15:58:24 -06001192 Log.d(TAG, "unlockUser started");
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06001193 }
1194
1195 @Override
1196 public void onProgress(int id, int progress, Bundle extras) throws RemoteException {
Jeff Sharkeyfd241082016-04-19 15:58:24 -06001197 Log.d(TAG, "unlockUser progress " + progress);
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06001198 }
1199
1200 @Override
1201 public void onFinished(int id, Bundle extras) throws RemoteException {
Jeff Sharkeyfd241082016-04-19 15:58:24 -06001202 Log.d(TAG, "unlockUser finished");
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06001203 latch.countDown();
1204 }
1205 };
1206
Jeff Sharkey8924e872015-11-30 12:52:10 -07001207 try {
Rubin Xu0cbc19e2016-12-09 14:00:21 +00001208 mActivityManager.unlockUser(userId, token, secret, listener);
Jeff Sharkey8924e872015-11-30 12:52:10 -07001209 } catch (RemoteException e) {
1210 throw e.rethrowAsRuntimeException();
1211 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06001212
1213 try {
1214 latch.await(15, TimeUnit.SECONDS);
1215 } catch (InterruptedException e) {
1216 Thread.currentThread().interrupt();
1217 }
Ricky Waidc283a82016-03-24 19:55:08 +00001218 try {
1219 if (!mUserManager.getUserInfo(userId).isManagedProfile()) {
1220 final List<UserInfo> profiles = mUserManager.getProfiles(userId);
1221 for (UserInfo pi : profiles) {
1222 // Unlock managed profile with unified lock
Pavel Grafov0acc4bf2017-08-23 12:20:54 +01001223 if (tiedManagedProfileReadyToUnlock(pi)) {
1224 unlockChildProfile(pi.id, false /* ignoreUserNotAuthenticated */);
Ricky Waidc283a82016-03-24 19:55:08 +00001225 }
1226 }
1227 }
1228 } catch (RemoteException e) {
1229 Log.d(TAG, "Failed to unlock child profile", e);
1230 }
Jeff Sharkey8924e872015-11-30 12:52:10 -07001231 }
Amith Yamasani52c489c2012-03-28 11:42:42 -07001232
Pavel Grafov0acc4bf2017-08-23 12:20:54 +01001233 private boolean tiedManagedProfileReadyToUnlock(UserInfo userInfo) {
1234 return userInfo.isManagedProfile()
1235 && !mLockPatternUtils.isSeparateProfileChallengeEnabled(userInfo.id)
1236 && mStorage.hasChildProfileLock(userInfo.id)
1237 && mUserManager.isUserRunning(userInfo.id);
1238 }
1239
Rich Canningsf64ec632019-02-21 12:40:36 -08001240 private Map<Integer, byte[]> getDecryptedPasswordsForAllTiedProfiles(int userId) {
Rubin Xua55b1682017-01-31 10:06:56 +00001241 if (mUserManager.getUserInfo(userId).isManagedProfile()) {
1242 return null;
Andres Morales8fa56652015-03-31 09:19:50 -07001243 }
Rich Canningsf64ec632019-02-21 12:40:36 -08001244 Map<Integer, byte[]> result = new ArrayMap<Integer, byte[]>();
Rubin Xua55b1682017-01-31 10:06:56 +00001245 final List<UserInfo> profiles = mUserManager.getProfiles(userId);
1246 final int size = profiles.size();
1247 for (int i = 0; i < size; i++) {
1248 final UserInfo profile = profiles.get(i);
1249 if (!profile.isManagedProfile()) {
1250 continue;
1251 }
1252 final int managedUserId = profile.id;
1253 if (mLockPatternUtils.isSeparateProfileChallengeEnabled(managedUserId)) {
1254 continue;
1255 }
1256 try {
Rubin Xu4f988c92017-09-12 16:25:26 +01001257 result.put(managedUserId, getDecryptedPasswordForTiedProfile(managedUserId));
Rubin Xua55b1682017-01-31 10:06:56 +00001258 } catch (KeyStoreException | UnrecoverableKeyException | NoSuchAlgorithmException
1259 | NoSuchPaddingException | InvalidKeyException
1260 | InvalidAlgorithmParameterException | IllegalBlockSizeException
1261 | BadPaddingException | CertificateException | IOException e) {
Rubin Xu4f988c92017-09-12 16:25:26 +01001262 Slog.e(TAG, "getDecryptedPasswordsForAllTiedProfiles failed for user " +
1263 managedUserId, e);
Rubin Xua55b1682017-01-31 10:06:56 +00001264 }
1265 }
1266 return result;
Amith Yamasani52c489c2012-03-28 11:42:42 -07001267 }
1268
Rubin Xua55b1682017-01-31 10:06:56 +00001269 /**
1270 * Synchronize all profile's work challenge of the given user if it's unified: tie or clear them
1271 * depending on the parent user's secure state.
1272 *
1273 * When clearing tied work challenges, a pre-computed password table for profiles are required,
1274 * since changing password for profiles requires existing password, and existing passwords can
1275 * only be computed before the parent user's password is cleared.
1276 *
1277 * Strictly this is a recursive function, since setLockCredentialInternal ends up calling this
1278 * method again on profiles. However the recursion is guaranteed to terminate as this method
1279 * terminates when the user is a managed profile.
1280 */
1281 private void synchronizeUnifiedWorkChallengeForProfiles(int userId,
Rich Canningsf64ec632019-02-21 12:40:36 -08001282 Map<Integer, byte[]> profilePasswordMap) throws RemoteException {
Ricky Waidc283a82016-03-24 19:55:08 +00001283 if (mUserManager.getUserInfo(userId).isManagedProfile()) {
1284 return;
1285 }
Rubin Xua55b1682017-01-31 10:06:56 +00001286 final boolean isSecure = isUserSecure(userId);
Ricky Waidc283a82016-03-24 19:55:08 +00001287 final List<UserInfo> profiles = mUserManager.getProfiles(userId);
1288 final int size = profiles.size();
1289 for (int i = 0; i < size; i++) {
1290 final UserInfo profile = profiles.get(i);
1291 if (profile.isManagedProfile()) {
1292 final int managedUserId = profile.id;
1293 if (mLockPatternUtils.isSeparateProfileChallengeEnabled(managedUserId)) {
1294 continue;
1295 }
1296 if (isSecure) {
1297 tieManagedProfileLockIfNecessary(managedUserId, null);
1298 } else {
Rubin Xua55b1682017-01-31 10:06:56 +00001299 // We use cached work profile password computed before clearing the parent's
1300 // credential, otherwise they get lost
1301 if (profilePasswordMap != null && profilePasswordMap.containsKey(managedUserId)) {
1302 setLockCredentialInternal(null, LockPatternUtils.CREDENTIAL_TYPE_NONE,
Adrian Roos7374d3a2017-03-31 14:14:53 -07001303 profilePasswordMap.get(managedUserId),
1304 DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED, managedUserId);
Rubin Xua55b1682017-01-31 10:06:56 +00001305 } else {
1306 Slog.wtf(TAG, "clear tied profile challenges, but no password supplied.");
1307 // Supplying null here would lead to untrusted credential change
1308 setLockCredentialInternal(null, LockPatternUtils.CREDENTIAL_TYPE_NONE, null,
Adrian Roos7374d3a2017-03-31 14:14:53 -07001309 DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED, managedUserId);
Rubin Xua55b1682017-01-31 10:06:56 +00001310 }
Ricky Waidc283a82016-03-24 19:55:08 +00001311 mStorage.removeChildProfileLock(managedUserId);
1312 removeKeystoreProfileKey(managedUserId);
1313 }
1314 }
1315 }
1316 }
Andres Morales8fa56652015-03-31 09:19:50 -07001317
Ricky Waidc283a82016-03-24 19:55:08 +00001318 private boolean isManagedProfileWithUnifiedLock(int userId) {
1319 return mUserManager.getUserInfo(userId).isManagedProfile()
1320 && !mLockPatternUtils.isSeparateProfileChallengeEnabled(userId);
1321 }
1322
1323 private boolean isManagedProfileWithSeparatedLock(int userId) {
1324 return mUserManager.getUserInfo(userId).isManagedProfile()
1325 && mLockPatternUtils.isSeparateProfileChallengeEnabled(userId);
1326 }
1327
1328 // This method should be called by LockPatternUtil only, all internal methods in this class
Rubin Xu1de89b32016-11-30 20:03:13 +00001329 // should call setLockCredentialInternal.
Amith Yamasani52c489c2012-03-28 11:42:42 -07001330 @Override
Rich Canningsf64ec632019-02-21 12:40:36 -08001331 public void setLockCredential(byte[] credential, int type,
1332 byte[] savedCredential, int requestedQuality, int userId)
Andres Morales8fa56652015-03-31 09:19:50 -07001333 throws RemoteException {
Rich Canningsf64ec632019-02-21 12:40:36 -08001334
Lenka Trochtova66c492a2018-12-06 11:29:21 +01001335 if (!mLockPatternUtils.hasSecureLockScreen()) {
1336 throw new UnsupportedOperationException(
1337 "This operation requires secure lock screen feature");
1338 }
Jim Millere484eaf2016-04-13 16:35:36 -07001339 checkWritePermission(userId);
Ricky Waidc283a82016-03-24 19:55:08 +00001340 synchronized (mSeparateChallengeLock) {
Adrian Roos7374d3a2017-03-31 14:14:53 -07001341 setLockCredentialInternal(credential, type, savedCredential, requestedQuality, userId);
Pavel Grafov28939982017-10-03 15:11:52 +01001342 setSeparateProfileChallengeEnabledLocked(userId, true, null);
Andrew Scull5daf2732016-11-14 15:02:45 +00001343 notifyPasswordChanged(userId);
Ricky Waidc283a82016-03-24 19:55:08 +00001344 }
Pavel Grafov28939982017-10-03 15:11:52 +01001345 notifySeparateProfileChallengeChanged(userId);
Ricky Waidc283a82016-03-24 19:55:08 +00001346 }
1347
Rich Canningsf64ec632019-02-21 12:40:36 -08001348 private void setLockCredentialInternal(byte[] credential, int credentialType,
1349 byte[] savedCredential, int requestedQuality, int userId) throws RemoteException {
Rubin Xudf406d82017-02-16 16:49:43 +00001350 // Normalize savedCredential and credential such that empty string is always represented
1351 // as null.
Rich Canningsf64ec632019-02-21 12:40:36 -08001352 if (savedCredential == null || savedCredential.length == 0) {
Rubin Xudf406d82017-02-16 16:49:43 +00001353 savedCredential = null;
1354 }
Rich Canningsf64ec632019-02-21 12:40:36 -08001355 if (credential == null || credential.length == 0) {
Rubin Xudf406d82017-02-16 16:49:43 +00001356 credential = null;
1357 }
Rubin Xu3bf722a2016-12-15 16:07:38 +00001358 synchronized (mSpManager) {
1359 if (isSyntheticPasswordBasedCredentialLocked(userId)) {
1360 spBasedSetLockCredentialInternalLocked(credential, credentialType, savedCredential,
Adrian Roos7374d3a2017-03-31 14:14:53 -07001361 requestedQuality, userId);
Rubin Xu3bf722a2016-12-15 16:07:38 +00001362 return;
1363 }
1364 }
Adrian Roos7374d3a2017-03-31 14:14:53 -07001365
Rubin Xu1de89b32016-11-30 20:03:13 +00001366 if (credentialType == LockPatternUtils.CREDENTIAL_TYPE_NONE) {
1367 if (credential != null) {
1368 Slog.wtf(TAG, "CredentialType is none, but credential is non-null.");
1369 }
Paul Crowleycc701552016-05-17 14:18:49 -07001370 clearUserKeyProtection(userId);
Andres Moralescfb61602015-04-16 16:31:15 -07001371 getGateKeeperService().clearSecureUserId(userId);
Rubin Xu1de89b32016-11-30 20:03:13 +00001372 mStorage.writeCredentialHash(CredentialHash.createEmptyHash(), userId);
Chad Brubakera91a8502015-05-07 10:02:22 -07001373 setKeystorePassword(null, userId);
Paul Crowleycc701552016-05-17 14:18:49 -07001374 fixateNewestUserKeyAuth(userId);
Rubin Xua55b1682017-01-31 10:06:56 +00001375 synchronizeUnifiedWorkChallengeForProfiles(userId, null);
Andrew Scull5daf2732016-11-14 15:02:45 +00001376 notifyActivePasswordMetricsAvailable(null, userId);
Dmitry Dementyev77183ef2018-01-05 15:46:00 -08001377 mRecoverableKeyStoreManager.lockScreenSecretChanged(credentialType, credential, userId);
Andres Moralesd9fc85a2015-04-09 19:14:42 -07001378 return;
1379 }
Rubin Xu1de89b32016-11-30 20:03:13 +00001380 if (credential == null) {
1381 throw new RemoteException("Null credential with mismatched credential type");
Andres Morales8fa56652015-03-31 09:19:50 -07001382 }
Rubin Xua55b1682017-01-31 10:06:56 +00001383
1384 CredentialHash currentHandle = mStorage.readCredentialHash(userId);
Ricky Waidc283a82016-03-24 19:55:08 +00001385 if (isManagedProfileWithUnifiedLock(userId)) {
1386 // get credential from keystore when managed profile has unified lock
Rubin Xua55b1682017-01-31 10:06:56 +00001387 if (savedCredential == null) {
1388 try {
1389 savedCredential = getDecryptedPasswordForTiedProfile(userId);
1390 } catch (FileNotFoundException e) {
1391 Slog.i(TAG, "Child profile key not found");
1392 } catch (UnrecoverableKeyException | InvalidKeyException | KeyStoreException
1393 | NoSuchAlgorithmException | NoSuchPaddingException
1394 | InvalidAlgorithmParameterException | IllegalBlockSizeException
1395 | BadPaddingException | CertificateException | IOException e) {
1396 Slog.e(TAG, "Failed to decrypt child profile key", e);
1397 }
Andres Morales8fa56652015-03-31 09:19:50 -07001398 }
Ricky Waidc283a82016-03-24 19:55:08 +00001399 } else {
Rubin Xua55b1682017-01-31 10:06:56 +00001400 if (currentHandle.hash == null) {
Ricky Waidc283a82016-03-24 19:55:08 +00001401 if (savedCredential != null) {
1402 Slog.w(TAG, "Saved credential provided, but none stored");
1403 }
1404 savedCredential = null;
1405 }
Andres Morales8fa56652015-03-31 09:19:50 -07001406 }
Rubin Xu3bf722a2016-12-15 16:07:38 +00001407 synchronized (mSpManager) {
1408 if (shouldMigrateToSyntheticPasswordLocked(userId)) {
1409 initializeSyntheticPasswordLocked(currentHandle.hash, savedCredential,
Adrian Roos7374d3a2017-03-31 14:14:53 -07001410 currentHandle.type, requestedQuality, userId);
Rubin Xu3bf722a2016-12-15 16:07:38 +00001411 spBasedSetLockCredentialInternalLocked(credential, credentialType, savedCredential,
Adrian Roos7374d3a2017-03-31 14:14:53 -07001412 requestedQuality, userId);
Rubin Xu3bf722a2016-12-15 16:07:38 +00001413 return;
1414 }
1415 }
1416 if (DEBUG) Slog.d(TAG, "setLockCredentialInternal: user=" + userId);
Rubin Xua55b1682017-01-31 10:06:56 +00001417 byte[] enrolledHandle = enrollCredential(currentHandle.hash, savedCredential, credential,
Rubin Xu1de89b32016-11-30 20:03:13 +00001418 userId);
Andres Morales8fa56652015-03-31 09:19:50 -07001419 if (enrolledHandle != null) {
Rubin Xu1de89b32016-11-30 20:03:13 +00001420 CredentialHash willStore = CredentialHash.create(enrolledHandle, credentialType);
1421 mStorage.writeCredentialHash(willStore, userId);
Rubin Xua55b1682017-01-31 10:06:56 +00001422 // push new secret and auth token to vold
1423 GateKeeperResponse gkResponse = getGateKeeperService()
Rich Canningsf64ec632019-02-21 12:40:36 -08001424 .verifyChallenge(userId, 0, willStore.hash, credential);
Rubin Xua55b1682017-01-31 10:06:56 +00001425 setUserKeyProtection(userId, credential, convertResponse(gkResponse));
Paul Crowleycc701552016-05-17 14:18:49 -07001426 fixateNewestUserKeyAuth(userId);
Rubin Xua55b1682017-01-31 10:06:56 +00001427 // Refresh the auth token
1428 doVerifyCredential(credential, credentialType, true, 0, userId, null /* progressCallback */);
1429 synchronizeUnifiedWorkChallengeForProfiles(userId, null);
Dmitry Dementyev6e167242018-01-25 15:29:50 -08001430 mRecoverableKeyStoreManager.lockScreenSecretChanged(credentialType, credential,
1431 userId);
Andres Morales8fa56652015-03-31 09:19:50 -07001432 } else {
Rubin Xu1de89b32016-11-30 20:03:13 +00001433 throw new RemoteException("Failed to enroll " +
1434 (credentialType == LockPatternUtils.CREDENTIAL_TYPE_PASSWORD ? "password"
1435 : "pattern"));
Andres Morales8fa56652015-03-31 09:19:50 -07001436 }
1437 }
1438
Rubin Xua55b1682017-01-31 10:06:56 +00001439 private VerifyCredentialResponse convertResponse(GateKeeperResponse gateKeeperResponse) {
Adrian Roos7374d3a2017-03-31 14:14:53 -07001440 return VerifyCredentialResponse.fromGateKeeperResponse(gateKeeperResponse);
Rubin Xua55b1682017-01-31 10:06:56 +00001441 }
1442
Rubin Xu0cbc19e2016-12-09 14:00:21 +00001443 @VisibleForTesting
Rich Canningsf64ec632019-02-21 12:40:36 -08001444 protected void tieProfileLockToParent(int userId, byte[] password) {
Ricky Waidc283a82016-03-24 19:55:08 +00001445 if (DEBUG) Slog.v(TAG, "tieProfileLockToParent for user: " + userId);
Ricky Waidc283a82016-03-24 19:55:08 +00001446 byte[] encryptionResult;
1447 byte[] iv;
1448 try {
1449 KeyGenerator keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES);
1450 keyGenerator.init(new SecureRandom());
1451 SecretKey secretKey = keyGenerator.generateKey();
Ricky Waidc283a82016-03-24 19:55:08 +00001452 java.security.KeyStore keyStore = java.security.KeyStore.getInstance("AndroidKeyStore");
1453 keyStore.load(null);
Ricky Wai97c8f8d2016-07-13 17:57:45 +01001454 try {
1455 keyStore.setEntry(
1456 LockPatternUtils.PROFILE_KEY_NAME_ENCRYPT + userId,
1457 new java.security.KeyStore.SecretKeyEntry(secretKey),
1458 new KeyProtection.Builder(KeyProperties.PURPOSE_ENCRYPT)
1459 .setBlockModes(KeyProperties.BLOCK_MODE_GCM)
1460 .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
1461 .build());
1462 keyStore.setEntry(
1463 LockPatternUtils.PROFILE_KEY_NAME_DECRYPT + userId,
1464 new java.security.KeyStore.SecretKeyEntry(secretKey),
1465 new KeyProtection.Builder(KeyProperties.PURPOSE_DECRYPT)
1466 .setBlockModes(KeyProperties.BLOCK_MODE_GCM)
1467 .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
1468 .setUserAuthenticationRequired(true)
1469 .setUserAuthenticationValidityDurationSeconds(30)
Pavel Grafove053c1e2017-08-08 16:53:32 +01001470 .setCriticalToDeviceEncryption(true)
Ricky Wai97c8f8d2016-07-13 17:57:45 +01001471 .build());
1472 // Key imported, obtain a reference to it.
1473 SecretKey keyStoreEncryptionKey = (SecretKey) keyStore.getKey(
1474 LockPatternUtils.PROFILE_KEY_NAME_ENCRYPT + userId, null);
1475 Cipher cipher = Cipher.getInstance(
1476 KeyProperties.KEY_ALGORITHM_AES + "/" + KeyProperties.BLOCK_MODE_GCM + "/"
1477 + KeyProperties.ENCRYPTION_PADDING_NONE);
1478 cipher.init(Cipher.ENCRYPT_MODE, keyStoreEncryptionKey);
Rich Canningsf64ec632019-02-21 12:40:36 -08001479 encryptionResult = cipher.doFinal(password);
Ricky Wai97c8f8d2016-07-13 17:57:45 +01001480 iv = cipher.getIV();
1481 } finally {
1482 // The original key can now be discarded.
1483 keyStore.deleteEntry(LockPatternUtils.PROFILE_KEY_NAME_ENCRYPT + userId);
1484 }
Ricky Waidc283a82016-03-24 19:55:08 +00001485 } catch (CertificateException | UnrecoverableKeyException
Zach Jange61672a2016-11-22 17:47:18 +00001486 | IOException | BadPaddingException | IllegalBlockSizeException | KeyStoreException
Ricky Waidc283a82016-03-24 19:55:08 +00001487 | NoSuchPaddingException | NoSuchAlgorithmException | InvalidKeyException e) {
1488 throw new RuntimeException("Failed to encrypt key", e);
1489 }
1490 ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
1491 try {
1492 if (iv.length != PROFILE_KEY_IV_SIZE) {
1493 throw new RuntimeException("Invalid iv length: " + iv.length);
1494 }
1495 outputStream.write(iv);
1496 outputStream.write(encryptionResult);
1497 } catch (IOException e) {
1498 throw new RuntimeException("Failed to concatenate byte arrays", e);
1499 }
1500 mStorage.writeChildProfileLock(userId, outputStream.toByteArray());
1501 }
1502
Andres Morales8fa56652015-03-31 09:19:50 -07001503 private byte[] enrollCredential(byte[] enrolledHandle,
Rich Canningsf64ec632019-02-21 12:40:36 -08001504 byte[] enrolledCredential, byte[] toEnroll, int userId)
Andres Morales8fa56652015-03-31 09:19:50 -07001505 throws RemoteException {
Jim Millerde1af082013-09-11 14:58:26 -07001506 checkWritePermission(userId);
Andres Morales23974272015-05-14 22:42:26 -07001507 GateKeeperResponse response = getGateKeeperService().enroll(userId, enrolledHandle,
Rich Canningsf64ec632019-02-21 12:40:36 -08001508 enrolledCredential, toEnroll);
Jim Millerde1af082013-09-11 14:58:26 -07001509
Andres Morales23974272015-05-14 22:42:26 -07001510 if (response == null) {
1511 return null;
Andres Morales8fa56652015-03-31 09:19:50 -07001512 }
Jim Millerde1af082013-09-11 14:58:26 -07001513
Andres Morales23974272015-05-14 22:42:26 -07001514 byte[] hash = response.getPayload();
1515 if (hash != null) {
1516 setKeystorePassword(toEnroll, userId);
1517 } else {
1518 // Should not happen
1519 Slog.e(TAG, "Throttled while enrolling a password");
1520 }
Andres Morales8fa56652015-03-31 09:19:50 -07001521 return hash;
Jim Millerde1af082013-09-11 14:58:26 -07001522 }
1523
Rubin Xu3bf722a2016-12-15 16:07:38 +00001524 private void setAuthlessUserKeyProtection(int userId, byte[] key) throws RemoteException {
1525 if (DEBUG) Slog.d(TAG, "setAuthlessUserKeyProtectiond: user=" + userId);
1526 addUserKeyAuth(userId, null, key);
1527 }
1528
Rich Canningsf64ec632019-02-21 12:40:36 -08001529 private void setUserKeyProtection(int userId, byte[] credential, VerifyCredentialResponse vcr)
Paul Crowleyfaeb3eb2016-02-08 15:58:29 +00001530 throws RemoteException {
Rubin Xua55b1682017-01-31 10:06:56 +00001531 if (DEBUG) Slog.d(TAG, "setUserKeyProtection: user=" + userId);
Paul Crowleyfaeb3eb2016-02-08 15:58:29 +00001532 if (vcr == null) {
1533 throw new RemoteException("Null response verifying a credential we just set");
1534 }
1535 if (vcr.getResponseCode() != VerifyCredentialResponse.RESPONSE_OK) {
1536 throw new RemoteException("Non-OK response verifying a credential we just set: "
Rubin Xu1de89b32016-11-30 20:03:13 +00001537 + vcr.getResponseCode());
Paul Crowleyfaeb3eb2016-02-08 15:58:29 +00001538 }
1539 byte[] token = vcr.getPayload();
1540 if (token == null) {
1541 throw new RemoteException("Empty payload verifying a credential we just set");
1542 }
Paul Crowleycc701552016-05-17 14:18:49 -07001543 addUserKeyAuth(userId, token, secretFromCredential(credential));
Paul Crowleyfaeb3eb2016-02-08 15:58:29 +00001544 }
1545
1546 private void clearUserKeyProtection(int userId) throws RemoteException {
Rubin Xua55b1682017-01-31 10:06:56 +00001547 if (DEBUG) Slog.d(TAG, "clearUserKeyProtection user=" + userId);
Paul Crowleycc701552016-05-17 14:18:49 -07001548 addUserKeyAuth(userId, null, null);
Paul Crowleyfaeb3eb2016-02-08 15:58:29 +00001549 }
1550
Rich Canningsf64ec632019-02-21 12:40:36 -08001551 private static byte[] secretFromCredential(byte[] credential) throws RemoteException {
Paul Crowleyfaeb3eb2016-02-08 15:58:29 +00001552 try {
1553 MessageDigest digest = MessageDigest.getInstance("SHA-512");
1554 // Personalize the hash
Rich Canningsf64ec632019-02-21 12:40:36 -08001555 byte[] personalization = "Android FBE credential hash".getBytes();
Paul Crowleyfaeb3eb2016-02-08 15:58:29 +00001556 // Pad it to the block size of the hash function
1557 personalization = Arrays.copyOf(personalization, 128);
1558 digest.update(personalization);
Rich Canningsf64ec632019-02-21 12:40:36 -08001559 digest.update(credential);
Paul Crowleyfaeb3eb2016-02-08 15:58:29 +00001560 return digest.digest();
1561 } catch (NoSuchAlgorithmException e) {
1562 throw new RuntimeException("NoSuchAlgorithmException for SHA-512");
1563 }
1564 }
1565
Paul Crowleycc701552016-05-17 14:18:49 -07001566 private void addUserKeyAuth(int userId, byte[] token, byte[] secret)
Paul Crowleyfaeb3eb2016-02-08 15:58:29 +00001567 throws RemoteException {
Rubin Xu0cbc19e2016-12-09 14:00:21 +00001568 final UserInfo userInfo = mUserManager.getUserInfo(userId);
1569 final IStorageManager storageManager = mInjector.getStorageManager();
Paul Crowley815036f2016-03-29 14:14:48 -07001570 final long callingId = Binder.clearCallingIdentity();
1571 try {
Sudheer Shanka2250d562016-11-07 15:41:02 -08001572 storageManager.addUserKeyAuth(userId, userInfo.serialNumber, token, secret);
Paul Crowley815036f2016-03-29 14:14:48 -07001573 } finally {
1574 Binder.restoreCallingIdentity(callingId);
1575 }
Paul Crowleyfaeb3eb2016-02-08 15:58:29 +00001576 }
1577
Paul Crowleycc701552016-05-17 14:18:49 -07001578 private void fixateNewestUserKeyAuth(int userId)
1579 throws RemoteException {
Rubin Xua55b1682017-01-31 10:06:56 +00001580 if (DEBUG) Slog.d(TAG, "fixateNewestUserKeyAuth: user=" + userId);
Rubin Xu0cbc19e2016-12-09 14:00:21 +00001581 final IStorageManager storageManager = mInjector.getStorageManager();
Toni Barzic6c818722016-05-27 09:18:39 -07001582 final long callingId = Binder.clearCallingIdentity();
1583 try {
Sudheer Shanka2250d562016-11-07 15:41:02 -08001584 storageManager.fixateNewestUserKeyAuth(userId);
Toni Barzic6c818722016-05-27 09:18:39 -07001585 } finally {
1586 Binder.restoreCallingIdentity(callingId);
1587 }
Paul Crowleycc701552016-05-17 14:18:49 -07001588 }
1589
Jim Millerde1af082013-09-11 14:58:26 -07001590 @Override
Ricky Wai4613fe42016-05-24 11:11:42 +01001591 public void resetKeyStore(int userId) throws RemoteException {
Ricky Wai7f405f12016-05-31 12:05:05 +01001592 checkWritePermission(userId);
Ricky Wai4613fe42016-05-24 11:11:42 +01001593 if (DEBUG) Slog.v(TAG, "Reset keystore for user: " + userId);
1594 int managedUserId = -1;
Rich Canningsf64ec632019-02-21 12:40:36 -08001595 byte[] managedUserDecryptedPassword = null;
Ricky Wai4613fe42016-05-24 11:11:42 +01001596 final List<UserInfo> profiles = mUserManager.getProfiles(userId);
1597 for (UserInfo pi : profiles) {
1598 // Unlock managed profile with unified lock
1599 if (pi.isManagedProfile()
1600 && !mLockPatternUtils.isSeparateProfileChallengeEnabled(pi.id)
1601 && mStorage.hasChildProfileLock(pi.id)) {
1602 try {
1603 if (managedUserId == -1) {
1604 managedUserDecryptedPassword = getDecryptedPasswordForTiedProfile(pi.id);
1605 managedUserId = pi.id;
1606 } else {
1607 // Should not happen
1608 Slog.e(TAG, "More than one managed profile, uid1:" + managedUserId
1609 + ", uid2:" + pi.id);
1610 }
1611 } catch (UnrecoverableKeyException | InvalidKeyException | KeyStoreException
1612 | NoSuchAlgorithmException | NoSuchPaddingException
1613 | InvalidAlgorithmParameterException | IllegalBlockSizeException
1614 | BadPaddingException | CertificateException | IOException e) {
1615 Slog.e(TAG, "Failed to decrypt child profile key", e);
1616 }
1617 }
1618 }
1619 try {
1620 // Clear all the users credentials could have been installed in for this user.
1621 for (int profileId : mUserManager.getProfileIdsWithDisabled(userId)) {
1622 for (int uid : SYSTEM_CREDENTIAL_UIDS) {
1623 mKeyStore.clearUid(UserHandle.getUid(profileId, uid));
1624 }
1625 }
1626 } finally {
1627 if (managedUserId != -1 && managedUserDecryptedPassword != null) {
1628 if (DEBUG) Slog.v(TAG, "Restore tied profile lock");
Zach Jange61672a2016-11-22 17:47:18 +00001629 tieProfileLockToParent(managedUserId, managedUserDecryptedPassword);
Ricky Wai4613fe42016-05-24 11:11:42 +01001630 }
1631 }
Rich Canningsf64ec632019-02-21 12:40:36 -08001632 if (managedUserDecryptedPassword != null && managedUserDecryptedPassword.length > 0) {
1633 Arrays.fill(managedUserDecryptedPassword, (byte) 0);
1634 }
Ricky Wai4613fe42016-05-24 11:11:42 +01001635 }
1636
1637 @Override
Rich Canningsf64ec632019-02-21 12:40:36 -08001638 public VerifyCredentialResponse checkCredential(byte[] credential, int type, int userId,
Jorim Jaggie8fde5d2016-06-30 23:41:37 -07001639 ICheckCredentialProgressCallback progressCallback) throws RemoteException {
Rubin Xu1de89b32016-11-30 20:03:13 +00001640 checkPasswordReadPermission(userId);
1641 return doVerifyCredential(credential, type, false, 0, userId, progressCallback);
Andres Moralesd9fc85a2015-04-09 19:14:42 -07001642 }
Adrian Roos261d5ab2014-10-29 14:42:38 +01001643
Andres Moralesd9fc85a2015-04-09 19:14:42 -07001644 @Override
Rich Canningsf64ec632019-02-21 12:40:36 -08001645 public VerifyCredentialResponse verifyCredential(byte[] credential, int type, long challenge,
Rubin Xu1de89b32016-11-30 20:03:13 +00001646 int userId) throws RemoteException {
1647 checkPasswordReadPermission(userId);
1648 return doVerifyCredential(credential, type, true, challenge, userId,
1649 null /* progressCallback */);
Andres Moralesd9fc85a2015-04-09 19:14:42 -07001650 }
1651
Rubin Xu1de89b32016-11-30 20:03:13 +00001652 /**
1653 * Verify user credential and unlock the user. Fix pattern bug by deprecating the old base zero
1654 * format.
1655 */
Rich Canningsf64ec632019-02-21 12:40:36 -08001656 private VerifyCredentialResponse doVerifyCredential(byte[] credential, int credentialType,
Jorim Jaggie8fde5d2016-06-30 23:41:37 -07001657 boolean hasChallenge, long challenge, int userId,
1658 ICheckCredentialProgressCallback progressCallback) throws RemoteException {
Rich Canningsf64ec632019-02-21 12:40:36 -08001659 if (credential == null || credential.length == 0) {
Rubin Xu1de89b32016-11-30 20:03:13 +00001660 throw new IllegalArgumentException("Credential can't be null or empty");
1661 }
Adrian Roos7374d3a2017-03-31 14:14:53 -07001662 if (userId == USER_FRP && Settings.Global.getInt(mContext.getContentResolver(),
1663 Settings.Global.DEVICE_PROVISIONED, 0) != 0) {
1664 Slog.e(TAG, "FRP credential can only be verified prior to provisioning.");
1665 return VerifyCredentialResponse.ERROR;
1666 }
Rubin Xue94a7702017-06-20 17:29:57 +01001667 VerifyCredentialResponse response = null;
1668 response = spBasedDoVerifyCredential(credential, credentialType, hasChallenge, challenge,
1669 userId, progressCallback);
1670 // The user employs synthetic password based credential.
1671 if (response != null) {
Robert Berry40386df2018-01-22 21:16:58 +00001672 if (response.getResponseCode() == VerifyCredentialResponse.RESPONSE_OK) {
1673 mRecoverableKeyStoreManager.lockScreenSecretAvailable(credentialType, credential,
1674 userId);
1675 }
Rubin Xue94a7702017-06-20 17:29:57 +01001676 return response;
Rubin Xu3bf722a2016-12-15 16:07:38 +00001677 }
Rubin Xue94a7702017-06-20 17:29:57 +01001678
Adrian Roos7374d3a2017-03-31 14:14:53 -07001679 if (userId == USER_FRP) {
Andrew Scull971f2942017-07-12 15:09:45 +01001680 Slog.wtf(TAG, "Unexpected FRP credential type, should be SP based.");
1681 return VerifyCredentialResponse.ERROR;
Adrian Roos7374d3a2017-03-31 14:14:53 -07001682 }
1683
Andrew Scull971f2942017-07-12 15:09:45 +01001684 final CredentialHash storedHash = mStorage.readCredentialHash(userId);
Rubin Xu1de89b32016-11-30 20:03:13 +00001685 if (storedHash.type != credentialType) {
1686 Slog.wtf(TAG, "doVerifyCredential type mismatch with stored credential??"
1687 + " stored: " + storedHash.type + " passed in: " + credentialType);
1688 return VerifyCredentialResponse.ERROR;
1689 }
Andres Moralese40bad82015-05-28 14:21:36 -07001690
Rubin Xu1de89b32016-11-30 20:03:13 +00001691 boolean shouldReEnrollBaseZero = storedHash.type == LockPatternUtils.CREDENTIAL_TYPE_PATTERN
1692 && storedHash.isBaseZeroPattern;
Andres Moralese40bad82015-05-28 14:21:36 -07001693
Rich Canningsf64ec632019-02-21 12:40:36 -08001694 byte[] credentialToVerify;
Rubin Xu1de89b32016-11-30 20:03:13 +00001695 if (shouldReEnrollBaseZero) {
Rich Canningsf64ec632019-02-21 12:40:36 -08001696 credentialToVerify = LockPatternUtils.patternByteArrayToBaseZero(credential);
Rubin Xu1de89b32016-11-30 20:03:13 +00001697 } else {
1698 credentialToVerify = credential;
1699 }
Andres Moralesd9fc85a2015-04-09 19:14:42 -07001700
Rubin Xue94a7702017-06-20 17:29:57 +01001701 response = verifyCredential(userId, storedHash, credentialToVerify,
Rubin Xu1de89b32016-11-30 20:03:13 +00001702 hasChallenge, challenge, progressCallback);
Andres Morales59ef1262015-06-26 13:56:39 -07001703
Michal Karpinskie71f5832017-01-13 18:18:49 +00001704 if (response.getResponseCode() == VerifyCredentialResponse.RESPONSE_OK) {
1705 mStrongAuth.reportSuccessfulStrongAuthUnlock(userId);
1706 if (shouldReEnrollBaseZero) {
Adrian Roos7374d3a2017-03-31 14:14:53 -07001707 setLockCredentialInternal(credential, storedHash.type, credentialToVerify,
1708 DevicePolicyManager.PASSWORD_QUALITY_SOMETHING, userId);
Michal Karpinskie71f5832017-01-13 18:18:49 +00001709 }
Rubin Xu1de89b32016-11-30 20:03:13 +00001710 }
Andres Moralese40bad82015-05-28 14:21:36 -07001711
Rubin Xu1de89b32016-11-30 20:03:13 +00001712 return response;
Amith Yamasani52c489c2012-03-28 11:42:42 -07001713 }
1714
1715 @Override
Rich Canningsf64ec632019-02-21 12:40:36 -08001716 public VerifyCredentialResponse verifyTiedProfileChallenge(byte[] credential, int type,
Ricky Wai53940d42016-04-05 15:29:24 +01001717 long challenge, int userId) throws RemoteException {
1718 checkPasswordReadPermission(userId);
1719 if (!isManagedProfileWithUnifiedLock(userId)) {
1720 throw new RemoteException("User id must be managed profile with unified lock");
1721 }
1722 final int parentProfileId = mUserManager.getProfileParent(userId).id;
1723 // Unlock parent by using parent's challenge
Rubin Xu1de89b32016-11-30 20:03:13 +00001724 final VerifyCredentialResponse parentResponse = doVerifyCredential(
1725 credential,
1726 type,
1727 true /* hasChallenge */,
1728 challenge,
1729 parentProfileId,
1730 null /* progressCallback */);
Ricky Wai53940d42016-04-05 15:29:24 +01001731 if (parentResponse.getResponseCode() != VerifyCredentialResponse.RESPONSE_OK) {
1732 // Failed, just return parent's response
1733 return parentResponse;
1734 }
1735
1736 try {
1737 // Unlock work profile, and work profile with unified lock must use password only
Rubin Xu1de89b32016-11-30 20:03:13 +00001738 return doVerifyCredential(getDecryptedPasswordForTiedProfile(userId),
1739 LockPatternUtils.CREDENTIAL_TYPE_PASSWORD,
1740 true,
Ricky Wai53940d42016-04-05 15:29:24 +01001741 challenge,
Jorim Jaggie8fde5d2016-06-30 23:41:37 -07001742 userId, null /* progressCallback */);
Ricky Wai53940d42016-04-05 15:29:24 +01001743 } catch (UnrecoverableKeyException | InvalidKeyException | KeyStoreException
1744 | NoSuchAlgorithmException | NoSuchPaddingException
1745 | InvalidAlgorithmParameterException | IllegalBlockSizeException
1746 | BadPaddingException | CertificateException | IOException e) {
1747 Slog.e(TAG, "Failed to decrypt child profile key", e);
1748 throw new RemoteException("Unable to get tied profile token");
1749 }
1750 }
1751
Rubin Xu1de89b32016-11-30 20:03:13 +00001752 /**
1753 * Lowest-level credential verification routine that talks to GateKeeper. If verification
1754 * passes, unlock the corresponding user and keystore. Also handles the migration from legacy
1755 * hash to GK.
1756 */
Andres Morales23974272015-05-14 22:42:26 -07001757 private VerifyCredentialResponse verifyCredential(int userId, CredentialHash storedHash,
Rich Canningsf64ec632019-02-21 12:40:36 -08001758 byte[] credential, boolean hasChallenge, long challenge,
Rubin Xu1de89b32016-11-30 20:03:13 +00001759 ICheckCredentialProgressCallback progressCallback) throws RemoteException {
Rich Canningsf64ec632019-02-21 12:40:36 -08001760 if ((storedHash == null || storedHash.hash.length == 0)
1761 && (credential == null || credential.length == 0)) {
Andres Morales23974272015-05-14 22:42:26 -07001762 // don't need to pass empty credentials to GateKeeper
1763 return VerifyCredentialResponse.OK;
Andres Moralesd9fc85a2015-04-09 19:14:42 -07001764 }
1765
Rich Canningsf64ec632019-02-21 12:40:36 -08001766 if (storedHash == null || credential == null || credential.length == 0) {
Andres Morales23974272015-05-14 22:42:26 -07001767 return VerifyCredentialResponse.ERROR;
Amith Yamasani52c489c2012-03-28 11:42:42 -07001768 }
Adrian Roos261d5ab2014-10-29 14:42:38 +01001769
Jeff Sharkeyeddf5182016-08-09 16:36:08 -06001770 // We're potentially going to be doing a bunch of disk I/O below as part
1771 // of unlocking the user, so yell if calling from the main thread.
1772 StrictMode.noteDiskRead();
1773
Andres Morales8fa56652015-03-31 09:19:50 -07001774 if (storedHash.version == CredentialHash.VERSION_LEGACY) {
Rubin Xu1de89b32016-11-30 20:03:13 +00001775 final byte[] hash;
1776 if (storedHash.type == LockPatternUtils.CREDENTIAL_TYPE_PATTERN) {
Rich Canningsf64ec632019-02-21 12:40:36 -08001777 hash = LockPatternUtils.patternToHash(
1778 LockPatternUtils.byteArrayToPattern(credential));
Rubin Xu1de89b32016-11-30 20:03:13 +00001779 } else {
Rich Canningsf64ec632019-02-21 12:40:36 -08001780 hash = mLockPatternUtils.legacyPasswordToHash(credential, userId).getBytes();
Rubin Xu1de89b32016-11-30 20:03:13 +00001781 }
Andres Moralesd9fc85a2015-04-09 19:14:42 -07001782 if (Arrays.equals(hash, storedHash.hash)) {
Rubin Xu1de89b32016-11-30 20:03:13 +00001783 if (storedHash.type == LockPatternUtils.CREDENTIAL_TYPE_PATTERN) {
Rich Canningsf64ec632019-02-21 12:40:36 -08001784 unlockKeystore(LockPatternUtils.patternByteArrayToBaseZero(credential), userId);
Rubin Xu1de89b32016-11-30 20:03:13 +00001785 } else {
1786 unlockKeystore(credential, userId);
1787 }
Paul Crowleyfaeb3eb2016-02-08 15:58:29 +00001788 // Users with legacy credentials don't have credential-backed
1789 // FBE keys, so just pass through a fake token/secret
1790 Slog.i(TAG, "Unlocking user with fake token: " + userId);
1791 final byte[] fakeToken = String.valueOf(userId).getBytes();
1792 unlockUser(userId, fakeToken, fakeToken);
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -07001793
Andres Morales23974272015-05-14 22:42:26 -07001794 // migrate credential to GateKeeper
Adrian Roos7374d3a2017-03-31 14:14:53 -07001795 setLockCredentialInternal(credential, storedHash.type, null,
1796 storedHash.type == LockPatternUtils.CREDENTIAL_TYPE_PATTERN
1797 ? DevicePolicyManager.PASSWORD_QUALITY_SOMETHING
1798 : DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC
1799 /* TODO(roosa): keep the same password quality */, userId);
Andres Moralesd9fc85a2015-04-09 19:14:42 -07001800 if (!hasChallenge) {
Andrew Scull5daf2732016-11-14 15:02:45 +00001801 notifyActivePasswordMetricsAvailable(credential, userId);
Robert Berryf899bff2017-12-28 17:34:38 +00001802 // Use credentials to create recoverable keystore snapshot.
1803 mRecoverableKeyStoreManager.lockScreenSecretAvailable(
1804 storedHash.type, credential, userId);
Andres Morales23974272015-05-14 22:42:26 -07001805 return VerifyCredentialResponse.OK;
Andres Moralesd9fc85a2015-04-09 19:14:42 -07001806 }
1807 // Fall through to get the auth token. Technically this should never happen,
Andres Morales23974272015-05-14 22:42:26 -07001808 // as a user that had a legacy credential would have to unlock their device
Andres Moralesd9fc85a2015-04-09 19:14:42 -07001809 // before getting to a flow with a challenge, but supporting for consistency.
1810 } else {
Andres Morales23974272015-05-14 22:42:26 -07001811 return VerifyCredentialResponse.ERROR;
Andres Morales8fa56652015-03-31 09:19:50 -07001812 }
Andres Morales8fa56652015-03-31 09:19:50 -07001813 }
Paul Crowley98e0a262016-02-04 09:41:53 +00001814 GateKeeperResponse gateKeeperResponse = getGateKeeperService()
Rich Canningsf64ec632019-02-21 12:40:36 -08001815 .verifyChallenge(userId, challenge, storedHash.hash, credential);
Rubin Xua55b1682017-01-31 10:06:56 +00001816 VerifyCredentialResponse response = convertResponse(gateKeeperResponse);
1817 boolean shouldReEnroll = gateKeeperResponse.getShouldReEnroll();
Andres Morales8fa56652015-03-31 09:19:50 -07001818
Andres Morales23974272015-05-14 22:42:26 -07001819 if (response.getResponseCode() == VerifyCredentialResponse.RESPONSE_OK) {
Jorim Jaggie31f6b82016-07-01 16:15:09 -07001820
Andres Morales23974272015-05-14 22:42:26 -07001821 // credential has matched
Jorim Jaggie8fde5d2016-06-30 23:41:37 -07001822
1823 if (progressCallback != null) {
1824 progressCallback.onCredentialVerified();
1825 }
Andrew Scull5daf2732016-11-14 15:02:45 +00001826 notifyActivePasswordMetricsAvailable(credential, userId);
Andres Morales23974272015-05-14 22:42:26 -07001827 unlockKeystore(credential, userId);
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -07001828
Rubin Xu3bf722a2016-12-15 16:07:38 +00001829 Slog.i(TAG, "Unlocking user " + userId + " with token length "
1830 + response.getPayload().length);
Paul Crowleyfaeb3eb2016-02-08 15:58:29 +00001831 unlockUser(userId, response.getPayload(), secretFromCredential(credential));
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -07001832
Ricky Waidc283a82016-03-24 19:55:08 +00001833 if (isManagedProfileWithSeparatedLock(userId)) {
Clara Bayarri56878a92015-10-29 15:43:55 +00001834 TrustManager trustManager =
1835 (TrustManager) mContext.getSystemService(Context.TRUST_SERVICE);
1836 trustManager.setDeviceLockedForUser(userId, false);
1837 }
Adrian Roos7374d3a2017-03-31 14:14:53 -07001838 int reEnrollQuality = storedHash.type == LockPatternUtils.CREDENTIAL_TYPE_PATTERN
1839 ? DevicePolicyManager.PASSWORD_QUALITY_SOMETHING
1840 : DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC
1841 /* TODO(roosa): keep the same password quality */;
Andres Morales23974272015-05-14 22:42:26 -07001842 if (shouldReEnroll) {
Adrian Roos7374d3a2017-03-31 14:14:53 -07001843 setLockCredentialInternal(credential, storedHash.type, credential,
1844 reEnrollQuality, userId);
Rubin Xu3bf722a2016-12-15 16:07:38 +00001845 } else {
1846 // Now that we've cleared of all required GK migration, let's do the final
1847 // migration to synthetic password.
1848 synchronized (mSpManager) {
1849 if (shouldMigrateToSyntheticPasswordLocked(userId)) {
Rubin Xu128180b2017-04-12 18:02:44 +01001850 AuthenticationToken auth = initializeSyntheticPasswordLocked(
Adrian Roos7374d3a2017-03-31 14:14:53 -07001851 storedHash.hash, credential, storedHash.type, reEnrollQuality,
1852 userId);
Rubin Xu128180b2017-04-12 18:02:44 +01001853 activateEscrowTokens(auth, userId);
Rubin Xu3bf722a2016-12-15 16:07:38 +00001854 }
1855 }
Andres Morales23974272015-05-14 22:42:26 -07001856 }
Dmitry Dementyev6a509e42017-12-19 14:47:26 -08001857 // Use credentials to create recoverable keystore snapshot.
1858 mRecoverableKeyStoreManager.lockScreenSecretAvailable(storedHash.type, credential,
1859 userId);
1860
Adrian Roos873010d2015-08-25 15:59:00 -07001861 } else if (response.getResponseCode() == VerifyCredentialResponse.RESPONSE_RETRY) {
1862 if (response.getTimeout() > 0) {
1863 requireStrongAuth(STRONG_AUTH_REQUIRED_AFTER_LOCKOUT, userId);
1864 }
Andres Morales23974272015-05-14 22:42:26 -07001865 }
Amith Yamasani52c489c2012-03-28 11:42:42 -07001866
Andres Morales23974272015-05-14 22:42:26 -07001867 return response;
1868 }
Andres Moralesd9fc85a2015-04-09 19:14:42 -07001869
Rubin Xu7cf45092017-08-28 11:47:35 +01001870 /**
1871 * Call this method to notify DPMS regarding the latest password metric. This should be called
1872 * when the user is authenticating or when a new password is being set.
1873 */
Rich Canningsf64ec632019-02-21 12:40:36 -08001874 private void notifyActivePasswordMetricsAvailable(byte[] password, @UserIdInt int userId) {
Andrew Scull5daf2732016-11-14 15:02:45 +00001875 final PasswordMetrics metrics;
1876 if (password == null) {
1877 metrics = new PasswordMetrics();
1878 } else {
1879 metrics = PasswordMetrics.computeForPassword(password);
1880 metrics.quality = mLockPatternUtils.getKeyguardStoredPasswordQuality(userId);
1881 }
1882
1883 // Asynchronous to avoid dead lock
1884 mHandler.post(() -> {
1885 DevicePolicyManager dpm = (DevicePolicyManager)
1886 mContext.getSystemService(Context.DEVICE_POLICY_SERVICE);
1887 dpm.setActivePasswordState(metrics, userId);
1888 });
1889 }
1890
1891 /**
1892 * Call after {@link #notifyActivePasswordMetricsAvailable} so metrics are updated before
1893 * reporting the password changed.
1894 */
1895 private void notifyPasswordChanged(@UserIdInt int userId) {
1896 // Same handler as notifyActivePasswordMetricsAvailable to ensure correct ordering
1897 mHandler.post(() -> {
1898 DevicePolicyManager dpm = (DevicePolicyManager)
1899 mContext.getSystemService(Context.DEVICE_POLICY_SERVICE);
1900 dpm.reportPasswordChanged(userId);
Adrian Roos1c8e3c02018-11-20 20:07:55 +01001901 LocalServices.getService(WindowManagerInternal.class).reportPasswordChanged(userId);
Andrew Scull5daf2732016-11-14 15:02:45 +00001902 });
1903 }
1904
Amith Yamasani52c489c2012-03-28 11:42:42 -07001905 @Override
Adrian Roos261d5ab2014-10-29 14:42:38 +01001906 public boolean checkVoldPassword(int userId) throws RemoteException {
Paul Lawrence945490c2014-03-27 16:37:28 +00001907 if (!mFirstCallToVold) {
1908 return false;
1909 }
1910 mFirstCallToVold = false;
1911
1912 checkPasswordReadPermission(userId);
1913
1914 // There's no guarantee that this will safely connect, but if it fails
1915 // we will simply show the lock screen when we shouldn't, so relatively
1916 // benign. There is an outside chance something nasty would happen if
1917 // this service restarted before vold stales out the password in this
1918 // case. The nastiness is limited to not showing the lock screen when
1919 // we should, within the first minute of decrypting the phone if this
1920 // service can't connect to vold, it restarts, and then the new instance
1921 // does successfully connect.
Rubin Xu0cbc19e2016-12-09 14:00:21 +00001922 final IStorageManager service = mInjector.getStorageManager();
Rich Canningsf64ec632019-02-21 12:40:36 -08001923 // TODO(b/120484642): Update vold to return a password as a byte array
Paul Lawrence0bbd1082016-04-26 15:21:02 -07001924 String password;
1925 long identity = Binder.clearCallingIdentity();
1926 try {
1927 password = service.getPassword();
1928 service.clearPassword();
1929 } finally {
1930 Binder.restoreCallingIdentity(identity);
1931 }
Paul Lawrence945490c2014-03-27 16:37:28 +00001932 if (password == null) {
1933 return false;
1934 }
1935
1936 try {
Adrian Roos9dd16eb2015-01-08 16:20:49 +01001937 if (mLockPatternUtils.isLockPatternEnabled(userId)) {
Rich Canningsf64ec632019-02-21 12:40:36 -08001938 if (checkCredential(password.getBytes(), LockPatternUtils.CREDENTIAL_TYPE_PATTERN,
1939 userId, null /* progressCallback */)
Rubin Xu1de89b32016-11-30 20:03:13 +00001940 .getResponseCode() == GateKeeperResponse.RESPONSE_OK) {
Paul Lawrence945490c2014-03-27 16:37:28 +00001941 return true;
1942 }
1943 }
1944 } catch (Exception e) {
1945 }
1946
1947 try {
Adrian Roos9dd16eb2015-01-08 16:20:49 +01001948 if (mLockPatternUtils.isLockPasswordEnabled(userId)) {
Rich Canningsf64ec632019-02-21 12:40:36 -08001949 if (checkCredential(password.getBytes(), LockPatternUtils.CREDENTIAL_TYPE_PASSWORD,
1950 userId, null /* progressCallback */)
Rubin Xu1de89b32016-11-30 20:03:13 +00001951 .getResponseCode() == GateKeeperResponse.RESPONSE_OK) {
Paul Lawrence945490c2014-03-27 16:37:28 +00001952 return true;
1953 }
1954 }
1955 } catch (Exception e) {
1956 }
1957
1958 return false;
1959 }
1960
Amith Yamasanif11a5742016-06-16 08:20:07 -07001961 private void removeUser(int userId, boolean unknownUser) {
Rubin Xu7b7424b2017-03-31 18:03:20 +01001962 mSpManager.removeUser(userId);
Adrian Roos261d5ab2014-10-29 14:42:38 +01001963 mStorage.removeUser(userId);
Adrian Roosb5e47222015-08-14 15:53:06 -07001964 mStrongAuth.removeUser(userId);
Andrew Scullede482d2018-01-30 13:54:29 +00001965 tryRemoveUserFromSpCacheLater(userId);
Robin Lee49d810c2014-09-23 13:50:22 +01001966
1967 final KeyStore ks = KeyStore.getInstance();
Chad Brubaker83ce0952015-05-12 13:00:02 -07001968 ks.onUserRemoved(userId);
Andres Morales070fe632015-06-24 10:37:10 -07001969
1970 try {
1971 final IGateKeeperService gk = getGateKeeperService();
1972 if (gk != null) {
Rubin Xu1de89b32016-11-30 20:03:13 +00001973 gk.clearSecureUserId(userId);
Andres Morales070fe632015-06-24 10:37:10 -07001974 }
1975 } catch (RemoteException ex) {
1976 Slog.w(TAG, "unable to clear GK secure user id");
1977 }
Irina Dumitrescud74fb7c2019-03-06 16:42:29 +00001978 if (unknownUser || mUserManager.getUserInfo(userId).isManagedProfile()) {
Ricky Waidc283a82016-03-24 19:55:08 +00001979 removeKeystoreProfileKey(userId);
1980 }
1981 }
1982
1983 private void removeKeystoreProfileKey(int targetUserId) {
1984 if (DEBUG) Slog.v(TAG, "Remove keystore profile key for user: " + targetUserId);
1985 try {
1986 java.security.KeyStore keyStore = java.security.KeyStore.getInstance("AndroidKeyStore");
1987 keyStore.load(null);
Ricky Waid3982442016-05-24 19:27:08 +01001988 keyStore.deleteEntry(LockPatternUtils.PROFILE_KEY_NAME_ENCRYPT + targetUserId);
1989 keyStore.deleteEntry(LockPatternUtils.PROFILE_KEY_NAME_DECRYPT + targetUserId);
Ricky Waidc283a82016-03-24 19:55:08 +00001990 } catch (KeyStoreException | NoSuchAlgorithmException | CertificateException
1991 | IOException e) {
1992 // We have tried our best to remove all keys
1993 Slog.e(TAG, "Unable to remove keystore profile key for user:" + targetUserId, e);
1994 }
Amith Yamasani52c489c2012-03-28 11:42:42 -07001995 }
1996
Adrian Roosb5e47222015-08-14 15:53:06 -07001997 @Override
1998 public void registerStrongAuthTracker(IStrongAuthTracker tracker) {
1999 checkPasswordReadPermission(UserHandle.USER_ALL);
2000 mStrongAuth.registerStrongAuthTracker(tracker);
2001 }
2002
2003 @Override
2004 public void unregisterStrongAuthTracker(IStrongAuthTracker tracker) {
2005 checkPasswordReadPermission(UserHandle.USER_ALL);
2006 mStrongAuth.unregisterStrongAuthTracker(tracker);
2007 }
2008
2009 @Override
2010 public void requireStrongAuth(int strongAuthReason, int userId) {
2011 checkWritePermission(userId);
2012 mStrongAuth.requireStrongAuth(strongAuthReason, userId);
2013 }
2014
Adrian Roos4ab7e592016-04-13 15:38:13 -07002015 @Override
2016 public void userPresent(int userId) {
2017 checkWritePermission(userId);
2018 mStrongAuth.reportUnlock(userId);
2019 }
2020
Victor Changa0940d32016-05-16 19:36:08 +01002021 @Override
2022 public int getStrongAuthForUser(int userId) {
2023 checkPasswordReadPermission(userId);
2024 return mStrongAuthTracker.getStrongAuthForUser(userId);
2025 }
2026
Jorim Jaggi2fef6f72016-11-01 19:06:25 -07002027 private boolean isCallerShell() {
2028 final int callingUid = Binder.getCallingUid();
2029 return callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID;
2030 }
2031
2032 private void enforceShell() {
2033 if (!isCallerShell()) {
2034 throw new SecurityException("Caller must be shell");
2035 }
2036 }
2037
2038 @Override
2039 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
2040 String[] args, ShellCallback callback, ResultReceiver resultReceiver)
2041 throws RemoteException {
2042 enforceShell();
2043 final long origId = Binder.clearCallingIdentity();
2044 try {
Felipe Leme1fc9c812018-07-11 10:02:23 -07002045 (new LockSettingsShellCommand(new LockPatternUtils(mContext))).exec(
Jorim Jaggi2fef6f72016-11-01 19:06:25 -07002046 this, in, out, err, args, callback, resultReceiver);
2047 } finally {
2048 Binder.restoreCallingIdentity(origId);
2049 }
2050 }
2051
Dmitry Dementyev1aa96132017-12-11 11:33:12 -08002052 @Override
Bo Zhu7f414d92018-02-28 09:28:19 -08002053 public void initRecoveryServiceWithSigFile(@NonNull String rootCertificateAlias,
2054 @NonNull byte[] recoveryServiceCertFile, @NonNull byte[] recoveryServiceSigFile)
2055 throws RemoteException {
2056 mRecoverableKeyStoreManager.initRecoveryServiceWithSigFile(rootCertificateAlias,
2057 recoveryServiceCertFile, recoveryServiceSigFile);
2058 }
2059
2060 @Override
Dmitry Dementyev4da14e02018-03-23 15:18:33 -07002061 public @NonNull KeyChainSnapshot getKeyChainSnapshot() throws RemoteException {
Dmitry Dementyevb4fb9872018-01-26 11:49:34 -08002062 return mRecoverableKeyStoreManager.getKeyChainSnapshot();
Dmitry Dementyev1aa96132017-12-11 11:33:12 -08002063 }
2064
Dmitry Dementyev4da14e02018-03-23 15:18:33 -07002065 @Override
Dmitry Dementyev14298312018-01-04 15:19:19 -08002066 public void setSnapshotCreatedPendingIntent(@Nullable PendingIntent intent)
Dmitry Dementyevb8b030b2017-12-19 11:02:54 -08002067 throws RemoteException {
Dmitry Dementyev14298312018-01-04 15:19:19 -08002068 mRecoverableKeyStoreManager.setSnapshotCreatedPendingIntent(intent);
Dmitry Dementyevb8b030b2017-12-19 11:02:54 -08002069 }
2070
Dmitry Dementyev1aa96132017-12-11 11:33:12 -08002071 @Override
Dmitry Dementyev7d8c78a2018-01-12 19:14:07 -08002072 public void setServerParams(byte[] serverParams) throws RemoteException {
2073 mRecoverableKeyStoreManager.setServerParams(serverParams);
Dmitry Dementyev1aa96132017-12-11 11:33:12 -08002074 }
2075
2076 @Override
Robert Berrybbe02ae2018-02-20 19:47:43 +00002077 public void setRecoveryStatus(String alias, int status) throws RemoteException {
2078 mRecoverableKeyStoreManager.setRecoveryStatus(alias, status);
Dmitry Dementyev1aa96132017-12-11 11:33:12 -08002079 }
2080
Dmitry Dementyev4da14e02018-03-23 15:18:33 -07002081 @Override
2082 public @NonNull Map getRecoveryStatus() throws RemoteException {
Robert Berry56f06b42018-02-23 13:31:32 +00002083 return mRecoverableKeyStoreManager.getRecoveryStatus();
Dmitry Dementyevb8b030b2017-12-19 11:02:54 -08002084 }
2085
Dmitry Dementyev1aa96132017-12-11 11:33:12 -08002086 @Override
Dmitry Dementyev0916e7c2018-01-23 13:02:08 -08002087 public void setRecoverySecretTypes(@NonNull @KeyChainProtectionParams.UserSecretType
Dmitry Dementyev14298312018-01-04 15:19:19 -08002088 int[] secretTypes) throws RemoteException {
2089 mRecoverableKeyStoreManager.setRecoverySecretTypes(secretTypes);
Dmitry Dementyev1aa96132017-12-11 11:33:12 -08002090 }
2091
2092 @Override
Dmitry Dementyev4da14e02018-03-23 15:18:33 -07002093 public @NonNull int[] getRecoverySecretTypes() throws RemoteException {
Dmitry Dementyev14298312018-01-04 15:19:19 -08002094 return mRecoverableKeyStoreManager.getRecoverySecretTypes();
Dmitry Dementyev1aa96132017-12-11 11:33:12 -08002095
2096 }
2097
2098 @Override
Dmitry Dementyev4da14e02018-03-23 15:18:33 -07002099 public @NonNull byte[] startRecoverySessionWithCertPath(@NonNull String sessionId,
Bo Zhub31ab672018-03-20 22:44:18 -07002100 @NonNull String rootCertificateAlias, @NonNull RecoveryCertPath verifierCertPath,
2101 @NonNull byte[] vaultParams, @NonNull byte[] vaultChallenge,
2102 @NonNull List<KeyChainProtectionParams> secrets)
Bo Zhu7c1972f2018-02-22 21:43:52 -08002103 throws RemoteException {
2104 return mRecoverableKeyStoreManager.startRecoverySessionWithCertPath(
Bo Zhub31ab672018-03-20 22:44:18 -07002105 sessionId, rootCertificateAlias, verifierCertPath, vaultParams, vaultChallenge,
2106 secrets);
Bo Zhu7c1972f2018-02-22 21:43:52 -08002107 }
2108
Dmitry Dementyev4da14e02018-03-23 15:18:33 -07002109 @Override
Robert Berry4a5c87d2018-03-19 18:00:46 +00002110 public Map<String, String> recoverKeyChainSnapshot(
2111 @NonNull String sessionId,
2112 @NonNull byte[] recoveryKeyBlob,
2113 @NonNull List<WrappedApplicationKey> applicationKeys) throws RemoteException {
2114 return mRecoverableKeyStoreManager.recoverKeyChainSnapshot(
2115 sessionId, recoveryKeyBlob, applicationKeys);
2116 }
2117
2118 @Override
Dmitry Dementyev745d2c92018-04-13 14:10:05 -07002119 public void closeSession(@NonNull String sessionId) throws RemoteException {
2120 mRecoverableKeyStoreManager.closeSession(sessionId);
Dmitry Dementyev1aa96132017-12-11 11:33:12 -08002121 }
2122
Robert Berrycfc990a2017-12-22 15:54:30 +00002123 @Override
Robert Berry5daccec2018-01-06 19:16:25 +00002124 public void removeKey(@NonNull String alias) throws RemoteException {
2125 mRecoverableKeyStoreManager.removeKey(alias);
2126 }
2127
2128 @Override
Dmitry Dementyev4da14e02018-03-23 15:18:33 -07002129 public @Nullable String generateKey(@NonNull String alias) throws RemoteException {
Robert Berrya3b99472018-02-23 15:59:02 +00002130 return mRecoverableKeyStoreManager.generateKey(alias);
Dmitry Dementyev29b9de52018-01-31 16:09:32 -08002131 }
2132
2133 @Override
Bo Zhuc7048342019-01-03 14:04:58 -08002134 public @Nullable String generateKeyWithMetadata(
2135 @NonNull String alias, @Nullable byte[] metadata) throws RemoteException {
2136 return mRecoverableKeyStoreManager.generateKeyWithMetadata(alias, metadata);
2137 }
2138
2139 @Override
2140 public @Nullable String importKey(@NonNull String alias, @NonNull byte[] keyBytes)
2141 throws RemoteException {
Bo Zhu2c8e5382018-02-26 15:54:25 -08002142 return mRecoverableKeyStoreManager.importKey(alias, keyBytes);
2143 }
2144
2145 @Override
Bo Zhuc7048342019-01-03 14:04:58 -08002146 public @Nullable String importKeyWithMetadata(@NonNull String alias, @NonNull byte[] keyBytes,
2147 @Nullable byte[] metadata) throws RemoteException {
2148 return mRecoverableKeyStoreManager.importKeyWithMetadata(alias, keyBytes, metadata);
2149 }
2150
2151 @Override
Dmitry Dementyev4da14e02018-03-23 15:18:33 -07002152 public @Nullable String getKey(@NonNull String alias) throws RemoteException {
Dmitry Dementyev29b9de52018-01-31 16:09:32 -08002153 return mRecoverableKeyStoreManager.getKey(alias);
2154 }
2155
Amith Yamasani52c489c2012-03-28 11:42:42 -07002156 private static final String[] VALID_SETTINGS = new String[] {
Rubin Xu1de89b32016-11-30 20:03:13 +00002157 LockPatternUtils.LOCKOUT_PERMANENT_KEY,
Rubin Xu1de89b32016-11-30 20:03:13 +00002158 LockPatternUtils.PATTERN_EVER_CHOSEN_KEY,
2159 LockPatternUtils.PASSWORD_TYPE_KEY,
2160 LockPatternUtils.PASSWORD_TYPE_ALTERNATE_KEY,
2161 LockPatternUtils.LOCK_PASSWORD_SALT_KEY,
2162 LockPatternUtils.DISABLE_LOCKSCREEN_KEY,
2163 LockPatternUtils.LOCKSCREEN_OPTIONS,
2164 LockPatternUtils.LOCKSCREEN_BIOMETRIC_WEAK_FALLBACK,
2165 LockPatternUtils.BIOMETRIC_WEAK_EVER_CHOSEN_KEY,
2166 LockPatternUtils.LOCKSCREEN_POWER_BUTTON_INSTANTLY_LOCKS,
2167 LockPatternUtils.PASSWORD_HISTORY_KEY,
2168 Secure.LOCK_PATTERN_ENABLED,
2169 Secure.LOCK_BIOMETRIC_WEAK_FLAGS,
2170 Secure.LOCK_PATTERN_VISIBLE,
2171 Secure.LOCK_PATTERN_TACTILE_FEEDBACK_ENABLED
Jim Miller187ec582013-04-15 18:27:54 -07002172 };
2173
Svetoslav Ganov6d2c0e52015-06-23 16:33:36 +00002174 // Reading these settings needs the contacts permission
2175 private static final String[] READ_CONTACTS_PROTECTED_SETTINGS = new String[] {
Rubin Xu1de89b32016-11-30 20:03:13 +00002176 Secure.LOCK_SCREEN_OWNER_INFO_ENABLED,
2177 Secure.LOCK_SCREEN_OWNER_INFO
Jim Miller187ec582013-04-15 18:27:54 -07002178 };
Paul Lawrence945490c2014-03-27 16:37:28 +00002179
Adrian Roos001b00d2015-02-24 17:08:48 +01002180 // Reading these settings needs the same permission as checking the password
2181 private static final String[] READ_PASSWORD_PROTECTED_SETTINGS = new String[] {
2182 LockPatternUtils.LOCK_PASSWORD_SALT_KEY,
2183 LockPatternUtils.PASSWORD_HISTORY_KEY,
Adrian Roos855fa302015-04-02 16:01:12 +02002184 LockPatternUtils.PASSWORD_TYPE_KEY,
Ricky Wai7f405f12016-05-31 12:05:05 +01002185 SEPARATE_PROFILE_CHALLENGE_KEY
Adrian Roos001b00d2015-02-24 17:08:48 +01002186 };
2187
Amith Yamasani072543f2015-02-13 11:09:45 -08002188 private static final String[] SETTINGS_TO_BACKUP = new String[] {
Rubin Xu1de89b32016-11-30 20:03:13 +00002189 Secure.LOCK_SCREEN_OWNER_INFO_ENABLED,
Bryan Mawhinneye483b562017-05-15 14:46:05 +01002190 Secure.LOCK_SCREEN_OWNER_INFO,
2191 Secure.LOCK_PATTERN_VISIBLE,
2192 LockPatternUtils.LOCKSCREEN_POWER_BUTTON_INSTANTLY_LOCKS
Amith Yamasani072543f2015-02-13 11:09:45 -08002193 };
2194
Andres Morales301ea442015-04-17 09:15:47 -07002195 private class GateKeeperDiedRecipient implements IBinder.DeathRecipient {
2196 @Override
2197 public void binderDied() {
2198 mGateKeeperService.asBinder().unlinkToDeath(this, 0);
2199 mGateKeeperService = null;
2200 }
2201 }
2202
Rubin Xu3bf722a2016-12-15 16:07:38 +00002203 protected synchronized IGateKeeperService getGateKeeperService()
Andres Morales301ea442015-04-17 09:15:47 -07002204 throws RemoteException {
Andres Morales8fa56652015-03-31 09:19:50 -07002205 if (mGateKeeperService != null) {
2206 return mGateKeeperService;
2207 }
2208
Rubin Xu1de89b32016-11-30 20:03:13 +00002209 final IBinder service = ServiceManager.getService(Context.GATEKEEPER_SERVICE);
Andres Morales8fa56652015-03-31 09:19:50 -07002210 if (service != null) {
Andres Morales301ea442015-04-17 09:15:47 -07002211 service.linkToDeath(new GateKeeperDiedRecipient(), 0);
Andres Morales8fa56652015-03-31 09:19:50 -07002212 mGateKeeperService = IGateKeeperService.Stub.asInterface(service);
2213 return mGateKeeperService;
2214 }
2215
2216 Slog.e(TAG, "Unable to acquire GateKeeperService");
2217 return null;
2218 }
Rubin Xu3bf722a2016-12-15 16:07:38 +00002219
2220 /**
Andrew Scull1416bd02018-01-05 18:33:58 +00002221 * A user's synthetic password does not change so it must be cached in certain circumstances to
2222 * enable untrusted credential reset.
2223 *
2224 * Untrusted credential reset will be removed in a future version (b/68036371) at which point
2225 * this cache is no longer needed as the SP will always be known when changing the user's
2226 * credential.
2227 */
2228 @GuardedBy("mSpManager")
2229 private SparseArray<AuthenticationToken> mSpCache = new SparseArray();
2230
2231 private void onAuthTokenKnownForUser(@UserIdInt int userId, AuthenticationToken auth) {
Andrew Scullede482d2018-01-30 13:54:29 +00002232 // Preemptively cache the SP and then try to remove it in a handler.
2233 Slog.i(TAG, "Caching SP for user " + userId);
2234 synchronized (mSpManager) {
2235 mSpCache.put(userId, auth);
2236 }
2237 tryRemoveUserFromSpCacheLater(userId);
2238
David Anderson6ebc25b2019-02-12 16:25:56 -08002239 if (mInjector.isGsiRunning()) {
2240 Slog.w(TAG, "AuthSecret disabled in GSI");
2241 return;
2242 }
2243
Andrew Sculle6527c12018-01-05 18:33:58 +00002244 // Pass the primary user's auth secret to the HAL
2245 if (mAuthSecretService != null && mUserManager.getUserInfo(userId).isPrimary()) {
2246 try {
2247 final byte[] rawSecret = auth.deriveVendorAuthSecret();
2248 final ArrayList<Byte> secret = new ArrayList<>(rawSecret.length);
2249 for (int i = 0; i < rawSecret.length; ++i) {
2250 secret.add(rawSecret[i]);
2251 }
2252 mAuthSecretService.primaryUserCredential(secret);
2253 } catch (RemoteException e) {
2254 Slog.w(TAG, "Failed to pass primary user secret to AuthSecret HAL", e);
2255 }
2256 }
Andrew Scull1416bd02018-01-05 18:33:58 +00002257 }
2258
Andrew Scullede482d2018-01-30 13:54:29 +00002259 private void tryRemoveUserFromSpCacheLater(@UserIdInt int userId) {
2260 mHandler.post(() -> {
2261 if (!shouldCacheSpForUser(userId)) {
2262 // The transition from 'should not cache' to 'should cache' can only happen if
2263 // certain admin apps are installed after provisioning e.g. via adb. This is not
2264 // a common case and we do not seamlessly support; it may result in the SP not
2265 // being cached when it is needed. The cache can be re-populated by verifying
2266 // the credential again.
2267 Slog.i(TAG, "Removing SP from cache for user " + userId);
2268 synchronized (mSpManager) {
2269 mSpCache.remove(userId);
Andrew Scull1416bd02018-01-05 18:33:58 +00002270 }
2271 }
Andrew Scullede482d2018-01-30 13:54:29 +00002272 });
Andrew Scull1416bd02018-01-05 18:33:58 +00002273 }
2274
Andrew Scullede482d2018-01-30 13:54:29 +00002275 /** Do not hold any of the locks from this service when calling. */
Andrew Scull1416bd02018-01-05 18:33:58 +00002276 private boolean shouldCacheSpForUser(@UserIdInt int userId) {
2277 // Before the user setup has completed, an admin could be installed that requires the SP to
2278 // be cached (see below).
2279 if (Settings.Secure.getIntForUser(mContext.getContentResolver(),
2280 Settings.Secure.USER_SETUP_COMPLETE, 0, userId) == 0) {
2281 return true;
2282 }
2283
2284 // If the user has an admin which can perform an untrusted credential reset, the SP needs to
2285 // be cached. If there isn't a DevicePolicyManager then there can't be an admin in the first
2286 // place so caching is not necessary.
2287 final DevicePolicyManagerInternal dpmi = LocalServices.getService(
2288 DevicePolicyManagerInternal.class);
2289 if (dpmi == null) {
2290 return false;
2291 }
2292 return dpmi.canUserHaveUntrustedCredentialReset(userId);
2293 }
2294
2295 /**
Rubin Xu3bf722a2016-12-15 16:07:38 +00002296 * Precondition: vold and keystore unlocked.
2297 *
2298 * Create new synthetic password, set up synthetic password blob protected by the supplied
2299 * user credential, and make the newly-created SP blob active.
2300 *
2301 * The invariant under a synthetic password is:
2302 * 1. If user credential exists, then both vold and keystore and protected with keys derived
2303 * from the synthetic password.
2304 * 2. If user credential does not exist, vold and keystore protection are cleared. This is to
2305 * make it consistent with current behaviour. It also allows ActivityManager to call
2306 * unlockUser() with empty secret.
2307 * 3. Once a user is migrated to have synthetic password, its value will never change, no matter
2308 * whether the user changes his lockscreen PIN or clear/reset it. When the user clears its
2309 * lockscreen PIN, we still maintain the existing synthetic password in a password blob
Andrew Scull1416bd02018-01-05 18:33:58 +00002310 * protected by a default PIN.
Rubin Xu3bf722a2016-12-15 16:07:38 +00002311 * 4. The user SID is linked with synthetic password, but its cleared/re-created when the user
2312 * clears/re-creates his lockscreen PIN.
2313 *
2314 *
2315 * Different cases of calling this method:
2316 * 1. credentialHash != null
2317 * This implies credential != null, a new SP blob will be provisioned, and existing SID
2318 * migrated to associate with the new SP.
2319 * This happens during a normal migration case when the user currently has password.
2320 *
2321 * 2. credentialhash == null and credential == null
Rubin Xu9a6d39a52018-02-07 08:52:34 +00002322 * A new SP blob and will be created, while the user has no credentials.
Rubin Xu3bf722a2016-12-15 16:07:38 +00002323 * This can happens when we are activating an escrow token on a unsecured device, during
2324 * which we want to create the SP structure with an empty user credential.
Rubin Xu9a6d39a52018-02-07 08:52:34 +00002325 * This could also happen during an untrusted reset to clear password.
Rubin Xu3bf722a2016-12-15 16:07:38 +00002326 *
2327 * 3. credentialhash == null and credential != null
2328 * This is the untrusted credential reset, OR the user sets a new lockscreen password
2329 * FOR THE FIRST TIME on a SP-enabled device. New credential and new SID will be created
2330 */
Andrew Scull1416bd02018-01-05 18:33:58 +00002331 @GuardedBy("mSpManager")
Rubin Xu16c823e2017-06-27 14:44:58 +01002332 @VisibleForTesting
2333 protected AuthenticationToken initializeSyntheticPasswordLocked(byte[] credentialHash,
Rich Canningsf64ec632019-02-21 12:40:36 -08002334 byte[] credential, int credentialType, int requestedQuality,
Adrian Roos7374d3a2017-03-31 14:14:53 -07002335 int userId) throws RemoteException {
Rubin Xu3bf722a2016-12-15 16:07:38 +00002336 Slog.i(TAG, "Initialize SyntheticPassword for user: " + userId);
Rubin Xu9a6d39a52018-02-07 08:52:34 +00002337 final AuthenticationToken auth = mSpManager.newSyntheticPasswordAndSid(
2338 getGateKeeperService(), credentialHash, credential, userId);
Andrew Scull1416bd02018-01-05 18:33:58 +00002339 onAuthTokenKnownForUser(userId, auth);
Rubin Xu3bf722a2016-12-15 16:07:38 +00002340 if (auth == null) {
2341 Slog.wtf(TAG, "initializeSyntheticPasswordLocked returns null auth token");
2342 return null;
2343 }
2344 long handle = mSpManager.createPasswordBasedSyntheticPassword(getGateKeeperService(),
Adrian Roos7374d3a2017-03-31 14:14:53 -07002345 credential, credentialType, auth, requestedQuality, userId);
Rubin Xu3bf722a2016-12-15 16:07:38 +00002346 if (credential != null) {
2347 if (credentialHash == null) {
2348 // Since when initializing SP, we didn't provide an existing password handle
2349 // for it to migrate SID, we need to create a new SID for the user.
2350 mSpManager.newSidForUser(getGateKeeperService(), auth, userId);
2351 }
2352 mSpManager.verifyChallenge(getGateKeeperService(), auth, 0L, userId);
2353 setAuthlessUserKeyProtection(userId, auth.deriveDiskEncryptionKey());
2354 setKeystorePassword(auth.deriveKeyStorePassword(), userId);
2355 } else {
2356 clearUserKeyProtection(userId);
2357 setKeystorePassword(null, userId);
2358 getGateKeeperService().clearSecureUserId(userId);
2359 }
2360 fixateNewestUserKeyAuth(userId);
2361 setLong(SYNTHETIC_PASSWORD_HANDLE_KEY, handle, userId);
2362 return auth;
2363 }
2364
2365 private long getSyntheticPasswordHandleLocked(int userId) {
Adrian Roos60dcbbf2017-08-08 16:19:33 +02002366 return getLong(SYNTHETIC_PASSWORD_HANDLE_KEY,
2367 SyntheticPasswordManager.DEFAULT_HANDLE, userId);
Rubin Xu3bf722a2016-12-15 16:07:38 +00002368 }
2369
Rubin Xufcd49f92017-08-24 18:21:52 +01002370 private boolean isSyntheticPasswordBasedCredentialLocked(int userId) {
Adrian Roos7374d3a2017-03-31 14:14:53 -07002371 if (userId == USER_FRP) {
2372 final int type = mStorage.readPersistentDataBlock().type;
2373 return type == PersistentData.TYPE_SP || type == PersistentData.TYPE_SP_WEAVER;
2374 }
Rubin Xu3bf722a2016-12-15 16:07:38 +00002375 long handle = getSyntheticPasswordHandleLocked(userId);
2376 // This is a global setting
Paul Crowley7a0cc0a2017-05-31 22:12:57 +00002377 long enabled = getLong(SYNTHETIC_PASSWORD_ENABLED_KEY,
2378 SYNTHETIC_PASSWORD_ENABLED_BY_DEFAULT, UserHandle.USER_SYSTEM);
Rubin Xu3bf722a2016-12-15 16:07:38 +00002379 return enabled != 0 && handle != SyntheticPasswordManager.DEFAULT_HANDLE;
2380 }
2381
Rubin Xu16c823e2017-06-27 14:44:58 +01002382 @VisibleForTesting
Rubin Xufcd49f92017-08-24 18:21:52 +01002383 protected boolean shouldMigrateToSyntheticPasswordLocked(int userId) {
Rubin Xu3bf722a2016-12-15 16:07:38 +00002384 long handle = getSyntheticPasswordHandleLocked(userId);
2385 // This is a global setting
Paul Crowley7a0cc0a2017-05-31 22:12:57 +00002386 long enabled = getLong(SYNTHETIC_PASSWORD_ENABLED_KEY,
2387 SYNTHETIC_PASSWORD_ENABLED_BY_DEFAULT, UserHandle.USER_SYSTEM);
Rubin Xu3bf722a2016-12-15 16:07:38 +00002388 return enabled != 0 && handle == SyntheticPasswordManager.DEFAULT_HANDLE;
2389 }
2390
Rubin Xufcd49f92017-08-24 18:21:52 +01002391 private void enableSyntheticPasswordLocked() {
Rubin Xu3bf722a2016-12-15 16:07:38 +00002392 setLong(SYNTHETIC_PASSWORD_ENABLED_KEY, 1, UserHandle.USER_SYSTEM);
2393 }
2394
Rich Canningsf64ec632019-02-21 12:40:36 -08002395 private VerifyCredentialResponse spBasedDoVerifyCredential(byte[] userCredential, int
Rubin Xu3bf722a2016-12-15 16:07:38 +00002396 credentialType, boolean hasChallenge, long challenge, int userId,
2397 ICheckCredentialProgressCallback progressCallback) throws RemoteException {
Rubin Xue94a7702017-06-20 17:29:57 +01002398 if (DEBUG) Slog.d(TAG, "spBasedDoVerifyCredential: user=" + userId);
Rubin Xu3bf722a2016-12-15 16:07:38 +00002399 if (credentialType == LockPatternUtils.CREDENTIAL_TYPE_NONE) {
2400 userCredential = null;
2401 }
Rubin Xue94a7702017-06-20 17:29:57 +01002402
Kevin Chyna38653c2019-02-11 17:46:21 -08002403 final PackageManager pm = mContext.getPackageManager();
2404 // TODO: When lockout is handled under the HAL for all biometrics (fingerprint),
2405 // we need to generate challenge for each one, have it signed by GK and reset lockout
2406 // for each modality.
2407 if (!hasChallenge && pm.hasSystemFeature(PackageManager.FEATURE_FACE)) {
2408 challenge = mContext.getSystemService(FaceManager.class).generateChallenge();
2409 }
2410
Rubin Xue94a7702017-06-20 17:29:57 +01002411 final AuthenticationResult authResult;
2412 VerifyCredentialResponse response;
2413 synchronized (mSpManager) {
2414 if (!isSyntheticPasswordBasedCredentialLocked(userId)) {
2415 return null;
2416 }
2417 if (userId == USER_FRP) {
2418 return mSpManager.verifyFrpCredential(getGateKeeperService(),
2419 userCredential, credentialType, progressCallback);
2420 }
2421
2422 long handle = getSyntheticPasswordHandleLocked(userId);
2423 authResult = mSpManager.unwrapPasswordBasedSyntheticPassword(
Rubin Xucf326f12017-11-15 11:55:35 +00002424 getGateKeeperService(), handle, userCredential, userId, progressCallback);
Rubin Xue94a7702017-06-20 17:29:57 +01002425
Rubin Xu16c823e2017-06-27 14:44:58 +01002426 if (authResult.credentialType != credentialType) {
2427 Slog.e(TAG, "Credential type mismatch.");
2428 return VerifyCredentialResponse.ERROR;
2429 }
Rubin Xue94a7702017-06-20 17:29:57 +01002430 response = authResult.gkResponse;
2431 // credential has matched
2432 if (response.getResponseCode() == VerifyCredentialResponse.RESPONSE_OK) {
2433 // perform verifyChallenge with synthetic password which generates the real GK auth
2434 // token and response for the current user
2435 response = mSpManager.verifyChallenge(getGateKeeperService(), authResult.authToken,
2436 challenge, userId);
2437 if (response.getResponseCode() != VerifyCredentialResponse.RESPONSE_OK) {
2438 // This shouldn't really happen: the unwrapping of SP succeeds, but SP doesn't
2439 // match the recorded GK password handle.
2440 Slog.wtf(TAG, "verifyChallenge with SP failed.");
2441 return VerifyCredentialResponse.ERROR;
2442 }
2443 }
Adrian Roos7374d3a2017-03-31 14:14:53 -07002444 }
2445
Rubin Xu3bf722a2016-12-15 16:07:38 +00002446 if (response.getResponseCode() == VerifyCredentialResponse.RESPONSE_OK) {
Rubin Xu3bf722a2016-12-15 16:07:38 +00002447 notifyActivePasswordMetricsAvailable(userCredential, userId);
2448 unlockKeystore(authResult.authToken.deriveKeyStorePassword(), userId);
Kevin Chyna38653c2019-02-11 17:46:21 -08002449 // Reset lockout
Kevin Chyncf1a62e2019-02-21 11:11:59 -08002450 if (mInjector.hasBiometrics()) {
Kevin Chyna38653c2019-02-11 17:46:21 -08002451 BiometricManager bm = mContext.getSystemService(BiometricManager.class);
2452 Slog.i(TAG, "Resetting lockout, length: "
2453 + authResult.gkResponse.getPayload().length);
2454 bm.resetLockout(authResult.gkResponse.getPayload());
2455
2456 if (!hasChallenge && pm.hasSystemFeature(PackageManager.FEATURE_FACE)) {
2457 mContext.getSystemService(FaceManager.class).revokeChallenge();
2458 }
2459 }
Rubin Xu3bf722a2016-12-15 16:07:38 +00002460
2461 final byte[] secret = authResult.authToken.deriveDiskEncryptionKey();
2462 Slog.i(TAG, "Unlocking user " + userId + " with secret only, length " + secret.length);
2463 unlockUser(userId, null, secret);
2464
Rubin Xue94a7702017-06-20 17:29:57 +01002465 activateEscrowTokens(authResult.authToken, userId);
2466
Rubin Xu3bf722a2016-12-15 16:07:38 +00002467 if (isManagedProfileWithSeparatedLock(userId)) {
2468 TrustManager trustManager =
2469 (TrustManager) mContext.getSystemService(Context.TRUST_SERVICE);
2470 trustManager.setDeviceLockedForUser(userId, false);
2471 }
Rubin Xue94a7702017-06-20 17:29:57 +01002472 mStrongAuth.reportSuccessfulStrongAuthUnlock(userId);
Andrew Scull1416bd02018-01-05 18:33:58 +00002473
2474 onAuthTokenKnownForUser(userId, authResult.authToken);
Rubin Xu3bf722a2016-12-15 16:07:38 +00002475 } else if (response.getResponseCode() == VerifyCredentialResponse.RESPONSE_RETRY) {
2476 if (response.getTimeout() > 0) {
2477 requireStrongAuth(STRONG_AUTH_REQUIRED_AFTER_LOCKOUT, userId);
2478 }
2479 }
2480
2481 return response;
2482 }
2483
2484 /**
2485 * Change the user's lockscreen password by creating a new SP blob and update the handle, based
2486 * on an existing authentication token. Even though a new SP blob is created, the underlying
2487 * synthetic password is never changed.
2488 *
2489 * When clearing credential, we keep the SP unchanged, but clear its password handle so its
2490 * SID is gone. We also clear password from (software-based) keystore and vold, which will be
2491 * added back when new password is set in future.
2492 */
Andrew Scull1416bd02018-01-05 18:33:58 +00002493 @GuardedBy("mSpManager")
Rich Canningsf64ec632019-02-21 12:40:36 -08002494 private long setLockCredentialWithAuthTokenLocked(byte[] credential, int credentialType,
Adrian Roos7374d3a2017-03-31 14:14:53 -07002495 AuthenticationToken auth, int requestedQuality, int userId) throws RemoteException {
Rubin Xu3bf722a2016-12-15 16:07:38 +00002496 if (DEBUG) Slog.d(TAG, "setLockCredentialWithAuthTokenLocked: user=" + userId);
2497 long newHandle = mSpManager.createPasswordBasedSyntheticPassword(getGateKeeperService(),
Adrian Roos7374d3a2017-03-31 14:14:53 -07002498 credential, credentialType, auth, requestedQuality, userId);
Rich Canningsf64ec632019-02-21 12:40:36 -08002499 final Map<Integer, byte[]> profilePasswords;
Rubin Xu3bf722a2016-12-15 16:07:38 +00002500 if (credential != null) {
2501 // // not needed by synchronizeUnifiedWorkChallengeForProfiles()
2502 profilePasswords = null;
2503
2504 if (mSpManager.hasSidForUser(userId)) {
2505 // We are changing password of a secured device, nothing more needed as
2506 // createPasswordBasedSyntheticPassword has already taken care of maintaining
2507 // the password handle and SID unchanged.
2508
2509 //refresh auth token
2510 mSpManager.verifyChallenge(getGateKeeperService(), auth, 0L, userId);
2511 } else {
2512 // A new password is set on a previously-unsecured device, we need to generate
2513 // a new SID, and re-add keys to vold and keystore.
2514 mSpManager.newSidForUser(getGateKeeperService(), auth, userId);
2515 mSpManager.verifyChallenge(getGateKeeperService(), auth, 0L, userId);
2516 setAuthlessUserKeyProtection(userId, auth.deriveDiskEncryptionKey());
2517 fixateNewestUserKeyAuth(userId);
2518 setKeystorePassword(auth.deriveKeyStorePassword(), userId);
2519 }
2520 } else {
2521 // Cache all profile password if they use unified work challenge. This will later be
2522 // used to clear the profile's password in synchronizeUnifiedWorkChallengeForProfiles()
2523 profilePasswords = getDecryptedPasswordsForAllTiedProfiles(userId);
2524
2525 // we are clearing password of a secured device, so need to nuke SID as well.
2526 mSpManager.clearSidForUser(userId);
2527 getGateKeeperService().clearSecureUserId(userId);
2528 // Clear key from vold so ActivityManager can just unlock the user with empty secret
2529 // during boot.
2530 clearUserKeyProtection(userId);
2531 fixateNewestUserKeyAuth(userId);
2532 setKeystorePassword(null, userId);
2533 }
2534 setLong(SYNTHETIC_PASSWORD_HANDLE_KEY, newHandle, userId);
2535 synchronizeUnifiedWorkChallengeForProfiles(userId, profilePasswords);
Rubin Xu7cf45092017-08-28 11:47:35 +01002536
2537 notifyActivePasswordMetricsAvailable(credential, userId);
Rich Canningsf64ec632019-02-21 12:40:36 -08002538
2539 if (profilePasswords != null) {
2540 for (Map.Entry<Integer, byte[]> entry : profilePasswords.entrySet()) {
2541 Arrays.fill(entry.getValue(), (byte) 0);
2542 }
2543 }
2544
Rubin Xu3bf722a2016-12-15 16:07:38 +00002545 return newHandle;
2546 }
2547
Andrew Scull1416bd02018-01-05 18:33:58 +00002548 @GuardedBy("mSpManager")
Rich Canningsf64ec632019-02-21 12:40:36 -08002549 private void spBasedSetLockCredentialInternalLocked(byte[] credential, int credentialType,
2550 byte[] savedCredential, int requestedQuality, int userId) throws RemoteException {
Rubin Xu3bf722a2016-12-15 16:07:38 +00002551 if (DEBUG) Slog.d(TAG, "spBasedSetLockCredentialInternalLocked: user=" + userId);
2552 if (isManagedProfileWithUnifiedLock(userId)) {
2553 // get credential from keystore when managed profile has unified lock
2554 try {
2555 savedCredential = getDecryptedPasswordForTiedProfile(userId);
2556 } catch (FileNotFoundException e) {
2557 Slog.i(TAG, "Child profile key not found");
2558 } catch (UnrecoverableKeyException | InvalidKeyException | KeyStoreException
2559 | NoSuchAlgorithmException | NoSuchPaddingException
2560 | InvalidAlgorithmParameterException | IllegalBlockSizeException
2561 | BadPaddingException | CertificateException | IOException e) {
2562 Slog.e(TAG, "Failed to decrypt child profile key", e);
2563 }
2564 }
2565 long handle = getSyntheticPasswordHandleLocked(userId);
Rubin Xu8b30ec32017-03-05 00:47:09 +00002566 AuthenticationResult authResult = mSpManager.unwrapPasswordBasedSyntheticPassword(
Rubin Xucf326f12017-11-15 11:55:35 +00002567 getGateKeeperService(), handle, savedCredential, userId, null);
Rubin Xu8b30ec32017-03-05 00:47:09 +00002568 VerifyCredentialResponse response = authResult.gkResponse;
2569 AuthenticationToken auth = authResult.authToken;
Rubin Xu16c823e2017-06-27 14:44:58 +01002570
2571 // If existing credential is provided, then it must match.
2572 if (savedCredential != null && auth == null) {
2573 throw new RemoteException("Failed to enroll " +
2574 (credentialType == LockPatternUtils.CREDENTIAL_TYPE_PASSWORD ? "password"
2575 : "pattern"));
2576 }
2577
Rubin Xu9a6d39a52018-02-07 08:52:34 +00002578 boolean untrustedReset = false;
Rubin Xu3bf722a2016-12-15 16:07:38 +00002579 if (auth != null) {
Andrew Scull1416bd02018-01-05 18:33:58 +00002580 onAuthTokenKnownForUser(userId, auth);
Rubin Xu8b30ec32017-03-05 00:47:09 +00002581 } else if (response != null
Andrew Scull1416bd02018-01-05 18:33:58 +00002582 && response.getResponseCode() == VerifyCredentialResponse.RESPONSE_ERROR) {
Rubin Xu9a6d39a52018-02-07 08:52:34 +00002583 // We are performing an untrusted credential change, by DevicePolicyManager or other
2584 // internal callers that don't provide the existing credential
Rubin Xu3bf722a2016-12-15 16:07:38 +00002585 Slog.w(TAG, "Untrusted credential change invoked");
Rubin Xu9a6d39a52018-02-07 08:52:34 +00002586 // Try to get a cached auth token, so we can keep SP unchanged.
2587 auth = mSpCache.get(userId);
2588 untrustedReset = true;
Rubin Xu8b30ec32017-03-05 00:47:09 +00002589 } else /* response == null || responseCode == VerifyCredentialResponse.RESPONSE_RETRY */ {
2590 Slog.w(TAG, "spBasedSetLockCredentialInternalLocked: " +
2591 (response != null ? "rate limit exceeded" : "failed"));
2592 return;
Rubin Xu3bf722a2016-12-15 16:07:38 +00002593 }
Rubin Xu9a6d39a52018-02-07 08:52:34 +00002594
2595 if (auth != null) {
2596 if (untrustedReset) {
2597 // Force change the current SID to mantain existing behaviour that an untrusted
2598 // reset leads to a change of SID. If the untrusted reset is for clearing the
2599 // current password, the nuking of the SID will be done in
2600 // setLockCredentialWithAuthTokenLocked next
2601 mSpManager.newSidForUser(getGateKeeperService(), auth, userId);
2602 }
2603 setLockCredentialWithAuthTokenLocked(credential, credentialType, auth, requestedQuality,
2604 userId);
2605 mSpManager.destroyPasswordBasedSyntheticPassword(handle, userId);
2606 } else {
2607 throw new IllegalStateException(
2608 "Untrusted credential reset not possible without cached SP");
2609 // Could call initializeSyntheticPasswordLocked(null, credential, credentialType,
2610 // requestedQuality, userId) instead if we still allow untrusted reset that changes
2611 // synthetic password. That would invalidate existing escrow tokens though.
2612 }
Dmitry Dementyev6e167242018-01-25 15:29:50 -08002613 mRecoverableKeyStoreManager.lockScreenSecretChanged(credentialType, credential, userId);
Rubin Xuf095f832017-01-31 15:23:34 +00002614 }
2615
Rubin Xuf01e9072018-03-30 20:59:28 +01002616 /**
2617 * Returns a fixed pseudorandom byte string derived from the user's synthetic password.
2618 * This is used to salt the password history hash to protect the hash against offline
2619 * bruteforcing, since rederiving this value requires a successful authentication.
Rubin Xu4ed98982018-05-23 14:27:53 +01002620 * If user is a managed profile with unified challenge, currentCredential is ignored.
Rubin Xuf01e9072018-03-30 20:59:28 +01002621 */
2622 @Override
Rich Canningsf64ec632019-02-21 12:40:36 -08002623 public byte[] getHashFactor(byte[] currentCredential, int userId) throws RemoteException {
Rubin Xuf01e9072018-03-30 20:59:28 +01002624 checkPasswordReadPermission(userId);
Rich Canningsf64ec632019-02-21 12:40:36 -08002625 if (currentCredential == null || currentCredential.length == 0) {
Rubin Xuf01e9072018-03-30 20:59:28 +01002626 currentCredential = null;
2627 }
Rubin Xu4ed98982018-05-23 14:27:53 +01002628 if (isManagedProfileWithUnifiedLock(userId)) {
2629 try {
2630 currentCredential = getDecryptedPasswordForTiedProfile(userId);
2631 } catch (Exception e) {
2632 Slog.e(TAG, "Failed to get work profile credential", e);
2633 return null;
2634 }
2635 }
Rubin Xuf01e9072018-03-30 20:59:28 +01002636 synchronized (mSpManager) {
2637 if (!isSyntheticPasswordBasedCredentialLocked(userId)) {
2638 Slog.w(TAG, "Synthetic password not enabled");
2639 return null;
2640 }
2641 long handle = getSyntheticPasswordHandleLocked(userId);
2642 AuthenticationResult auth = mSpManager.unwrapPasswordBasedSyntheticPassword(
2643 getGateKeeperService(), handle, currentCredential, userId, null);
2644 if (auth.authToken == null) {
2645 Slog.w(TAG, "Current credential is incorrect");
2646 return null;
2647 }
2648 return auth.authToken.derivePasswordHashFactor();
2649 }
2650 }
2651
Ram Periathiruvadi32d53552019-02-19 13:25:46 -08002652 private long addEscrowToken(byte[] token, int userId, EscrowTokenStateChangeCallback callback)
2653 throws RemoteException {
Rubin Xuf095f832017-01-31 15:23:34 +00002654 if (DEBUG) Slog.d(TAG, "addEscrowToken: user=" + userId);
2655 synchronized (mSpManager) {
2656 enableSyntheticPasswordLocked();
Rubin Xu8b30ec32017-03-05 00:47:09 +00002657 // Migrate to synthetic password based credentials if the user has no password,
Rubin Xuf095f832017-01-31 15:23:34 +00002658 // the token can then be activated immediately.
2659 AuthenticationToken auth = null;
2660 if (!isUserSecure(userId)) {
2661 if (shouldMigrateToSyntheticPasswordLocked(userId)) {
2662 auth = initializeSyntheticPasswordLocked(null, null,
Adrian Roos7374d3a2017-03-31 14:14:53 -07002663 LockPatternUtils.CREDENTIAL_TYPE_NONE,
2664 DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED, userId);
Rubin Xuf095f832017-01-31 15:23:34 +00002665 } else /* isSyntheticPasswordBasedCredentialLocked(userId) */ {
2666 long pwdHandle = getSyntheticPasswordHandleLocked(userId);
2667 auth = mSpManager.unwrapPasswordBasedSyntheticPassword(getGateKeeperService(),
Rubin Xucf326f12017-11-15 11:55:35 +00002668 pwdHandle, null, userId, null).authToken;
Rubin Xuf095f832017-01-31 15:23:34 +00002669 }
2670 }
Rubin Xu128180b2017-04-12 18:02:44 +01002671 if (isSyntheticPasswordBasedCredentialLocked(userId)) {
2672 disableEscrowTokenOnNonManagedDevicesIfNeeded(userId);
2673 if (!mSpManager.hasEscrowData(userId)) {
2674 throw new SecurityException("Escrow token is disabled on the current user");
2675 }
Rubin Xuf095f832017-01-31 15:23:34 +00002676 }
Ram Periathiruvadi32d53552019-02-19 13:25:46 -08002677 long handle = mSpManager.createTokenBasedSyntheticPassword(token, userId, callback);
Rubin Xuf095f832017-01-31 15:23:34 +00002678 if (auth != null) {
2679 mSpManager.activateTokenBasedSyntheticPassword(handle, auth, userId);
2680 }
2681 return handle;
2682 }
2683 }
2684
Rubin Xufcd49f92017-08-24 18:21:52 +01002685 private void activateEscrowTokens(AuthenticationToken auth, int userId) {
Rubin Xuf095f832017-01-31 15:23:34 +00002686 if (DEBUG) Slog.d(TAG, "activateEscrowTokens: user=" + userId);
2687 synchronized (mSpManager) {
Rubin Xue94a7702017-06-20 17:29:57 +01002688 disableEscrowTokenOnNonManagedDevicesIfNeeded(userId);
Rubin Xuf095f832017-01-31 15:23:34 +00002689 for (long handle : mSpManager.getPendingTokensForUser(userId)) {
2690 Slog.i(TAG, String.format("activateEscrowTokens: %x %d ", handle, userId));
2691 mSpManager.activateTokenBasedSyntheticPassword(handle, auth, userId);
2692 }
2693 }
2694 }
2695
Rubin Xufcd49f92017-08-24 18:21:52 +01002696 private boolean isEscrowTokenActive(long handle, int userId) {
Rubin Xuf095f832017-01-31 15:23:34 +00002697 synchronized (mSpManager) {
2698 return mSpManager.existsHandle(handle, userId);
2699 }
2700 }
2701
Rubin Xufcd49f92017-08-24 18:21:52 +01002702 private boolean removeEscrowToken(long handle, int userId) {
Rubin Xuf095f832017-01-31 15:23:34 +00002703 synchronized (mSpManager) {
2704 if (handle == getSyntheticPasswordHandleLocked(userId)) {
2705 Slog.w(TAG, "Cannot remove password handle");
2706 return false;
2707 }
2708 if (mSpManager.removePendingToken(handle, userId)) {
2709 return true;
2710 }
2711 if (mSpManager.existsHandle(handle, userId)) {
2712 mSpManager.destroyTokenBasedSyntheticPassword(handle, userId);
2713 return true;
2714 } else {
2715 return false;
2716 }
2717 }
2718 }
2719
Rich Canningsf64ec632019-02-21 12:40:36 -08002720 private boolean setLockCredentialWithToken(byte[] credential, int type, long tokenHandle,
Adrian Roos7374d3a2017-03-31 14:14:53 -07002721 byte[] token, int requestedQuality, int userId) throws RemoteException {
Rubin Xuf095f832017-01-31 15:23:34 +00002722 boolean result;
2723 synchronized (mSpManager) {
2724 if (!mSpManager.hasEscrowData(userId)) {
2725 throw new SecurityException("Escrow token is disabled on the current user");
2726 }
2727 result = setLockCredentialWithTokenInternal(credential, type, tokenHandle, token,
Adrian Roos7374d3a2017-03-31 14:14:53 -07002728 requestedQuality, userId);
Rubin Xuf095f832017-01-31 15:23:34 +00002729 }
2730 if (result) {
2731 synchronized (mSeparateChallengeLock) {
Pavel Grafov28939982017-10-03 15:11:52 +01002732 setSeparateProfileChallengeEnabledLocked(userId, true, null);
Rubin Xuf095f832017-01-31 15:23:34 +00002733 }
2734 notifyPasswordChanged(userId);
Pavel Grafov28939982017-10-03 15:11:52 +01002735 notifySeparateProfileChallengeChanged(userId);
Rubin Xuf095f832017-01-31 15:23:34 +00002736 }
2737 return result;
2738 }
2739
Rich Canningsf64ec632019-02-21 12:40:36 -08002740 private boolean setLockCredentialWithTokenInternal(byte[] credential, int type,
Adrian Roos7374d3a2017-03-31 14:14:53 -07002741 long tokenHandle, byte[] token, int requestedQuality, int userId) throws RemoteException {
Andrew Scull1416bd02018-01-05 18:33:58 +00002742 final AuthenticationResult result;
Rubin Xuf095f832017-01-31 15:23:34 +00002743 synchronized (mSpManager) {
Andrew Scull1416bd02018-01-05 18:33:58 +00002744 result = mSpManager.unwrapTokenBasedSyntheticPassword(
Rubin Xuf095f832017-01-31 15:23:34 +00002745 getGateKeeperService(), tokenHandle, token, userId);
2746 if (result.authToken == null) {
2747 Slog.w(TAG, "Invalid escrow token supplied");
2748 return false;
2749 }
Rubin Xu24570e42017-09-19 15:27:21 +01002750 if (result.gkResponse.getResponseCode() != VerifyCredentialResponse.RESPONSE_OK) {
2751 // Most likely, an untrusted credential reset happened in the past which
2752 // changed the synthetic password
2753 Slog.e(TAG, "Obsolete token: synthetic password derived but it fails GK "
2754 + "verification.");
2755 return false;
2756 }
Rubin Xu7cf45092017-08-28 11:47:35 +01002757 // Update PASSWORD_TYPE_KEY since it's needed by notifyActivePasswordMetricsAvailable()
2758 // called by setLockCredentialWithAuthTokenLocked().
2759 // TODO: refactor usage of PASSWORD_TYPE_KEY b/65239740
2760 setLong(LockPatternUtils.PASSWORD_TYPE_KEY, requestedQuality, userId);
Rubin Xuf095f832017-01-31 15:23:34 +00002761 long oldHandle = getSyntheticPasswordHandleLocked(userId);
Adrian Roos7374d3a2017-03-31 14:14:53 -07002762 setLockCredentialWithAuthTokenLocked(credential, type, result.authToken,
2763 requestedQuality, userId);
Rubin Xuf095f832017-01-31 15:23:34 +00002764 mSpManager.destroyPasswordBasedSyntheticPassword(oldHandle, userId);
Rubin Xuf095f832017-01-31 15:23:34 +00002765 }
Andrew Scull1416bd02018-01-05 18:33:58 +00002766 onAuthTokenKnownForUser(userId, result.authToken);
2767 return true;
Rubin Xuf095f832017-01-31 15:23:34 +00002768 }
2769
Rubin Xufcd49f92017-08-24 18:21:52 +01002770 private boolean unlockUserWithToken(long tokenHandle, byte[] token, int userId)
Rubin Xuf095f832017-01-31 15:23:34 +00002771 throws RemoteException {
Rubin Xuf095f832017-01-31 15:23:34 +00002772 AuthenticationResult authResult;
2773 synchronized (mSpManager) {
2774 if (!mSpManager.hasEscrowData(userId)) {
2775 throw new SecurityException("Escrow token is disabled on the current user");
2776 }
2777 authResult = mSpManager.unwrapTokenBasedSyntheticPassword(getGateKeeperService(),
2778 tokenHandle, token, userId);
2779 if (authResult.authToken == null) {
2780 Slog.w(TAG, "Invalid escrow token supplied");
Rubin Xufcd49f92017-08-24 18:21:52 +01002781 return false;
Rubin Xuf095f832017-01-31 15:23:34 +00002782 }
2783 }
2784 unlockUser(userId, null, authResult.authToken.deriveDiskEncryptionKey());
Andrew Scull1416bd02018-01-05 18:33:58 +00002785 onAuthTokenKnownForUser(userId, authResult.authToken);
Rubin Xufcd49f92017-08-24 18:21:52 +01002786 return true;
Rubin Xu3bf722a2016-12-15 16:07:38 +00002787 }
2788
2789 @Override
2790 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args){
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06002791 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
Rubin Xu3bf722a2016-12-15 16:07:38 +00002792
Rubin Xua0a0d352017-05-15 16:18:01 +00002793 pw.println("Current lock settings service state:");
2794 pw.println(String.format("SP Enabled = %b",
2795 mLockPatternUtils.isSyntheticPasswordEnabled()));
Rubin Xu3bf722a2016-12-15 16:07:38 +00002796
Rubin Xua0a0d352017-05-15 16:18:01 +00002797 List<UserInfo> users = mUserManager.getUsers();
2798 for (int user = 0; user < users.size(); user++) {
2799 final int userId = users.get(user).id;
2800 pw.println(" User " + userId);
2801 synchronized (mSpManager) {
Rubin Xu3bf722a2016-12-15 16:07:38 +00002802 pw.println(String.format(" SP Handle = %x",
2803 getSyntheticPasswordHandleLocked(userId)));
Rubin Xua0a0d352017-05-15 16:18:01 +00002804 }
2805 try {
2806 pw.println(String.format(" SID = %x",
2807 getGateKeeperService().getSecureUserId(userId)));
2808 } catch (RemoteException e) {
2809 // ignore.
Rubin Xu3bf722a2016-12-15 16:07:38 +00002810 }
2811 }
2812 }
2813
Rubin Xuf095f832017-01-31 15:23:34 +00002814 private void disableEscrowTokenOnNonManagedDevicesIfNeeded(int userId) {
2815 long ident = Binder.clearCallingIdentity();
2816 try {
2817 // Managed profile should have escrow enabled
2818 if (mUserManager.getUserInfo(userId).isManagedProfile()) {
Rubin Xubc7a47c2017-02-22 20:31:57 +00002819 Slog.i(TAG, "Managed profile can have escrow token");
Rubin Xuf095f832017-01-31 15:23:34 +00002820 return;
2821 }
Rubin Xuf34d2f62017-03-20 12:36:35 +00002822 DevicePolicyManager dpm = mInjector.getDevicePolicyManager();
Rubin Xuf095f832017-01-31 15:23:34 +00002823 // Devices with Device Owner should have escrow enabled on all users.
Rubin Xuf34d2f62017-03-20 12:36:35 +00002824 if (dpm.getDeviceOwnerComponentOnAnyUser() != null) {
Rubin Xubc7a47c2017-02-22 20:31:57 +00002825 Slog.i(TAG, "Corp-owned device can have escrow token");
2826 return;
2827 }
2828 // We could also have a profile owner on the given (non-managed) user for unicorn cases
Rubin Xuf34d2f62017-03-20 12:36:35 +00002829 if (dpm.getProfileOwnerAsUser(userId) != null) {
Rubin Xubc7a47c2017-02-22 20:31:57 +00002830 Slog.i(TAG, "User with profile owner can have escrow token");
Rubin Xuf095f832017-01-31 15:23:34 +00002831 return;
2832 }
2833 // If the device is yet to be provisioned (still in SUW), there is still
2834 // a chance that Device Owner will be set on the device later, so postpone
2835 // disabling escrow token for now.
Rubin Xuf34d2f62017-03-20 12:36:35 +00002836 if (!dpm.isDeviceProvisioned()) {
Rubin Xubc7a47c2017-02-22 20:31:57 +00002837 Slog.i(TAG, "Postpone disabling escrow tokens until device is provisioned");
Rubin Xuf095f832017-01-31 15:23:34 +00002838 return;
2839 }
Rakesh Iyercb18d562017-03-06 18:05:53 -08002840
2841 // Escrow tokens are enabled on automotive builds.
2842 if (mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE)) {
2843 return;
2844 }
2845
Rubin Xuf095f832017-01-31 15:23:34 +00002846 // Disable escrow token permanently on all other device/user types.
2847 Slog.i(TAG, "Disabling escrow token on user " + userId);
2848 if (isSyntheticPasswordBasedCredentialLocked(userId)) {
2849 mSpManager.destroyEscrowData(userId);
2850 }
Rubin Xuf095f832017-01-31 15:23:34 +00002851 } finally {
2852 Binder.restoreCallingIdentity(ident);
2853 }
2854 }
2855
Adrian Roos7374d3a2017-03-31 14:14:53 -07002856 private class DeviceProvisionedObserver extends ContentObserver {
2857 private final Uri mDeviceProvisionedUri = Settings.Global.getUriFor(
2858 Settings.Global.DEVICE_PROVISIONED);
Andrew Scull1416bd02018-01-05 18:33:58 +00002859 private final Uri mUserSetupCompleteUri = Settings.Secure.getUriFor(
2860 Settings.Secure.USER_SETUP_COMPLETE);
Adrian Roos7374d3a2017-03-31 14:14:53 -07002861
2862 private boolean mRegistered;
2863
2864 public DeviceProvisionedObserver() {
2865 super(null);
2866 }
2867
2868 @Override
Andrew Scullede482d2018-01-30 13:54:29 +00002869 public void onChange(boolean selfChange, Uri uri, @UserIdInt int userId) {
Adrian Roos7374d3a2017-03-31 14:14:53 -07002870 if (mDeviceProvisionedUri.equals(uri)) {
2871 updateRegistration();
2872
2873 if (isProvisioned()) {
2874 Slog.i(TAG, "Reporting device setup complete to IGateKeeperService");
2875 reportDeviceSetupComplete();
Adrian Roos454f53f2017-08-08 14:56:42 +02002876 clearFrpCredentialIfOwnerNotSecure();
Adrian Roos7374d3a2017-03-31 14:14:53 -07002877 }
Andrew Scull1416bd02018-01-05 18:33:58 +00002878 } else if (mUserSetupCompleteUri.equals(uri)) {
Andrew Scullede482d2018-01-30 13:54:29 +00002879 tryRemoveUserFromSpCacheLater(userId);
Adrian Roos7374d3a2017-03-31 14:14:53 -07002880 }
2881 }
2882
2883 public void onSystemReady() {
Adrian Roos2adc2632017-09-05 17:01:42 +02002884 if (frpCredentialEnabled(mContext)) {
Adrian Roos7374d3a2017-03-31 14:14:53 -07002885 updateRegistration();
2886 } else {
2887 // If we don't intend to use frpCredentials and we're not provisioned yet, send
2888 // deviceSetupComplete immediately, so gatekeeper can discard any lingering
2889 // credentials immediately.
2890 if (!isProvisioned()) {
2891 Slog.i(TAG, "FRP credential disabled, reporting device setup complete "
2892 + "to Gatekeeper immediately");
2893 reportDeviceSetupComplete();
2894 }
2895 }
2896 }
2897
2898 private void reportDeviceSetupComplete() {
2899 try {
2900 getGateKeeperService().reportDeviceSetupComplete();
2901 } catch (RemoteException e) {
2902 Slog.e(TAG, "Failure reporting to IGateKeeperService", e);
2903 }
2904 }
2905
Adrian Roos454f53f2017-08-08 14:56:42 +02002906 /**
2907 * Clears the FRP credential if the user that controls it does not have a secure
2908 * lockscreen.
2909 */
2910 private void clearFrpCredentialIfOwnerNotSecure() {
2911 List<UserInfo> users = mUserManager.getUsers();
2912 for (UserInfo user : users) {
Adrian Roos2adc2632017-09-05 17:01:42 +02002913 if (userOwnsFrpCredential(mContext, user)) {
Adrian Roos454f53f2017-08-08 14:56:42 +02002914 if (!isUserSecure(user.id)) {
2915 mStorage.writePersistentDataBlock(PersistentData.TYPE_NONE, user.id,
2916 0, null);
2917 }
2918 return;
2919 }
2920 }
2921 }
2922
Adrian Roos7374d3a2017-03-31 14:14:53 -07002923 private void updateRegistration() {
2924 boolean register = !isProvisioned();
2925 if (register == mRegistered) {
2926 return;
2927 }
2928 if (register) {
2929 mContext.getContentResolver().registerContentObserver(mDeviceProvisionedUri,
2930 false, this);
Andrew Scull1416bd02018-01-05 18:33:58 +00002931 mContext.getContentResolver().registerContentObserver(mUserSetupCompleteUri,
2932 false, this, UserHandle.USER_ALL);
Adrian Roos7374d3a2017-03-31 14:14:53 -07002933 } else {
2934 mContext.getContentResolver().unregisterContentObserver(this);
2935 }
2936 mRegistered = register;
2937 }
2938
2939 private boolean isProvisioned() {
2940 return Settings.Global.getInt(mContext.getContentResolver(),
2941 Settings.Global.DEVICE_PROVISIONED, 0) != 0;
2942 }
2943 }
Rubin Xufcd49f92017-08-24 18:21:52 +01002944
2945 private final class LocalService extends LockSettingsInternal {
2946
2947 @Override
Ram Periathiruvadi32d53552019-02-19 13:25:46 -08002948 public long addEscrowToken(byte[] token, int userId,
2949 EscrowTokenStateChangeCallback callback) {
Rubin Xufcd49f92017-08-24 18:21:52 +01002950 try {
Ram Periathiruvadi32d53552019-02-19 13:25:46 -08002951 return LockSettingsService.this.addEscrowToken(token, userId, callback);
Rubin Xufcd49f92017-08-24 18:21:52 +01002952 } catch (RemoteException re) {
2953 throw re.rethrowFromSystemServer();
2954 }
2955 }
2956
2957 @Override
2958 public boolean removeEscrowToken(long handle, int userId) {
2959 return LockSettingsService.this.removeEscrowToken(handle, userId);
2960 }
2961
2962 @Override
2963 public boolean isEscrowTokenActive(long handle, int userId) {
2964 return LockSettingsService.this.isEscrowTokenActive(handle, userId);
2965 }
2966
2967 @Override
Rich Canningsf64ec632019-02-21 12:40:36 -08002968 public boolean setLockCredentialWithToken(byte[] credential, int type,
2969 long tokenHandle, byte[] token, int requestedQuality, int userId) {
Lenka Trochtova66c492a2018-12-06 11:29:21 +01002970 if (!mLockPatternUtils.hasSecureLockScreen()) {
2971 throw new UnsupportedOperationException(
2972 "This operation requires secure lock screen feature.");
2973 }
Rubin Xufcd49f92017-08-24 18:21:52 +01002974 try {
2975 return LockSettingsService.this.setLockCredentialWithToken(credential, type,
2976 tokenHandle, token, requestedQuality, userId);
2977 } catch (RemoteException re) {
2978 throw re.rethrowFromSystemServer();
2979 }
2980 }
2981
2982 @Override
2983 public boolean unlockUserWithToken(long tokenHandle, byte[] token, int userId) {
2984 try {
2985 return LockSettingsService.this.unlockUserWithToken(tokenHandle, token, userId);
2986 } catch (RemoteException re) {
2987 throw re.rethrowFromSystemServer();
2988 }
2989 }
2990 }
Amith Yamasani52c489c2012-03-28 11:42:42 -07002991}