Debian Codegraph @

core/java/com/android/internal/widget/LockPatternUtils.java

raw symbols SCIP
1 /*
2 * Copyright (C) 2007 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
17 package com.android.internal.widget;
18
19 import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC;
20 import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_MANAGED;
21 import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_NUMERIC;
22 import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_NUMERIC_COMPLEX;
23 import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_SOMETHING;
24 import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
25
26 import android.annotation.IntDef;
27 import android.annotation.NonNull;
28 import android.annotation.Nullable;
29 import android.app.PropertyInvalidatedCache;
30 import android.app.admin.DevicePolicyManager;
31 import android.app.admin.PasswordMetrics;
32 import android.app.trust.IStrongAuthTracker;
33 import android.app.trust.TrustManager;
34 import android.compat.annotation.UnsupportedAppUsage;
35 import android.content.ComponentName;
36 import android.content.ContentResolver;
37 import android.content.Context;
38 import android.content.pm.PackageManager;
39 import android.content.pm.UserInfo;
40 import android.os.Build;
41 import android.os.Handler;
42 import android.os.Looper;
43 import android.os.Message;
44 import android.os.RemoteException;
45 import android.os.ServiceManager;
46 import android.os.SystemClock;
47 import android.os.UserHandle;
48 import android.os.UserManager;
49 import android.os.storage.StorageManager;
50 import android.provider.Settings;
51 import android.text.TextUtils;
52 import android.util.Log;
53 import android.util.SparseBooleanArray;
54 import android.util.SparseIntArray;
55 import android.util.SparseLongArray;
56
57 import com.android.internal.annotations.VisibleForTesting;
58 import com.android.server.LocalServices;
59
60 import com.google.android.collect.Lists;
61
62 import java.lang.annotation.Retention;
63 import java.lang.annotation.RetentionPolicy;
64 import java.security.NoSuchAlgorithmException;
65 import java.security.SecureRandom;
66 import java.util.ArrayList;
67 import java.util.Collection;
68 import java.util.HashMap;
69 import java.util.List;
70
71 /**
72 * Utilities for the lock pattern and its settings.
73 */
74 public class LockPatternUtils {
75 private static final String TAG = "LockPatternUtils";
76 private static final boolean FRP_CREDENTIAL_ENABLED = true;
77
78 /**
79 * The key to identify when the lock pattern enabled flag is being accessed for legacy reasons.
80 */
81 public static final String LEGACY_LOCK_PATTERN_ENABLED = "legacy_lock_pattern_enabled";
82
83 /**
84 * The interval of the countdown for showing progress of the lockout.
85 */
86 public static final long FAILED_ATTEMPT_COUNTDOWN_INTERVAL_MS = 1000L;
87
88 /**
89 * This dictates when we start telling the user that continued failed attempts will wipe
90 * their device.
91 */
92 public static final int FAILED_ATTEMPTS_BEFORE_WIPE_GRACE = 5;
93
94 /**
95 * The minimum number of dots in a valid pattern.
96 */
97 public static final int MIN_LOCK_PATTERN_SIZE = 4;
98
99 /**
100 * The minimum size of a valid password.
101 */
102 public static final int MIN_LOCK_PASSWORD_SIZE = 4;
103
104 /**
105 * The minimum number of dots the user must include in a wrong pattern attempt for it to be
106 * counted.
107 */
108 public static final int MIN_PATTERN_REGISTER_FAIL = MIN_LOCK_PATTERN_SIZE;
109
110 // NOTE: When modifying this, make sure credential sufficiency validation logic is intact.
111 public static final int CREDENTIAL_TYPE_NONE = -1;
112 public static final int CREDENTIAL_TYPE_PATTERN = 1;
113 // This is the legacy value persisted on disk. Never return it to clients, but internally
114 // we still need it to handle upgrade cases.
115 public static final int CREDENTIAL_TYPE_PASSWORD_OR_PIN = 2;
116 public static final int CREDENTIAL_TYPE_PIN = 3;
117 public static final int CREDENTIAL_TYPE_PASSWORD = 4;
118
119 @Retention(RetentionPolicy.SOURCE)
120 @IntDef(prefix = {"CREDENTIAL_TYPE_"}, value = {
121 CREDENTIAL_TYPE_NONE,
122 CREDENTIAL_TYPE_PATTERN,
123 CREDENTIAL_TYPE_PASSWORD,
124 CREDENTIAL_TYPE_PIN,
125 // CREDENTIAL_TYPE_PASSWORD_OR_PIN is missing on purpose.
126 })
127 public @interface CredentialType {}
128
129 /**
130 * Flag provided to {@link #verifyCredential(LockscreenCredential, int, int)} . If set, the
131 * method will return a handle to the Gatekeeper Password in the
132 * {@link VerifyCredentialResponse}.
133 */
134 public static final int VERIFY_FLAG_REQUEST_GK_PW_HANDLE = 1 << 0;
135
136 @Retention(RetentionPolicy.SOURCE)
137 @IntDef(flag = true, value = {
138 VERIFY_FLAG_REQUEST_GK_PW_HANDLE
139 })
140 public @interface VerifyFlag {}
141
142 /**
143 * Special user id for triggering the FRP verification flow.
144 */
145 public static final int USER_FRP = UserHandle.USER_NULL + 1;
146
147 @Deprecated
148 public final static String LOCKOUT_PERMANENT_KEY = "lockscreen.lockedoutpermanently";
149 public final static String PATTERN_EVER_CHOSEN_KEY = "lockscreen.patterneverchosen";
150 public final static String PASSWORD_TYPE_KEY = "lockscreen.password_type";
151 @Deprecated
152 public final static String PASSWORD_TYPE_ALTERNATE_KEY = "lockscreen.password_type_alternate";
153 public final static String LOCK_PASSWORD_SALT_KEY = "lockscreen.password_salt";
154 public final static String DISABLE_LOCKSCREEN_KEY = "lockscreen.disabled";
155 public final static String LOCKSCREEN_OPTIONS = "lockscreen.options";
156 @Deprecated
157 public final static String LOCKSCREEN_BIOMETRIC_WEAK_FALLBACK
158 = "lockscreen.biometric_weak_fallback";
159 @Deprecated
160 public final static String BIOMETRIC_WEAK_EVER_CHOSEN_KEY
161 = "lockscreen.biometricweakeverchosen";
162 public final static String LOCKSCREEN_POWER_BUTTON_INSTANTLY_LOCKS
163 = "lockscreen.power_button_instantly_locks";
164 @Deprecated
165 public final static String LOCKSCREEN_WIDGETS_ENABLED = "lockscreen.widgets_enabled";
166
167 public final static String PASSWORD_HISTORY_KEY = "lockscreen.passwordhistory";
168
169 private static final String LOCK_SCREEN_OWNER_INFO = Settings.Secure.LOCK_SCREEN_OWNER_INFO;
170 private static final String LOCK_SCREEN_OWNER_INFO_ENABLED =
171 Settings.Secure.LOCK_SCREEN_OWNER_INFO_ENABLED;
172
173 private static final String LOCK_SCREEN_DEVICE_OWNER_INFO = "lockscreen.device_owner_info";
174
175 private static final String ENABLED_TRUST_AGENTS = "lockscreen.enabledtrustagents";
176 private static final String KNOWN_TRUST_AGENTS = "lockscreen.knowntrustagents";
177 private static final String IS_TRUST_USUALLY_MANAGED = "lockscreen.istrustusuallymanaged";
178
179 public static final String PROFILE_KEY_NAME_ENCRYPT = "profile_key_name_encrypt_";
180 public static final String PROFILE_KEY_NAME_DECRYPT = "profile_key_name_decrypt_";
181 public static final String SYNTHETIC_PASSWORD_KEY_PREFIX = "synthetic_password_";
182
183 public static final String SYNTHETIC_PASSWORD_HANDLE_KEY = "sp-handle";
184 public static final String SYNTHETIC_PASSWORD_ENABLED_KEY = "enable-sp";
185 public static final int SYNTHETIC_PASSWORD_ENABLED_BY_DEFAULT = 1;
186 public static final String PASSWORD_HISTORY_DELIMITER = ",";
187
188 @UnsupportedAppUsage
189 private final Context mContext;
190 @UnsupportedAppUsage
191 private final ContentResolver mContentResolver;
192 private DevicePolicyManager mDevicePolicyManager;
193 private ILockSettings mLockSettingsService;
194 private UserManager mUserManager;
195 private final Handler mHandler;
196 private final SparseLongArray mLockoutDeadlines = new SparseLongArray();
197 private Boolean mHasSecureLockScreen;
198
199 private HashMap<UserHandle, UserManager> mUserManagerCache = new HashMap<>();
200
201 /**
202 * Use {@link TrustManager#isTrustUsuallyManaged(int)}.
203 *
204 * This returns the lazily-peristed value and should only be used by TrustManagerService.
205 */
206 public boolean isTrustUsuallyManaged(int userId) {
207 if (!(mLockSettingsService instanceof ILockSettings.Stub)) {
208 throw new IllegalStateException("May only be called by TrustManagerService. "
209 + "Use TrustManager.isTrustUsuallyManaged()");
210 }
211 try {
212 return getLockSettings().getBoolean(IS_TRUST_USUALLY_MANAGED, false, userId);
213 } catch (RemoteException e) {
214 return false;
215 }
216 }
217
218 public void setTrustUsuallyManaged(boolean managed, int userId) {
219 try {
220 getLockSettings().setBoolean(IS_TRUST_USUALLY_MANAGED, managed, userId);
221 } catch (RemoteException e) {
222 // System dead.
223 }
224 }
225
226 public void userPresent(int userId) {
227 try {
228 getLockSettings().userPresent(userId);
229 } catch (RemoteException e) {
230 throw e.rethrowFromSystemServer();
231 }
232 }
233
234 public static final class RequestThrottledException extends Exception {
235 private int mTimeoutMs;
236 @UnsupportedAppUsage
237 public RequestThrottledException(int timeoutMs) {
238 mTimeoutMs = timeoutMs;
239 }
240
241 /**
242 * @return The amount of time in ms before another request may
243 * be executed
244 */
245 @UnsupportedAppUsage
246 public int getTimeoutMs() {
247 return mTimeoutMs;
248 }
249
250 }
251
252 @UnsupportedAppUsage
253 public DevicePolicyManager getDevicePolicyManager() {
254 if (mDevicePolicyManager == null) {
255 mDevicePolicyManager =
256 (DevicePolicyManager)mContext.getSystemService(Context.DEVICE_POLICY_SERVICE);
257 if (mDevicePolicyManager == null) {
258 Log.e(TAG, "Can't get DevicePolicyManagerService: is it running?",
259 new IllegalStateException("Stack trace:"));
260 }
261 }
262 return mDevicePolicyManager;
263 }
264
265 private UserManager getUserManager() {
266 if (mUserManager == null) {
267 mUserManager = UserManager.get(mContext);
268 }
269 return mUserManager;
270 }
271
272 private UserManager getUserManager(int userId) {
273 UserHandle userHandle = UserHandle.of(userId);
274 if (mUserManagerCache.containsKey(userHandle)) {
275 return mUserManagerCache.get(userHandle);
276 }
277
278 try {
279 Context userContext = mContext.createPackageContextAsUser("system", 0, userHandle);
280 UserManager userManager = userContext.getSystemService(UserManager.class);
281 mUserManagerCache.put(userHandle, userManager);
282 return userManager;
283 } catch (PackageManager.NameNotFoundException e) {
284 throw new RuntimeException("Failed to create context for user " + userHandle, e);
285 }
286 }
287
288 private TrustManager getTrustManager() {
289 TrustManager trust = (TrustManager) mContext.getSystemService(Context.TRUST_SERVICE);
290 if (trust == null) {
291 Log.e(TAG, "Can't get TrustManagerService: is it running?",
292 new IllegalStateException("Stack trace:"));
293 }
294 return trust;
295 }
296
297 @UnsupportedAppUsage
298 public LockPatternUtils(Context context) {
299 mContext = context;
300 mContentResolver = context.getContentResolver();
301
302 Looper looper = Looper.myLooper();
303 mHandler = looper != null ? new Handler(looper) : null;
304 }
305
306 @UnsupportedAppUsage
307 @VisibleForTesting
308 public ILockSettings getLockSettings() {
309 if (mLockSettingsService == null) {
310 ILockSettings service = ILockSettings.Stub.asInterface(
311 ServiceManager.getService("lock_settings"));
312 mLockSettingsService = service;
313 }
314 return mLockSettingsService;
315 }
316
317 public int getRequestedMinimumPasswordLength(int userId) {
318 return getDevicePolicyManager().getPasswordMinimumLength(null, userId);
319 }
320
321 public int getMaximumPasswordLength(int quality) {
322 return getDevicePolicyManager().getPasswordMaximumLength(quality);
323 }
324
325 /**
326 * Returns aggregated (legacy) password quality requirement on the target user from all admins.
327 */
328 public PasswordMetrics getRequestedPasswordMetrics(int userId) {
329 return getRequestedPasswordMetrics(userId, false);
330 }
331
332 /**
333 * Returns aggregated (legacy) password quality requirement on the target user from all admins,
334 * optioanlly disregarding policies set on the managed profile as if the profile had separate
335 * work challenge.
336 */
337 public PasswordMetrics getRequestedPasswordMetrics(int userId, boolean deviceWideOnly) {
338 return getDevicePolicyManager().getPasswordMinimumMetrics(userId, deviceWideOnly);
339 }
340
341 private int getRequestedPasswordHistoryLength(int userId) {
342 return getDevicePolicyManager().getPasswordHistoryLength(null, userId);
343 }
344
345 /**
346 * Returns the effective complexity for the user.
347 * @param userId The user to return the complexity for.
348 * @return complexity level for the user.
349 */
350 public @DevicePolicyManager.PasswordComplexity int getRequestedPasswordComplexity(int userId) {
351 return getRequestedPasswordComplexity(userId, false);
352 }
353
354 /**
355 * Returns the effective complexity for the user, optioanlly disregarding complexity set on the
356 * managed profile as if the profile had separate work challenge.
357
358 * @param userId The user to return the complexity for.
359 * @param deviceWideOnly whether to ignore complexity set on the managed profile.
360 * @return complexity level for the user.
361 */
362 public @DevicePolicyManager.PasswordComplexity int getRequestedPasswordComplexity(int userId,
363 boolean deviceWideOnly) {
364 return getDevicePolicyManager().getAggregatedPasswordComplexityForUser(userId,
365 deviceWideOnly);
366 }
367
368 @UnsupportedAppUsage
369 public void reportFailedPasswordAttempt(int userId) {
370 if (userId == USER_FRP && frpCredentialEnabled(mContext)) {
371 return;
372 }
373 getDevicePolicyManager().reportFailedPasswordAttempt(userId);
374 getTrustManager().reportUnlockAttempt(false /* authenticated */, userId);
375 }
376
377 @UnsupportedAppUsage
378 public void reportSuccessfulPasswordAttempt(int userId) {
379 if (userId == USER_FRP && frpCredentialEnabled(mContext)) {
380 return;
381 }
382 getDevicePolicyManager().reportSuccessfulPasswordAttempt(userId);
383 getTrustManager().reportUnlockAttempt(true /* authenticated */, userId);
384 }
385
386 public void reportPasswordLockout(int timeoutMs, int userId) {
387 if (userId == USER_FRP && frpCredentialEnabled(mContext)) {
388 return;
389 }
390 getTrustManager().reportUnlockLockout(timeoutMs, userId);
391 }
392
393 public int getCurrentFailedPasswordAttempts(int userId) {
394 if (userId == USER_FRP && frpCredentialEnabled(mContext)) {
395 return 0;
396 }
397 return getDevicePolicyManager().getCurrentFailedPasswordAttempts(userId);
398 }
399
400 public int getMaximumFailedPasswordsForWipe(int userId) {
401 if (userId == USER_FRP && frpCredentialEnabled(mContext)) {
402 return 0;
403 }
404 return getDevicePolicyManager().getMaximumFailedPasswordsForWipe(
405 null /* componentName */, userId);
406 }
407
408 /**
409 * Check to see if a credential matches the saved one.
410 * If credential matches, return an opaque attestation that the challenge was verified.
411 *
412 * @param credential The credential to check.
413 * @param userId The user whose credential is being verified
414 * @param flags See {@link VerifyFlag}
415 * @throws IllegalStateException if called on the main thread.
416 */
417 @NonNull
418 public VerifyCredentialResponse verifyCredential(@NonNull LockscreenCredential credential,
419 int userId, @VerifyFlag int flags) {
420 throwIfCalledOnMainThread();
421 try {
422 final VerifyCredentialResponse response = getLockSettings().verifyCredential(
423 credential, userId, flags);
424 if (response == null) {
425 return VerifyCredentialResponse.ERROR;
426 } else {
427 return response;
428 }
429 } catch (RemoteException re) {
430 Log.e(TAG, "failed to verify credential", re);
431 return VerifyCredentialResponse.ERROR;
432 }
433 }
434
435 /**
436 * With the Gatekeeper Password Handle returned via {@link #verifyCredential(
437 * LockscreenCredential, int, int)}, request Gatekeeper to create a HardwareAuthToken wrapping
438 * the given challenge.
439 */
440 @NonNull
441 public VerifyCredentialResponse verifyGatekeeperPasswordHandle(long gatekeeperPasswordHandle,
442 long challenge, int userId) {
443 try {
444 final VerifyCredentialResponse response = getLockSettings()
445 .verifyGatekeeperPasswordHandle(gatekeeperPasswordHandle, challenge, userId);
446 if (response == null) {
447 return VerifyCredentialResponse.ERROR;
448 }
449 return response;
450 } catch (RemoteException e) {
451 Log.e(TAG, "failed to verify gatekeeper password", e);
452 return VerifyCredentialResponse.ERROR;
453 }
454 }
455
456 public void removeGatekeeperPasswordHandle(long gatekeeperPasswordHandle) {
457 try {
458 getLockSettings().removeGatekeeperPasswordHandle(gatekeeperPasswordHandle);
459 } catch (RemoteException e) {
460 Log.e(TAG, "failed to remove gatekeeper password handle", e);
461 }
462 }
463
464 /**
465 * Check to see if a credential matches the saved one.
466 *
467 * @param credential The credential to check.
468 * @param userId The user whose credential is being checked
469 * @param progressCallback callback to deliver early signal that the credential matches
470 * @return {@code true} if credential matches, {@code false} otherwise
471 * @throws RequestThrottledException if credential verification is being throttled due to
472 * to many incorrect attempts.
473 * @throws IllegalStateException if called on the main thread.
474 */
475 public boolean checkCredential(@NonNull LockscreenCredential credential, int userId,
476 @Nullable CheckCredentialProgressCallback progressCallback)
477 throws RequestThrottledException {
478 throwIfCalledOnMainThread();
479 try {
480 VerifyCredentialResponse response = getLockSettings().checkCredential(
481 credential, userId, wrapCallback(progressCallback));
482 if (response == null) {
483 return false;
484 } else if (response.getResponseCode() == VerifyCredentialResponse.RESPONSE_OK) {
485 return true;
486 } else if (response.getResponseCode() == VerifyCredentialResponse.RESPONSE_RETRY) {
487 throw new RequestThrottledException(response.getTimeout());
488 } else {
489 return false;
490 }
491 } catch (RemoteException re) {
492 Log.e(TAG, "failed to check credential", re);
493 return false;
494 }
495 }
496
497 /**
498 * Check if the credential of a managed profile with unified challenge matches. In this context,
499 * The credential should be the parent user's lockscreen password. If credential matches,
500 * return an opaque attestation associated with the managed profile that the challenge was
501 * verified.
502 *
503 * @param credential The parent user's credential to check.
504 * @return the attestation that the challenge was verified, or null
505 * @param userId The managed profile user id
506 * @param flags See {@link VerifyFlag}
507 * @throws IllegalStateException if called on the main thread.
508 */
509 @NonNull
510 public VerifyCredentialResponse verifyTiedProfileChallenge(
511 @NonNull LockscreenCredential credential, int userId, @VerifyFlag int flags) {
512 throwIfCalledOnMainThread();
513 try {
514 final VerifyCredentialResponse response = getLockSettings()
515 .verifyTiedProfileChallenge(credential, userId, flags);
516 if (response == null) {
517 return VerifyCredentialResponse.ERROR;
518 } else {
519 return response;
520 }
521 } catch (RemoteException re) {
522 Log.e(TAG, "failed to verify tied profile credential", re);
523 return VerifyCredentialResponse.ERROR;
524 }
525 }
526
527 /**
528 * Returns the password history hash factor, needed to check new password against password
529 * history with {@link #checkPasswordHistory(byte[], byte[], int)}
530 */
531 public byte[] getPasswordHistoryHashFactor(@NonNull LockscreenCredential currentPassword,
532 int userId) {
533 try {
534 return getLockSettings().getHashFactor(currentPassword, userId);
535 } catch (RemoteException e) {
536 Log.e(TAG, "failed to get hash factor", e);
537 return null;
538 }
539 }
540
541 /**
542 * Check to see if a password matches any of the passwords stored in the
543 * password history.
544 *
545 * @param passwordToCheck The password to check.
546 * @param hashFactor Hash factor of the current user returned from
547 * {@link ILockSettings#getHashFactor}
548 * @return Whether the password matches any in the history.
549 */
550 public boolean checkPasswordHistory(byte[] passwordToCheck, byte[] hashFactor, int userId) {
551 if (passwordToCheck == null || passwordToCheck.length == 0) {
552 Log.e(TAG, "checkPasswordHistory: empty password");
553 return false;
554 }
555 String passwordHistory = getString(PASSWORD_HISTORY_KEY, userId);
556 if (TextUtils.isEmpty(passwordHistory)) {
557 return false;
558 }
559 int passwordHistoryLength = getRequestedPasswordHistoryLength(userId);
560 if(passwordHistoryLength == 0) {
561 return false;
562 }
563 byte[] salt = getSalt(userId).getBytes();
564 String legacyHash = LockscreenCredential.legacyPasswordToHash(passwordToCheck, salt);
565 String passwordHash = LockscreenCredential.passwordToHistoryHash(
566 passwordToCheck, salt, hashFactor);
567 String[] history = passwordHistory.split(PASSWORD_HISTORY_DELIMITER);
568 // Password History may be too long...
569 for (int i = 0; i < Math.min(passwordHistoryLength, history.length); i++) {
570 if (history[i].equals(legacyHash) || history[i].equals(passwordHash)) {
571 return true;
572 }
573 }
574 return false;
575 }
576
577 /**
578 * Return true if the user has ever chosen a pattern. This is true even if the pattern is
579 * currently cleared.
580 *
581 * @return True if the user has ever chosen a pattern.
582 */
583 public boolean isPatternEverChosen(int userId) {
584 return getBoolean(PATTERN_EVER_CHOSEN_KEY, false, userId);
585 }
586
587 /**
588 * Records that the user has chosen a pattern at some time, even if the pattern is
589 * currently cleared.
590 */
591 public void reportPatternWasChosen(int userId) {
592 setBoolean(PATTERN_EVER_CHOSEN_KEY, true, userId);
593 }
594
595 /**
596 * Used by device policy manager to validate the current password
597 * information it has.
598 * @Deprecated use {@link #getKeyguardStoredPasswordQuality}
599 */
600 @UnsupportedAppUsage
601 public int getActivePasswordQuality(int userId) {
602 return getKeyguardStoredPasswordQuality(userId);
603 }
604
605 /**
606 * Use it to reset keystore without wiping work profile
607 */
608 public void resetKeyStore(int userId) {
609 try {
610 getLockSettings().resetKeyStore(userId);
611 } catch (RemoteException e) {
612 // It should not happen
613 Log.e(TAG, "Couldn't reset keystore " + e);
614 }
615 }
616
617 /**
618 * Disable showing lock screen at all for a given user.
619 * This is only meaningful if pattern, pin or password are not set.
620 *
621 * @param disable Disables lock screen when true
622 * @param userId User ID of the user this has effect on
623 */
624 public void setLockScreenDisabled(boolean disable, int userId) {
625 setBoolean(DISABLE_LOCKSCREEN_KEY, disable, userId);
626 }
627
628 /**
629 * Determine if LockScreen is disabled for the current user. This is used to decide whether
630 * LockScreen is shown after reboot or after screen timeout / short press on power.
631 *
632 * @return true if lock screen is disabled
633 */
634 @UnsupportedAppUsage
635 public boolean isLockScreenDisabled(int userId) {
636 if (isSecure(userId)) {
637 return false;
638 }
639 boolean disabledByDefault = mContext.getResources().getBoolean(
640 com.android.internal.R.bool.config_disableLockscreenByDefault);
641 boolean isSystemUser = UserManager.isSplitSystemUser() && userId == UserHandle.USER_SYSTEM;
642 UserInfo userInfo = getUserManager().getUserInfo(userId);
643 boolean isDemoUser = UserManager.isDeviceInDemoMode(mContext) && userInfo != null
644 && userInfo.isDemo();
645 return getBoolean(DISABLE_LOCKSCREEN_KEY, false, userId)
646 || (disabledByDefault && !isSystemUser)
647 || isDemoUser;
648 }
649
650 /** Returns if the given quality maps to an alphabetic password */
651 public static boolean isQualityAlphabeticPassword(int quality) {
652 return quality >= PASSWORD_QUALITY_ALPHABETIC;
653 }
654
655 /** Returns if the given quality maps to an numeric pin */
656 public static boolean isQualityNumericPin(int quality) {
657 return quality == PASSWORD_QUALITY_NUMERIC || quality == PASSWORD_QUALITY_NUMERIC_COMPLEX;
658 }
659
660 /** Returns the canonical password quality corresponding to the given credential type. */
661 public static int credentialTypeToPasswordQuality(int credentialType) {
662 switch (credentialType) {
663 case CREDENTIAL_TYPE_NONE:
664 return PASSWORD_QUALITY_UNSPECIFIED;
665 case CREDENTIAL_TYPE_PATTERN:
666 return PASSWORD_QUALITY_SOMETHING;
667 case CREDENTIAL_TYPE_PIN:
668 return PASSWORD_QUALITY_NUMERIC;
669 case CREDENTIAL_TYPE_PASSWORD:
670 return PASSWORD_QUALITY_ALPHABETIC;
671 default:
672 throw new IllegalStateException("Unknown type: " + credentialType);
673 }
674 }
675
676 /**
677 * Save a new lockscreen credential.
678 *
679 * <p> This method will fail (returning {@code false}) if the previously saved credential
680 * provided is incorrect, or if the lockscreen verification is still being throttled.
681 *
682 * @param newCredential The new credential to save
683 * @param savedCredential The current credential
684 * @param userHandle the user whose lockscreen credential is to be changed
685 *
686 * @return whether this method saved the new password successfully or not. This flow will fail
687 * and return false if the given credential is wrong.
688 * @throws RuntimeException if password change encountered an unrecoverable error.
689 * @throws UnsupportedOperationException secure lockscreen is not supported on this device.
690 * @throws IllegalArgumentException if new credential is too short.
691 */
692 public boolean setLockCredential(@NonNull LockscreenCredential newCredential,
693 @NonNull LockscreenCredential savedCredential, int userHandle) {
694 if (!hasSecureLockScreen() && newCredential.getType() != CREDENTIAL_TYPE_NONE) {
695 throw new UnsupportedOperationException(
696 "This operation requires the lock screen feature.");
697 }
698 newCredential.checkLength();
699
700 try {
701 if (!getLockSettings().setLockCredential(newCredential, savedCredential, userHandle)) {
702 return false;
703 }
704 } catch (RemoteException e) {
705 throw new RuntimeException("Unable to save lock password", e);
706 }
707 return true;
708 }
709
710 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
711 public void setOwnerInfo(String info, int userId) {
712 setString(LOCK_SCREEN_OWNER_INFO, info, userId);
713 }
714
715 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
716 public void setOwnerInfoEnabled(boolean enabled, int userId) {
717 setBoolean(LOCK_SCREEN_OWNER_INFO_ENABLED, enabled, userId);
718 }
719
720 @UnsupportedAppUsage
721 public String getOwnerInfo(int userId) {
722 return getString(LOCK_SCREEN_OWNER_INFO, userId);
723 }
724
725 public boolean isOwnerInfoEnabled(int userId) {
726 return getBoolean(LOCK_SCREEN_OWNER_INFO_ENABLED, false, userId);
727 }
728
729 /**
730 * Sets the device owner information. If the information is {@code null} or empty then the
731 * device owner info is cleared.
732 *
733 * @param info Device owner information which will be displayed instead of the user
734 * owner info.
735 */
736 public void setDeviceOwnerInfo(String info) {
737 if (info != null && info.isEmpty()) {
738 info = null;
739 }
740
741 setString(LOCK_SCREEN_DEVICE_OWNER_INFO, info, UserHandle.USER_SYSTEM);
742 }
743
744 public String getDeviceOwnerInfo() {
745 return getString(LOCK_SCREEN_DEVICE_OWNER_INFO, UserHandle.USER_SYSTEM);
746 }
747
748 public boolean isDeviceOwnerInfoEnabled() {
749 return getDeviceOwnerInfo() != null;
750 }
751
752 /**
753 * Determine if the device supports encryption, even if it's set to default. This
754 * differs from isDeviceEncrypted() in that it returns true even if the device is
755 * encrypted with the default password.
756 * @return true if device encryption is enabled
757 */
758 @UnsupportedAppUsage
759 public static boolean isDeviceEncryptionEnabled() {
760 return StorageManager.isEncrypted();
761 }
762
763 /**
764 * Determine if the device is file encrypted
765 * @return true if device is file encrypted
766 */
767 public static boolean isFileEncryptionEnabled() {
768 return StorageManager.isFileEncryptedNativeOrEmulated();
769 }
770
771 /**
772 * Retrieves the quality mode for {@code userHandle}.
773 * @see DevicePolicyManager#getPasswordQuality(android.content.ComponentName)
774 *
775 * @return stored password quality
776 * @deprecated use {@link #getCredentialTypeForUser(int)} instead
777 */
778 @UnsupportedAppUsage
779 @Deprecated
780 public int getKeyguardStoredPasswordQuality(int userHandle) {
781 return credentialTypeToPasswordQuality(getCredentialTypeForUser(userHandle));
782 }
783
784 /**
785 * Enables/disables the Separate Profile Challenge for this {@code userHandle}. This is a no-op
786 * for user handles that do not belong to a profile that shares credential with parent.
787 * (managed profile and clone profile share lock credential with parent).
788 *
789 * @param userHandle Managed profile user id
790 * @param enabled True if separate challenge is enabled
791 * @param profilePassword Managed/Clone profile previous password. Null when {@code enabled} is
792 * true
793 */
794 public void setSeparateProfileChallengeEnabled(int userHandle, boolean enabled,
795 LockscreenCredential profilePassword) {
796 if (!isCredentialSharableWithParent(userHandle)) {
797 return;
798 }
799 try {
800 getLockSettings().setSeparateProfileChallengeEnabled(userHandle, enabled,
801 profilePassword);
802 reportEnabledTrustAgentsChanged(userHandle);
803 } catch (RemoteException e) {
804 Log.e(TAG, "Couldn't update work profile challenge enabled");
805 }
806 }
807
808 /**
809 * Returns true if {@code userHandle} is a managed profile with separate challenge.
810 */
811 public boolean isSeparateProfileChallengeEnabled(int userHandle) {
812 return isCredentialSharableWithParent(userHandle) && hasSeparateChallenge(userHandle);
813 }
814
815 /**
816 * Returns true if {@code userHandle} is a managed profile with unified challenge.
817 */
818 public boolean isManagedProfileWithUnifiedChallenge(int userHandle) {
819 return isManagedProfile(userHandle) && !hasSeparateChallenge(userHandle);
820 }
821
822 private boolean hasSeparateChallenge(int userHandle) {
823 try {
824 return getLockSettings().getSeparateProfileChallengeEnabled(userHandle);
825 } catch (RemoteException e) {
826 Log.e(TAG, "Couldn't get separate profile challenge enabled");
827 // Default value is false
828 return false;
829 }
830 }
831
832 private boolean isManagedProfile(int userHandle) {
833 final UserInfo info = getUserManager().getUserInfo(userHandle);
834 return info != null && info.isManagedProfile();
835 }
836
837 private boolean isCredentialSharableWithParent(int userHandle) {
838 return getUserManager(userHandle).isCredentialSharableWithParent();
839 }
840
841 /**
842 * Deserialize a pattern.
843 * @param bytes The pattern serialized with {@link #patternToByteArray}
844 * @return The pattern.
845 */
846 public static List<LockPatternView.Cell> byteArrayToPattern(byte[] bytes) {
847 if (bytes == null) {
848 return null;
849 }
850
851 List<LockPatternView.Cell> result = Lists.newArrayList();
852
853 for (int i = 0; i < bytes.length; i++) {
854 byte b = (byte) (bytes[i] - '1');
855 result.add(LockPatternView.Cell.of(b / 3, b % 3));
856 }
857 return result;
858 }
859
860 /**
861 * Serialize a pattern.
862 * @param pattern The pattern.
863 * @return The pattern in byte array form.
864 */
865 public static byte[] patternToByteArray(List<LockPatternView.Cell> pattern) {
866 if (pattern == null) {
867 return new byte[0];
868 }
869 final int patternSize = pattern.size();
870
871 byte[] res = new byte[patternSize];
872 for (int i = 0; i < patternSize; i++) {
873 LockPatternView.Cell cell = pattern.get(i);
874 res[i] = (byte) (cell.getRow() * 3 + cell.getColumn() + '1');
875 }
876 return res;
877 }
878
879 private String getSalt(int userId) {
880 long salt = getLong(LOCK_PASSWORD_SALT_KEY, 0, userId);
881 if (salt == 0) {
882 try {
883 salt = SecureRandom.getInstance("SHA1PRNG").nextLong();
884 setLong(LOCK_PASSWORD_SALT_KEY, salt, userId);
885 Log.v(TAG, "Initialized lock password salt for user: " + userId);
886 } catch (NoSuchAlgorithmException e) {
887 // Throw an exception rather than storing a password we'll never be able to recover
888 throw new IllegalStateException("Couldn't get SecureRandom number", e);
889 }
890 }
891 return Long.toHexString(salt);
892 }
893
894 /**
895 * Retrieve the credential type of a user.
896 */
897 private final PropertyInvalidatedCache.QueryHandler<Integer, Integer> mCredentialTypeQuery =
898 new PropertyInvalidatedCache.QueryHandler<>() {
899 @Override
900 public Integer apply(Integer userHandle) {
901 try {
902 return getLockSettings().getCredentialType(userHandle);
903 } catch (RemoteException re) {
904 Log.e(TAG, "failed to get credential type", re);
905 return CREDENTIAL_TYPE_NONE;
906 }
907 }
908 @Override
909 public boolean shouldBypassCache(Integer userHandle) {
910 return userHandle == USER_FRP;
911 }
912 };
913
914 /**
915 * The API that is cached.
916 */
917 private final static String CREDENTIAL_TYPE_API = "getCredentialType";
918
919 /**
920 * Cache the credential type of a user.
921 */
922 private final PropertyInvalidatedCache<Integer, Integer> mCredentialTypeCache =
923 new PropertyInvalidatedCache<>(4, PropertyInvalidatedCache.MODULE_SYSTEM,
924 CREDENTIAL_TYPE_API, CREDENTIAL_TYPE_API, mCredentialTypeQuery);
925
926 /**
927 * Invalidate the credential cache
928 * @hide
929 */
930 public final static void invalidateCredentialTypeCache() {
931 PropertyInvalidatedCache.invalidateCache(PropertyInvalidatedCache.MODULE_SYSTEM,
932 CREDENTIAL_TYPE_API);
933 }
934
935 /**
936 * Returns the credential type of the user, can be one of {@link #CREDENTIAL_TYPE_NONE},
937 * {@link #CREDENTIAL_TYPE_PATTERN}, {@link #CREDENTIAL_TYPE_PIN} and
938 * {@link #CREDENTIAL_TYPE_PASSWORD}
939 */
940 public @CredentialType int getCredentialTypeForUser(int userHandle) {
941 return mCredentialTypeCache.query(userHandle);
942 }
943
944 /**
945 * @param userId the user for which to report the value
946 * @return Whether the lock screen is secured.
947 */
948 @UnsupportedAppUsage
949 public boolean isSecure(int userId) {
950 int type = getCredentialTypeForUser(userId);
951 return type != CREDENTIAL_TYPE_NONE;
952 }
953
954 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
955 public boolean isLockPasswordEnabled(int userId) {
956 int type = getCredentialTypeForUser(userId);
957 return type == CREDENTIAL_TYPE_PASSWORD || type == CREDENTIAL_TYPE_PIN;
958 }
959
960 /**
961 * @return Whether the lock pattern is enabled
962 */
963 @UnsupportedAppUsage
964 public boolean isLockPatternEnabled(int userId) {
965 int type = getCredentialTypeForUser(userId);
966 return type == CREDENTIAL_TYPE_PATTERN;
967 }
968
969 @Deprecated
970 public boolean isLegacyLockPatternEnabled(int userId) {
971 // Note: this value should default to {@code true} to avoid any reset that might result.
972 // We must use a special key to read this value, since it will by default return the value
973 // based on the new logic.
974 return getBoolean(LEGACY_LOCK_PATTERN_ENABLED, true, userId);
975 }
976
977 @Deprecated
978 public void setLegacyLockPatternEnabled(int userId) {
979 setBoolean(Settings.Secure.LOCK_PATTERN_ENABLED, true, userId);
980 }
981
982 /**
983 * @return Whether the visible pattern is enabled.
984 */
985 @UnsupportedAppUsage
986 public boolean isVisiblePatternEnabled(int userId) {
987 return getBoolean(Settings.Secure.LOCK_PATTERN_VISIBLE, false, userId);
988 }
989
990 /**
991 * Set whether the visible pattern is enabled.
992 */
993 public void setVisiblePatternEnabled(boolean enabled, int userId) {
994 setBoolean(Settings.Secure.LOCK_PATTERN_VISIBLE, enabled, userId);
995 }
996
997 public boolean isVisiblePatternEverChosen(int userId) {
998 return getString(Settings.Secure.LOCK_PATTERN_VISIBLE, userId) != null;
999 }
1000
1001 /**
1002 * Set whether the visible password is enabled for cryptkeeper screen.
1003 */
1004 public void setVisiblePasswordEnabled(boolean enabled, int userId) {
1005 // No longer does anything.
1006 }
1007
1008 /**
1009 * Set and store the lockout deadline, meaning the user can't attempt their unlock
1010 * pattern until the deadline has passed.
1011 * @return the chosen deadline.
1012 */
1013 @UnsupportedAppUsage
1014 public long setLockoutAttemptDeadline(int userId, int timeoutMs) {
1015 final long deadline = SystemClock.elapsedRealtime() + timeoutMs;
1016 if (userId == USER_FRP) {
1017 // For secure password storage (that is required for FRP), the underlying storage also
1018 // enforces the deadline. Since we cannot store settings for the FRP user, don't.
1019 return deadline;
1020 }
1021 mLockoutDeadlines.put(userId, deadline);
1022 return deadline;
1023 }
1024
1025 /**
1026 * @return The elapsed time in millis in the future when the user is allowed to
1027 * attempt to enter their lock pattern, or 0 if the user is welcome to
1028 * enter a pattern.
1029 */
1030 public long getLockoutAttemptDeadline(int userId) {
1031 final long deadline = mLockoutDeadlines.get(userId, 0L);
1032 final long now = SystemClock.elapsedRealtime();
1033 if (deadline < now && deadline != 0) {
1034 // timeout expired
1035 mLockoutDeadlines.put(userId, 0);
1036 return 0L;
1037 }
1038 return deadline;
1039 }
1040
1041 private boolean getBoolean(String secureSettingKey, boolean defaultValue, int userId) {
1042 try {
1043 return getLockSettings().getBoolean(secureSettingKey, defaultValue, userId);
1044 } catch (RemoteException re) {
1045 return defaultValue;
1046 }
1047 }
1048
1049 private void setBoolean(String secureSettingKey, boolean enabled, int userId) {
1050 try {
1051 getLockSettings().setBoolean(secureSettingKey, enabled, userId);
1052 } catch (RemoteException re) {
1053 // What can we do?
1054 Log.e(TAG, "Couldn't write boolean " + secureSettingKey + re);
1055 }
1056 }
1057
1058 private long getLong(String secureSettingKey, long defaultValue, int userHandle) {
1059 try {
1060 return getLockSettings().getLong(secureSettingKey, defaultValue, userHandle);
1061 } catch (RemoteException re) {
1062 return defaultValue;
1063 }
1064 }
1065
1066 @UnsupportedAppUsage
1067 private void setLong(String secureSettingKey, long value, int userHandle) {
1068 try {
1069 getLockSettings().setLong(secureSettingKey, value, userHandle);
1070 } catch (RemoteException re) {
1071 // What can we do?
1072 Log.e(TAG, "Couldn't write long " + secureSettingKey + re);
1073 }
1074 }
1075
1076 @UnsupportedAppUsage
1077 private String getString(String secureSettingKey, int userHandle) {
1078 try {
1079 return getLockSettings().getString(secureSettingKey, null, userHandle);
1080 } catch (RemoteException re) {
1081 return null;
1082 }
1083 }
1084
1085 @UnsupportedAppUsage
1086 private void setString(String secureSettingKey, String value, int userHandle) {
1087 try {
1088 getLockSettings().setString(secureSettingKey, value, userHandle);
1089 } catch (RemoteException re) {
1090 // What can we do?
1091 Log.e(TAG, "Couldn't write string " + secureSettingKey + re);
1092 }
1093 }
1094
1095 public void setPowerButtonInstantlyLocks(boolean enabled, int userId) {
1096 setBoolean(LOCKSCREEN_POWER_BUTTON_INSTANTLY_LOCKS, enabled, userId);
1097 }
1098
1099 @UnsupportedAppUsage
1100 public boolean getPowerButtonInstantlyLocks(int userId) {
1101 return getBoolean(LOCKSCREEN_POWER_BUTTON_INSTANTLY_LOCKS, true, userId);
1102 }
1103
1104 public boolean isPowerButtonInstantlyLocksEverChosen(int userId) {
1105 return getString(LOCKSCREEN_POWER_BUTTON_INSTANTLY_LOCKS, userId) != null;
1106 }
1107
1108 /** Updates the list of enabled trust agent in LockSettings storage for the given user. */
1109 public void setEnabledTrustAgents(Collection<ComponentName> activeTrustAgents, int userId) {
1110 setString(ENABLED_TRUST_AGENTS, serializeTrustAgents(activeTrustAgents), userId);
1111 getTrustManager().reportEnabledTrustAgentsChanged(userId);
1112 }
1113
1114 /** Returns the list of enabled trust agent in LockSettings storage for the given user. */
1115 public List<ComponentName> getEnabledTrustAgents(int userId) {
1116 return deserializeTrustAgents(getString(ENABLED_TRUST_AGENTS, userId));
1117 }
1118
1119 /** Updates the list of known trust agent in LockSettings storage for the given user. */
1120 public void setKnownTrustAgents(Collection<ComponentName> knownTrustAgents, int userId) {
1121 setString(KNOWN_TRUST_AGENTS, serializeTrustAgents(knownTrustAgents), userId);
1122 }
1123
1124 /** Returns the list of known trust agent in LockSettings storage for the given user. */
1125 public List<ComponentName> getKnownTrustAgents(int userId) {
1126 return deserializeTrustAgents(getString(KNOWN_TRUST_AGENTS, userId));
1127 }
1128
1129 private String serializeTrustAgents(Collection<ComponentName> trustAgents) {
1130 StringBuilder sb = new StringBuilder();
1131 for (ComponentName cn : trustAgents) {
1132 if (sb.length() > 0) {
1133 sb.append(',');
1134 }
1135 sb.append(cn.flattenToShortString());
1136 }
1137 return sb.toString();
1138 }
1139
1140 private List<ComponentName> deserializeTrustAgents(String serializedTrustAgents) {
1141 if (TextUtils.isEmpty(serializedTrustAgents)) {
1142 return new ArrayList<>();
1143 }
1144 String[] split = serializedTrustAgents.split(",");
1145 ArrayList<ComponentName> trustAgents = new ArrayList<>(split.length);
1146 for (String s : split) {
1147 if (!TextUtils.isEmpty(s)) {
1148 trustAgents.add(ComponentName.unflattenFromString(s));
1149 }
1150 }
1151 return trustAgents;
1152 }
1153
1154 /**
1155 * Disable trust until credentials have been entered for user {@code userId}.
1156 *
1157 * Requires the {@link android.Manifest.permission#ACCESS_KEYGUARD_SECURE_STORAGE} permission.
1158 *
1159 * @param userId either an explicit user id or {@link android.os.UserHandle#USER_ALL}
1160 */
1161 public void requireCredentialEntry(int userId) {
1162 requireStrongAuth(StrongAuthTracker.SOME_AUTH_REQUIRED_AFTER_USER_REQUEST, userId);
1163 }
1164
1165 /**
1166 * Requests strong authentication for user {@code userId}.
1167 *
1168 * Requires the {@link android.Manifest.permission#ACCESS_KEYGUARD_SECURE_STORAGE} permission.
1169 *
1170 * @param strongAuthReason a combination of {@link StrongAuthTracker.StrongAuthFlags} indicating
1171 * the reason for and the strength of the requested authentication.
1172 * @param userId either an explicit user id or {@link android.os.UserHandle#USER_ALL}
1173 */
1174 public void requireStrongAuth(@StrongAuthTracker.StrongAuthFlags int strongAuthReason,
1175 int userId) {
1176 try {
1177 getLockSettings().requireStrongAuth(strongAuthReason, userId);
1178 } catch (RemoteException e) {
1179 Log.e(TAG, "Error while requesting strong auth: " + e);
1180 }
1181 }
1182
1183 private void reportEnabledTrustAgentsChanged(int userHandle) {
1184 getTrustManager().reportEnabledTrustAgentsChanged(userHandle);
1185 }
1186
1187 public boolean isCredentialRequiredToDecrypt(boolean defaultValue) {
1188 final int value = Settings.Global.getInt(mContentResolver,
1189 Settings.Global.REQUIRE_PASSWORD_TO_DECRYPT, -1);
1190 return value == -1 ? defaultValue : (value != 0);
1191 }
1192
1193 public void setCredentialRequiredToDecrypt(boolean required) {
1194 if (!(getUserManager().isSystemUser() || getUserManager().isPrimaryUser())) {
1195 throw new IllegalStateException(
1196 "Only the system or primary user may call setCredentialRequiredForDecrypt()");
1197 }
1198
1199 if (isDeviceEncryptionEnabled()){
1200 Settings.Global.putInt(mContext.getContentResolver(),
1201 Settings.Global.REQUIRE_PASSWORD_TO_DECRYPT, required ? 1 : 0);
1202 }
1203 }
1204
1205 private void throwIfCalledOnMainThread() {
1206 if (Looper.getMainLooper().isCurrentThread()) {
1207 throw new IllegalStateException("should not be called from the main thread.");
1208 }
1209 }
1210
1211 public void registerStrongAuthTracker(final StrongAuthTracker strongAuthTracker) {
1212 try {
1213 getLockSettings().registerStrongAuthTracker(strongAuthTracker.getStub());
1214 } catch (RemoteException e) {
1215 throw new RuntimeException("Could not register StrongAuthTracker");
1216 }
1217 }
1218
1219 public void unregisterStrongAuthTracker(final StrongAuthTracker strongAuthTracker) {
1220 try {
1221 getLockSettings().unregisterStrongAuthTracker(strongAuthTracker.getStub());
1222 } catch (RemoteException e) {
1223 Log.e(TAG, "Could not unregister StrongAuthTracker", e);
1224 }
1225 }
1226
1227 /** Register the given WeakEscrowTokenRemovedListener. */
1228 public boolean registerWeakEscrowTokenRemovedListener(
1229 @NonNull final IWeakEscrowTokenRemovedListener listener) {
1230 try {
1231 return getLockSettings().registerWeakEscrowTokenRemovedListener(listener);
1232 } catch (RemoteException e) {
1233 Log.e(TAG, "Could not register WeakEscrowTokenRemovedListener.");
1234 throw e.rethrowFromSystemServer();
1235 }
1236 }
1237
1238 /** Unregister the given WeakEscrowTokenRemovedListener. */
1239 public boolean unregisterWeakEscrowTokenRemovedListener(
1240 @NonNull final IWeakEscrowTokenRemovedListener listener) {
1241 try {
1242 return getLockSettings().unregisterWeakEscrowTokenRemovedListener(listener);
1243 } catch (RemoteException e) {
1244 Log.e(TAG, "Could not register WeakEscrowTokenRemovedListener.");
1245 throw e.rethrowFromSystemServer();
1246 }
1247 }
1248
1249 public void reportSuccessfulBiometricUnlock(boolean isStrongBiometric, int userId) {
1250 try {
1251 getLockSettings().reportSuccessfulBiometricUnlock(isStrongBiometric, userId);
1252 } catch (RemoteException e) {
1253 Log.e(TAG, "Could not report successful biometric unlock", e);
1254 }
1255 }
1256
1257 public void scheduleNonStrongBiometricIdleTimeout(int userId) {
1258 try {
1259 getLockSettings().scheduleNonStrongBiometricIdleTimeout(userId);
1260 } catch (RemoteException e) {
1261 Log.e(TAG, "Could not schedule non-strong biometric idle timeout", e);
1262 }
1263 }
1264
1265 /**
1266 * @see StrongAuthTracker#getStrongAuthForUser
1267 */
1268 public int getStrongAuthForUser(int userId) {
1269 try {
1270 return getLockSettings().getStrongAuthForUser(userId);
1271 } catch (RemoteException e) {
1272 Log.e(TAG, "Could not get StrongAuth", e);
1273 return StrongAuthTracker.getDefaultFlags(mContext);
1274 }
1275 }
1276
1277 /**
1278 * Whether the user is not allowed to set any credentials via PASSWORD_QUALITY_MANAGED.
1279 */
1280 public boolean isCredentialsDisabledForUser(int userId) {
1281 return getDevicePolicyManager().getPasswordQuality(/* admin= */ null, userId)
1282 == PASSWORD_QUALITY_MANAGED;
1283 }
1284
1285 /**
1286 * @see StrongAuthTracker#isTrustAllowedForUser
1287 */
1288 public boolean isTrustAllowedForUser(int userId) {
1289 return getStrongAuthForUser(userId) == StrongAuthTracker.STRONG_AUTH_NOT_REQUIRED;
1290 }
1291
1292 /**
1293 * @see StrongAuthTracker#isBiometricAllowedForUser(int)
1294 */
1295 public boolean isBiometricAllowedForUser(int userId) {
1296 return (getStrongAuthForUser(userId) & ~StrongAuthTracker.ALLOWING_BIOMETRIC) == 0;
1297 }
1298
1299 public boolean isUserInLockdown(int userId) {
1300 return getStrongAuthForUser(userId)
1301 == StrongAuthTracker.STRONG_AUTH_REQUIRED_AFTER_USER_LOCKDOWN;
1302 }
1303
1304 private static class WrappedCallback extends ICheckCredentialProgressCallback.Stub {
1305
1306 private Handler mHandler;
1307 private CheckCredentialProgressCallback mCallback;
1308
1309 WrappedCallback(Handler handler, CheckCredentialProgressCallback callback) {
1310 mHandler = handler;
1311 mCallback = callback;
1312 }
1313
1314 @Override
1315 public void onCredentialVerified() throws RemoteException {
1316 if (mHandler == null) {
1317 Log.e(TAG, "Handler is null during callback");
1318 }
1319 // Kill reference immediately to allow early GC at client side independent of
1320 // when system_server decides to lose its reference to the
1321 // ICheckCredentialProgressCallback binder object.
1322 mHandler.post(() -> {
1323 mCallback.onEarlyMatched();
1324 mCallback = null;
1325 });
1326 mHandler = null;
1327 }
1328 }
1329
1330 private ICheckCredentialProgressCallback wrapCallback(
1331 final CheckCredentialProgressCallback callback) {
1332 if (callback == null) {
1333 return null;
1334 } else {
1335 if (mHandler == null) {
1336 throw new IllegalStateException("Must construct LockPatternUtils on a looper thread"
1337 + " to use progress callbacks.");
1338 }
1339 return new WrappedCallback(mHandler, callback);
1340 }
1341 }
1342
1343 private LockSettingsInternal getLockSettingsInternal() {
1344 LockSettingsInternal service = LocalServices.getService(LockSettingsInternal.class);
1345 if (service == null) {
1346 throw new SecurityException("Only available to system server itself");
1347 }
1348 return service;
1349 }
1350 /**
1351 * Create an escrow token for the current user, which can later be used to unlock FBE
1352 * or change user password.
1353 *
1354 * After adding, if the user currently has lockscreen password, they will need to perform a
1355 * confirm credential operation in order to activate the token for future use. If the user
1356 * has no secure lockscreen, then the token is activated immediately.
1357 *
1358 * <p>This method is only available to code running in the system server process itself.
1359 *
1360 * @return a unique 64-bit token handle which is needed to refer to this token later.
1361 */
1362 public long addEscrowToken(byte[] token, int userId,
1363 @Nullable EscrowTokenStateChangeCallback callback) {
1364 return getLockSettingsInternal().addEscrowToken(token, userId, callback);
1365 }
1366
1367 /**
1368 * Create a weak escrow token for the current user, which can later be used to unlock FBE
1369 * or change user password.
1370 *
1371 * After adding, if the user currently has lockscreen password, they will need to perform a
1372 * confirm credential operation in order to activate the token for future use. If the user
1373 * has no secure lockscreen, then the token is activated immediately.
1374 *
1375 * If the user changes or removes lockscreen password, activated weak escrow tokens will be
1376 * removed.
1377 *
1378 * @return a unique 64-bit token handle which is needed to refer to this token later.
1379 */
1380 public long addWeakEscrowToken(byte[] token, int userId,
1381 @NonNull IWeakEscrowTokenActivatedListener callback) {
1382 try {
1383 return getLockSettings().addWeakEscrowToken(token, userId, callback);
1384 } catch (RemoteException e) {
1385 Log.e(TAG, "Could not add weak token.");
1386 throw e.rethrowFromSystemServer();
1387 }
1388 }
1389
1390 /**
1391 * Callback interface to notify when an added escrow token has been activated.
1392 */
1393 public interface EscrowTokenStateChangeCallback {
1394 /**
1395 * The method to be called when the token is activated.
1396 * @param handle 64 bit handle corresponding to the escrow token
1397 * @param userId user for whom the escrow token has been added
1398 */
1399 void onEscrowTokenActivated(long handle, int userId);
1400 }
1401
1402 /**
1403 * Remove an escrow token.
1404 *
1405 * <p>This method is only available to code running in the system server process itself.
1406 *
1407 * @return true if the given handle refers to a valid token previously returned from
1408 * {@link #addEscrowToken}, whether it's active or not. return false otherwise.
1409 */
1410 public boolean removeEscrowToken(long handle, int userId) {
1411 return getLockSettingsInternal().removeEscrowToken(handle, userId);
1412 }
1413
1414 /**
1415 * Remove a weak escrow token.
1416 *
1417 * @return true if the given handle refers to a valid weak token previously returned from
1418 * {@link #addWeakEscrowToken}, whether it's active or not. return false otherwise.
1419 */
1420 public boolean removeWeakEscrowToken(long handle, int userId) {
1421 try {
1422 return getLockSettings().removeWeakEscrowToken(handle, userId);
1423 } catch (RemoteException e) {
1424 Log.e(TAG, "Could not remove the weak token.");
1425 throw e.rethrowFromSystemServer();
1426 }
1427 }
1428
1429 /**
1430 * Check if the given escrow token is active or not. Only active token can be used to call
1431 * {@link #setLockCredentialWithToken} and {@link #unlockUserWithToken}
1432 *
1433 * <p>This method is only available to code running in the system server process itself.
1434 */
1435 public boolean isEscrowTokenActive(long handle, int userId) {
1436 return getLockSettingsInternal().isEscrowTokenActive(handle, userId);
1437 }
1438
1439 /**
1440 * Check if the given weak escrow token is active or not. Only active token can be used to call
1441 * {@link #setLockCredentialWithToken} and {@link #unlockUserWithToken}
1442 */
1443 public boolean isWeakEscrowTokenActive(long handle, int userId) {
1444 try {
1445 return getLockSettings().isWeakEscrowTokenActive(handle, userId);
1446 } catch (RemoteException e) {
1447 Log.e(TAG, "Could not check the weak token.");
1448 throw e.rethrowFromSystemServer();
1449 }
1450 }
1451
1452 /** Check if the given weak escrow token is valid. */
1453 public boolean isWeakEscrowTokenValid(long handle, byte[] token, int userId) {
1454 try {
1455 return getLockSettings().isWeakEscrowTokenValid(handle, token, userId);
1456 } catch (RemoteException e) {
1457 Log.e(TAG, "Could not validate the weak token.");
1458 throw e.rethrowFromSystemServer();
1459 }
1460 }
1461
1462 /**
1463 * Change a user's lock credential with a pre-configured escrow token.
1464 *
1465 * <p>This method is only available to code running in the system server process itself.
1466 *
1467 * @param credential The new credential to be set
1468 * @param tokenHandle Handle of the escrow token
1469 * @param token Escrow token
1470 * @param userHandle The user who's lock credential to be changed
1471 * @return {@code true} if the operation is successful.
1472 */
1473 public boolean setLockCredentialWithToken(@NonNull LockscreenCredential credential,
1474 long tokenHandle, byte[] token, int userHandle) {
1475 if (!hasSecureLockScreen() && credential.getType() != CREDENTIAL_TYPE_NONE) {
1476 throw new UnsupportedOperationException(
1477 "This operation requires the lock screen feature.");
1478 }
1479 credential.checkLength();
1480 LockSettingsInternal localService = getLockSettingsInternal();
1481
1482 return localService.setLockCredentialWithToken(credential, tokenHandle, token, userHandle);
1483 }
1484
1485 /**
1486 * Unlock the specified user by an pre-activated escrow token. This should have the same effect
1487 * on device encryption as the user entering their lockscreen credentials for the first time after
1488 * boot, this includes unlocking the user's credential-encrypted storage as well as the keystore
1489 *
1490 * <p>This method is only available to code running in the system server process itself.
1491 *
1492 * @return {@code true} if the supplied token is valid and unlock succeeds,
1493 * {@code false} otherwise.
1494 */
1495 public boolean unlockUserWithToken(long tokenHandle, byte[] token, int userId) {
1496 return getLockSettingsInternal().unlockUserWithToken(tokenHandle, token, userId);
1497 }
1498
1499
1500 /**
1501 * Callback to be notified about progress when checking credentials.
1502 */
1503 public interface CheckCredentialProgressCallback {
1504
1505 /**
1506 * Called as soon as possible when we know that the credentials match but the user hasn't
1507 * been fully unlocked.
1508 */
1509 void onEarlyMatched();
1510 }
1511
1512 /**
1513 * Tracks the global strong authentication state.
1514 */
1515 public static class StrongAuthTracker {
1516
1517 @IntDef(flag = true,
1518 value = { STRONG_AUTH_NOT_REQUIRED,
1519 STRONG_AUTH_REQUIRED_AFTER_BOOT,
1520 STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW,
1521 SOME_AUTH_REQUIRED_AFTER_USER_REQUEST,
1522 STRONG_AUTH_REQUIRED_AFTER_LOCKOUT,
1523 STRONG_AUTH_REQUIRED_AFTER_TIMEOUT,
1524 STRONG_AUTH_REQUIRED_AFTER_USER_LOCKDOWN,
1525 STRONG_AUTH_REQUIRED_AFTER_NON_STRONG_BIOMETRICS_TIMEOUT,
1526 SOME_AUTH_REQUIRED_AFTER_TRUSTAGENT_EXPIRED})
1527 @Retention(RetentionPolicy.SOURCE)
1528 public @interface StrongAuthFlags {}
1529
1530 /**
1531 * Strong authentication is not required.
1532 */
1533 public static final int STRONG_AUTH_NOT_REQUIRED = 0x0;
1534
1535 /**
1536 * Strong authentication is required because the user has not authenticated since boot.
1537 */
1538 public static final int STRONG_AUTH_REQUIRED_AFTER_BOOT = 0x1;
1539
1540 /**
1541 * Strong authentication is required because a device admin has requested it.
1542 */
1543 public static final int STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW = 0x2;
1544
1545 /**
1546 * Some authentication is required because the user has temporarily disabled trust.
1547 */
1548 public static final int SOME_AUTH_REQUIRED_AFTER_USER_REQUEST = 0x4;
1549
1550 /**
1551 * Strong authentication is required because the user has been locked out after too many
1552 * attempts.
1553 */
1554 public static final int STRONG_AUTH_REQUIRED_AFTER_LOCKOUT = 0x8;
1555
1556 /**
1557 * Strong authentication is required because it hasn't been used for a time required by
1558 * a device admin.
1559 */
1560 public static final int STRONG_AUTH_REQUIRED_AFTER_TIMEOUT = 0x10;
1561
1562 /**
1563 * Strong authentication is required because the user has triggered lockdown.
1564 */
1565 public static final int STRONG_AUTH_REQUIRED_AFTER_USER_LOCKDOWN = 0x20;
1566
1567 /**
1568 * Strong authentication is required to prepare for unattended upgrade.
1569 */
1570 public static final int STRONG_AUTH_REQUIRED_FOR_UNATTENDED_UPDATE = 0x40;
1571
1572 /**
1573 * Strong authentication is required because it hasn't been used for a time after a
1574 * non-strong biometric (i.e. weak or convenience biometric) is used to unlock device.
1575 */
1576 public static final int STRONG_AUTH_REQUIRED_AFTER_NON_STRONG_BIOMETRICS_TIMEOUT = 0x80;
1577
1578 /**
1579 * Some authentication is required because the trustagent either timed out or was disabled
1580 * manually.
1581 */
1582 public static final int SOME_AUTH_REQUIRED_AFTER_TRUSTAGENT_EXPIRED = 0x100;
1583
1584 /**
1585 * Strong auth flags that do not prevent biometric methods from being accepted as auth.
1586 * If any other flags are set, biometric authentication is disabled.
1587 */
1588 private static final int ALLOWING_BIOMETRIC = STRONG_AUTH_NOT_REQUIRED
1589 | SOME_AUTH_REQUIRED_AFTER_USER_REQUEST
1590 | SOME_AUTH_REQUIRED_AFTER_TRUSTAGENT_EXPIRED;
1591
1592 private final SparseIntArray mStrongAuthRequiredForUser = new SparseIntArray();
1593 private final H mHandler;
1594 private final int mDefaultStrongAuthFlags;
1595
1596 private final SparseBooleanArray mIsNonStrongBiometricAllowedForUser =
1597 new SparseBooleanArray();
1598 private final boolean mDefaultIsNonStrongBiometricAllowed = true;
1599
1600 public StrongAuthTracker(Context context) {
1601 this(context, Looper.myLooper());
1602 }
1603
1604 /**
1605 * @param looper the looper on whose thread calls to {@link #onStrongAuthRequiredChanged}
1606 * will be scheduled.
1607 * @param context the current {@link Context}
1608 */
1609 public StrongAuthTracker(Context context, Looper looper) {
1610 mHandler = new H(looper);
1611 mDefaultStrongAuthFlags = getDefaultFlags(context);
1612 }
1613
1614 public static @StrongAuthFlags int getDefaultFlags(Context context) {
1615 boolean strongAuthRequired = context.getResources().getBoolean(
1616 com.android.internal.R.bool.config_strongAuthRequiredOnBoot);
1617 return strongAuthRequired ? STRONG_AUTH_REQUIRED_AFTER_BOOT : STRONG_AUTH_NOT_REQUIRED;
1618 }
1619
1620 /**
1621 * Returns {@link #STRONG_AUTH_NOT_REQUIRED} if strong authentication is not required,
1622 * otherwise returns a combination of {@link StrongAuthFlags} indicating why strong
1623 * authentication is required.
1624 *
1625 * @param userId the user for whom the state is queried.
1626 */
1627 public @StrongAuthFlags int getStrongAuthForUser(int userId) {
1628 return mStrongAuthRequiredForUser.get(userId, mDefaultStrongAuthFlags);
1629 }
1630
1631 /**
1632 * @return true if unlocking with trust alone is allowed for {@code userId} by the current
1633 * strong authentication requirements.
1634 */
1635 public boolean isTrustAllowedForUser(int userId) {
1636 return getStrongAuthForUser(userId) == STRONG_AUTH_NOT_REQUIRED;
1637 }
1638
1639 /**
1640 * @return true if unlocking with a biometric method alone is allowed for {@code userId}
1641 * by the current strong authentication requirements.
1642 */
1643 public boolean isBiometricAllowedForUser(boolean isStrongBiometric, int userId) {
1644 boolean allowed = ((getStrongAuthForUser(userId) & ~ALLOWING_BIOMETRIC) == 0);
1645 if (!isStrongBiometric) {
1646 allowed &= isNonStrongBiometricAllowedAfterIdleTimeout(userId);
1647 }
1648 return allowed;
1649 }
1650
1651 /**
1652 * @return true if unlocking with a non-strong (i.e. weak or convenience) biometric method
1653 * alone is allowed for {@code userId}, otherwise returns false.
1654 */
1655 public boolean isNonStrongBiometricAllowedAfterIdleTimeout(int userId) {
1656 return mIsNonStrongBiometricAllowedForUser.get(userId,
1657 mDefaultIsNonStrongBiometricAllowed);
1658 }
1659
1660 /**
1661 * Called when the strong authentication requirements for {@code userId} changed.
1662 */
1663 public void onStrongAuthRequiredChanged(int userId) {
1664 }
1665
1666 /**
1667 * Called when whether non-strong biometric is allowed for {@code userId} changed.
1668 */
1669 public void onIsNonStrongBiometricAllowedChanged(int userId) {
1670 }
1671
1672 protected void handleStrongAuthRequiredChanged(@StrongAuthFlags int strongAuthFlags,
1673 int userId) {
1674 int oldValue = getStrongAuthForUser(userId);
1675 if (strongAuthFlags != oldValue) {
1676 if (strongAuthFlags == mDefaultStrongAuthFlags) {
1677 mStrongAuthRequiredForUser.delete(userId);
1678 } else {
1679 mStrongAuthRequiredForUser.put(userId, strongAuthFlags);
1680 }
1681 onStrongAuthRequiredChanged(userId);
1682 }
1683 }
1684
1685 protected void handleIsNonStrongBiometricAllowedChanged(boolean allowed,
1686 int userId) {
1687 boolean oldValue = isNonStrongBiometricAllowedAfterIdleTimeout(userId);
1688 if (allowed != oldValue) {
1689 if (allowed == mDefaultIsNonStrongBiometricAllowed) {
1690 mIsNonStrongBiometricAllowedForUser.delete(userId);
1691 } else {
1692 mIsNonStrongBiometricAllowedForUser.put(userId, allowed);
1693 }
1694 onIsNonStrongBiometricAllowedChanged(userId);
1695 }
1696 }
1697
1698 private final IStrongAuthTracker.Stub mStub = new IStrongAuthTracker.Stub() {
1699 @Override
1700 public void onStrongAuthRequiredChanged(@StrongAuthFlags int strongAuthFlags,
1701 int userId) {
1702 mHandler.obtainMessage(H.MSG_ON_STRONG_AUTH_REQUIRED_CHANGED,
1703 strongAuthFlags, userId).sendToTarget();
1704 }
1705
1706 @Override
1707 public void onIsNonStrongBiometricAllowedChanged(boolean allowed, int userId) {
1708 mHandler.obtainMessage(H.MSG_ON_IS_NON_STRONG_BIOMETRIC_ALLOWED_CHANGED,
1709 allowed ? 1 : 0, userId).sendToTarget();
1710 }
1711 };
1712
1713 public IStrongAuthTracker.Stub getStub() {
1714 return mStub;
1715 }
1716
1717 private class H extends Handler {
1718 static final int MSG_ON_STRONG_AUTH_REQUIRED_CHANGED = 1;
1719 static final int MSG_ON_IS_NON_STRONG_BIOMETRIC_ALLOWED_CHANGED = 2;
1720
1721 public H(Looper looper) {
1722 super(looper);
1723 }
1724
1725 @Override
1726 public void handleMessage(Message msg) {
1727 switch (msg.what) {
1728 case MSG_ON_STRONG_AUTH_REQUIRED_CHANGED:
1729 handleStrongAuthRequiredChanged(msg.arg1, msg.arg2);
1730 break;
1731 case MSG_ON_IS_NON_STRONG_BIOMETRIC_ALLOWED_CHANGED:
1732 handleIsNonStrongBiometricAllowedChanged(msg.arg1 == 1 /* allowed */,
1733 msg.arg2);
1734 break;
1735 }
1736 }
1737 }
1738 }
1739
1740 public void enableSyntheticPassword() {
1741 setLong(SYNTHETIC_PASSWORD_ENABLED_KEY, 1L, UserHandle.USER_SYSTEM);
1742 }
1743
1744 public void disableSyntheticPassword() {
1745 setLong(SYNTHETIC_PASSWORD_ENABLED_KEY, 0L, UserHandle.USER_SYSTEM);
1746 }
1747
1748 public boolean isSyntheticPasswordEnabled() {
1749 return getLong(SYNTHETIC_PASSWORD_ENABLED_KEY, SYNTHETIC_PASSWORD_ENABLED_BY_DEFAULT,
1750 UserHandle.USER_SYSTEM) != 0;
1751 }
1752
1753 /**
1754 * Returns whether the given user has pending escrow tokens
1755 */
1756 public boolean hasPendingEscrowToken(int userId) {
1757 try {
1758 return getLockSettings().hasPendingEscrowToken(userId);
1759 } catch (RemoteException e) {
1760 e.rethrowFromSystemServer();
1761 }
1762 return false;
1763 }
1764
1765 /**
1766 * Return true if the device supports the lock screen feature, false otherwise.
1767 */
1768 public boolean hasSecureLockScreen() {
1769 if (mHasSecureLockScreen == null) {
1770 try {
1771 mHasSecureLockScreen = Boolean.valueOf(getLockSettings().hasSecureLockScreen());
1772 } catch (RemoteException e) {
1773 e.rethrowFromSystemServer();
1774 }
1775 }
1776 return mHasSecureLockScreen.booleanValue();
1777 }
1778
1779 public static boolean userOwnsFrpCredential(Context context, UserInfo info) {
1780 return info != null && info.isPrimary() && info.isAdmin() && frpCredentialEnabled(context);
1781 }
1782
1783 public static boolean frpCredentialEnabled(Context context) {
1784 return FRP_CREDENTIAL_ENABLED && context.getResources().getBoolean(
1785 com.android.internal.R.bool.config_enableCredentialFactoryResetProtection);
1786 }
1787
1788 /**
1789 * Attempt to rederive the unified work challenge for the specified profile user and unlock the
1790 * user. If successful, this would allow the user to leave quiet mode automatically without
1791 * additional user authentication.
1792 *
1793 * This is made possible by the framework storing an encrypted copy of the unified challenge
1794 * auth-bound to the primary user's lockscreen. As long as the primery user has unlocked
1795 * recently (7 days), the framework will be able to decrypt it and plug the secret into the
1796 * unlock flow.
1797 *
1798 * @return {@code true} if automatic unlocking is successful, {@code false} otherwise.
1799 */
1800 public boolean tryUnlockWithCachedUnifiedChallenge(int userId) {
1801 try {
1802 return getLockSettings().tryUnlockWithCachedUnifiedChallenge(userId);
1803 } catch (RemoteException re) {
1804 return false;
1805 }
1806 }
1807
1808 /** Remove cached unified profile challenge, for testing and CTS usage. */
1809 public void removeCachedUnifiedChallenge(int userId) {
1810 try {
1811 getLockSettings().removeCachedUnifiedChallenge(userId);
1812 } catch (RemoteException re) {
1813 re.rethrowFromSystemServer();
1814 }
1815 }
1816 }