LockPatternUtils.java revision a4edd151c5266a2c794c95444fed67d19740cee3
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 17package com.android.internal.widget; 18 19import com.android.internal.R; 20import com.android.internal.telephony.ITelephony; 21import com.google.android.collect.Lists; 22 23import android.app.admin.DevicePolicyManager; 24import android.content.ContentResolver; 25import android.content.Context; 26import android.content.Intent; 27import android.content.pm.PackageManager; 28import android.os.FileObserver; 29import android.os.IBinder; 30import android.os.RemoteException; 31import android.os.ServiceManager; 32import android.os.SystemClock; 33import android.os.storage.IMountService; 34import android.provider.Settings; 35import android.security.KeyStore; 36import android.telephony.TelephonyManager; 37import android.text.TextUtils; 38import android.util.Log; 39import android.view.View; 40import android.widget.Button; 41 42import java.io.File; 43import java.io.FileNotFoundException; 44import java.io.IOException; 45import java.io.RandomAccessFile; 46import java.security.MessageDigest; 47import java.security.NoSuchAlgorithmException; 48import java.security.SecureRandom; 49import java.util.Arrays; 50import java.util.List; 51import java.util.concurrent.atomic.AtomicBoolean; 52 53/** 54 * Utilities for the lock pattern and its settings. 55 */ 56public class LockPatternUtils { 57 58 private static final String OPTION_ENABLE_FACELOCK = "enable_facelock"; 59 60 private static final String TAG = "LockPatternUtils"; 61 62 private static final String SYSTEM_DIRECTORY = "/system/"; 63 private static final String LOCK_PATTERN_FILE = "gesture.key"; 64 private static final String LOCK_PASSWORD_FILE = "password.key"; 65 66 /** 67 * The maximum number of incorrect attempts before the user is prevented 68 * from trying again for {@link #FAILED_ATTEMPT_TIMEOUT_MS}. 69 */ 70 public static final int FAILED_ATTEMPTS_BEFORE_TIMEOUT = 5; 71 72 /** 73 * The number of incorrect attempts before which we fall back on an alternative 74 * method of verifying the user, and resetting their lock pattern. 75 */ 76 public static final int FAILED_ATTEMPTS_BEFORE_RESET = 20; 77 78 /** 79 * How long the user is prevented from trying again after entering the 80 * wrong pattern too many times. 81 */ 82 public static final long FAILED_ATTEMPT_TIMEOUT_MS = 30000L; 83 84 /** 85 * The interval of the countdown for showing progress of the lockout. 86 */ 87 public static final long FAILED_ATTEMPT_COUNTDOWN_INTERVAL_MS = 1000L; 88 89 90 /** 91 * This dictates when we start telling the user that continued failed attempts will wipe 92 * their device. 93 */ 94 public static final int FAILED_ATTEMPTS_BEFORE_WIPE_GRACE = 5; 95 96 /** 97 * The minimum number of dots in a valid pattern. 98 */ 99 public static final int MIN_LOCK_PATTERN_SIZE = 4; 100 101 /** 102 * The minimum number of dots the user must include in a wrong pattern 103 * attempt for it to be counted against the counts that affect 104 * {@link #FAILED_ATTEMPTS_BEFORE_TIMEOUT} and {@link #FAILED_ATTEMPTS_BEFORE_RESET} 105 */ 106 public static final int MIN_PATTERN_REGISTER_FAIL = MIN_LOCK_PATTERN_SIZE; 107 108 private final static String LOCKOUT_PERMANENT_KEY = "lockscreen.lockedoutpermanently"; 109 private final static String LOCKOUT_ATTEMPT_DEADLINE = "lockscreen.lockoutattemptdeadline"; 110 private final static String PATTERN_EVER_CHOSEN_KEY = "lockscreen.patterneverchosen"; 111 public final static String PASSWORD_TYPE_KEY = "lockscreen.password_type"; 112 public static final String PASSWORD_TYPE_ALTERNATE_KEY = "lockscreen.password_type_alternate"; 113 private final static String LOCK_PASSWORD_SALT_KEY = "lockscreen.password_salt"; 114 private final static String DISABLE_LOCKSCREEN_KEY = "lockscreen.disabled"; 115 private final static String LOCKSCREEN_OPTIONS = "lockscreen.options"; 116 public final static String LOCKSCREEN_BIOMETRIC_WEAK_FALLBACK 117 = "lockscreen.biometric_weak_fallback"; 118 public final static String BIOMETRIC_WEAK_EVER_CHOSEN_KEY 119 = "lockscreen.biometricweakeverchosen"; 120 public final static String LOCKSCREEN_POWER_BUTTON_INSTANTLY_LOCKS 121 = "lockscreen.power_button_instantly_locks"; 122 123 private final static String PASSWORD_HISTORY_KEY = "lockscreen.passwordhistory"; 124 125 private final Context mContext; 126 private final ContentResolver mContentResolver; 127 private DevicePolicyManager mDevicePolicyManager; 128 private static String sLockPatternFilename; 129 private static String sLockPasswordFilename; 130 131 private static final AtomicBoolean sHaveNonZeroPatternFile = new AtomicBoolean(false); 132 private static final AtomicBoolean sHaveNonZeroPasswordFile = new AtomicBoolean(false); 133 134 private static FileObserver sPasswordObserver; 135 136 private static class PasswordFileObserver extends FileObserver { 137 public PasswordFileObserver(String path, int mask) { 138 super(path, mask); 139 } 140 141 @Override 142 public void onEvent(int event, String path) { 143 if (LOCK_PATTERN_FILE.equals(path)) { 144 Log.d(TAG, "lock pattern file changed"); 145 sHaveNonZeroPatternFile.set(new File(sLockPatternFilename).length() > 0); 146 } else if (LOCK_PASSWORD_FILE.equals(path)) { 147 Log.d(TAG, "lock password file changed"); 148 sHaveNonZeroPasswordFile.set(new File(sLockPasswordFilename).length() > 0); 149 } 150 } 151 } 152 153 public DevicePolicyManager getDevicePolicyManager() { 154 if (mDevicePolicyManager == null) { 155 mDevicePolicyManager = 156 (DevicePolicyManager)mContext.getSystemService(Context.DEVICE_POLICY_SERVICE); 157 if (mDevicePolicyManager == null) { 158 Log.e(TAG, "Can't get DevicePolicyManagerService: is it running?", 159 new IllegalStateException("Stack trace:")); 160 } 161 } 162 return mDevicePolicyManager; 163 } 164 /** 165 * @param contentResolver Used to look up and save settings. 166 */ 167 public LockPatternUtils(Context context) { 168 mContext = context; 169 mContentResolver = context.getContentResolver(); 170 171 // Initialize the location of gesture & PIN lock files 172 if (sLockPatternFilename == null) { 173 String dataSystemDirectory = 174 android.os.Environment.getDataDirectory().getAbsolutePath() + 175 SYSTEM_DIRECTORY; 176 sLockPatternFilename = dataSystemDirectory + LOCK_PATTERN_FILE; 177 sLockPasswordFilename = dataSystemDirectory + LOCK_PASSWORD_FILE; 178 sHaveNonZeroPatternFile.set(new File(sLockPatternFilename).length() > 0); 179 sHaveNonZeroPasswordFile.set(new File(sLockPasswordFilename).length() > 0); 180 int fileObserverMask = FileObserver.CLOSE_WRITE | FileObserver.DELETE | 181 FileObserver.MOVED_TO | FileObserver.CREATE; 182 sPasswordObserver = new PasswordFileObserver(dataSystemDirectory, fileObserverMask); 183 sPasswordObserver.startWatching(); 184 } 185 } 186 187 public int getRequestedMinimumPasswordLength() { 188 return getDevicePolicyManager().getPasswordMinimumLength(null); 189 } 190 191 192 /** 193 * Gets the device policy password mode. If the mode is non-specific, returns 194 * MODE_PATTERN which allows the user to choose anything. 195 */ 196 public int getRequestedPasswordQuality() { 197 return getDevicePolicyManager().getPasswordQuality(null); 198 } 199 200 public int getRequestedPasswordHistoryLength() { 201 return getDevicePolicyManager().getPasswordHistoryLength(null); 202 } 203 204 public int getRequestedPasswordMinimumLetters() { 205 return getDevicePolicyManager().getPasswordMinimumLetters(null); 206 } 207 208 public int getRequestedPasswordMinimumUpperCase() { 209 return getDevicePolicyManager().getPasswordMinimumUpperCase(null); 210 } 211 212 public int getRequestedPasswordMinimumLowerCase() { 213 return getDevicePolicyManager().getPasswordMinimumLowerCase(null); 214 } 215 216 public int getRequestedPasswordMinimumNumeric() { 217 return getDevicePolicyManager().getPasswordMinimumNumeric(null); 218 } 219 220 public int getRequestedPasswordMinimumSymbols() { 221 return getDevicePolicyManager().getPasswordMinimumSymbols(null); 222 } 223 224 public int getRequestedPasswordMinimumNonLetter() { 225 return getDevicePolicyManager().getPasswordMinimumNonLetter(null); 226 } 227 /** 228 * Returns the actual password mode, as set by keyguard after updating the password. 229 * 230 * @return 231 */ 232 public void reportFailedPasswordAttempt() { 233 getDevicePolicyManager().reportFailedPasswordAttempt(); 234 } 235 236 public void reportSuccessfulPasswordAttempt() { 237 getDevicePolicyManager().reportSuccessfulPasswordAttempt(); 238 } 239 240 /** 241 * Check to see if a pattern matches the saved pattern. If no pattern exists, 242 * always returns true. 243 * @param pattern The pattern to check. 244 * @return Whether the pattern matches the stored one. 245 */ 246 public boolean checkPattern(List<LockPatternView.Cell> pattern) { 247 try { 248 // Read all the bytes from the file 249 RandomAccessFile raf = new RandomAccessFile(sLockPatternFilename, "r"); 250 final byte[] stored = new byte[(int) raf.length()]; 251 int got = raf.read(stored, 0, stored.length); 252 raf.close(); 253 if (got <= 0) { 254 return true; 255 } 256 // Compare the hash from the file with the entered pattern's hash 257 return Arrays.equals(stored, LockPatternUtils.patternToHash(pattern)); 258 } catch (FileNotFoundException fnfe) { 259 return true; 260 } catch (IOException ioe) { 261 return true; 262 } 263 } 264 265 /** 266 * Check to see if a password matches the saved password. If no password exists, 267 * always returns true. 268 * @param password The password to check. 269 * @return Whether the password matches the stored one. 270 */ 271 public boolean checkPassword(String password) { 272 try { 273 // Read all the bytes from the file 274 RandomAccessFile raf = new RandomAccessFile(sLockPasswordFilename, "r"); 275 final byte[] stored = new byte[(int) raf.length()]; 276 int got = raf.read(stored, 0, stored.length); 277 raf.close(); 278 if (got <= 0) { 279 return true; 280 } 281 // Compare the hash from the file with the entered password's hash 282 return Arrays.equals(stored, passwordToHash(password)); 283 } catch (FileNotFoundException fnfe) { 284 return true; 285 } catch (IOException ioe) { 286 return true; 287 } 288 } 289 290 /** 291 * Check to see if a password matches any of the passwords stored in the 292 * password history. 293 * 294 * @param password The password to check. 295 * @return Whether the password matches any in the history. 296 */ 297 public boolean checkPasswordHistory(String password) { 298 String passwordHashString = new String(passwordToHash(password)); 299 String passwordHistory = getString(PASSWORD_HISTORY_KEY); 300 if (passwordHistory == null) { 301 return false; 302 } 303 // Password History may be too long... 304 int passwordHashLength = passwordHashString.length(); 305 int passwordHistoryLength = getRequestedPasswordHistoryLength(); 306 if(passwordHistoryLength == 0) { 307 return false; 308 } 309 int neededPasswordHistoryLength = passwordHashLength * passwordHistoryLength 310 + passwordHistoryLength - 1; 311 if (passwordHistory.length() > neededPasswordHistoryLength) { 312 passwordHistory = passwordHistory.substring(0, neededPasswordHistoryLength); 313 } 314 return passwordHistory.contains(passwordHashString); 315 } 316 317 /** 318 * Check to see if the user has stored a lock pattern. 319 * @return Whether a saved pattern exists. 320 */ 321 public boolean savedPatternExists() { 322 return sHaveNonZeroPatternFile.get(); 323 } 324 325 /** 326 * Check to see if the user has stored a lock pattern. 327 * @return Whether a saved pattern exists. 328 */ 329 public boolean savedPasswordExists() { 330 return sHaveNonZeroPasswordFile.get(); 331 } 332 333 /** 334 * Return true if the user has ever chosen a pattern. This is true even if the pattern is 335 * currently cleared. 336 * 337 * @return True if the user has ever chosen a pattern. 338 */ 339 public boolean isPatternEverChosen() { 340 return getBoolean(PATTERN_EVER_CHOSEN_KEY, false); 341 } 342 343 /** 344 * Return true if the user has ever chosen biometric weak. This is true even if biometric 345 * weak is not current set. 346 * 347 * @return True if the user has ever chosen biometric weak. 348 */ 349 public boolean isBiometricWeakEverChosen() { 350 return getBoolean(BIOMETRIC_WEAK_EVER_CHOSEN_KEY, false); 351 } 352 353 /** 354 * Used by device policy manager to validate the current password 355 * information it has. 356 */ 357 public int getActivePasswordQuality() { 358 int activePasswordQuality = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED; 359 // Note we don't want to use getKeyguardStoredPasswordQuality() because we want this to 360 // return biometric_weak if that is being used instead of the backup 361 int quality = 362 (int) getLong(PASSWORD_TYPE_KEY, DevicePolicyManager.PASSWORD_QUALITY_SOMETHING); 363 switch (quality) { 364 case DevicePolicyManager.PASSWORD_QUALITY_SOMETHING: 365 if (isLockPatternEnabled()) { 366 activePasswordQuality = DevicePolicyManager.PASSWORD_QUALITY_SOMETHING; 367 } 368 break; 369 case DevicePolicyManager.PASSWORD_QUALITY_BIOMETRIC_WEAK: 370 if (isBiometricWeakInstalled()) { 371 activePasswordQuality = DevicePolicyManager.PASSWORD_QUALITY_BIOMETRIC_WEAK; 372 } 373 break; 374 case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC: 375 if (isLockPasswordEnabled()) { 376 activePasswordQuality = DevicePolicyManager.PASSWORD_QUALITY_NUMERIC; 377 } 378 break; 379 case DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC: 380 if (isLockPasswordEnabled()) { 381 activePasswordQuality = DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC; 382 } 383 break; 384 case DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC: 385 if (isLockPasswordEnabled()) { 386 activePasswordQuality = DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC; 387 } 388 break; 389 case DevicePolicyManager.PASSWORD_QUALITY_COMPLEX: 390 if (isLockPasswordEnabled()) { 391 activePasswordQuality = DevicePolicyManager.PASSWORD_QUALITY_COMPLEX; 392 } 393 break; 394 } 395 396 return activePasswordQuality; 397 } 398 399 /** 400 * Clear any lock pattern or password. 401 */ 402 public void clearLock(boolean isFallback) { 403 if(!isFallback) deleteGallery(); 404 saveLockPassword(null, DevicePolicyManager.PASSWORD_QUALITY_SOMETHING); 405 setLockPatternEnabled(false); 406 saveLockPattern(null); 407 setLong(PASSWORD_TYPE_KEY, DevicePolicyManager.PASSWORD_QUALITY_SOMETHING); 408 setLong(PASSWORD_TYPE_ALTERNATE_KEY, DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED); 409 } 410 411 /** 412 * Disable showing lock screen at all when the DevicePolicyManager allows it. 413 * This is only meaningful if pattern, pin or password are not set. 414 * 415 * @param disable Disables lock screen when true 416 */ 417 public void setLockScreenDisabled(boolean disable) { 418 setLong(DISABLE_LOCKSCREEN_KEY, disable ? 1 : 0); 419 } 420 421 /** 422 * Determine if LockScreen can be disabled. This is used, for example, to tell if we should 423 * show LockScreen or go straight to the home screen. 424 * 425 * @return true if lock screen is can be disabled 426 */ 427 public boolean isLockScreenDisabled() { 428 return !isSecure() && getLong(DISABLE_LOCKSCREEN_KEY, 0) != 0; 429 } 430 431 /** 432 * Save a lock pattern. 433 * @param pattern The new pattern to save. 434 */ 435 public void saveLockPattern(List<LockPatternView.Cell> pattern) { 436 this.saveLockPattern(pattern, false); 437 } 438 439 /** 440 * Calls back SetupFaceLock to delete the temporary gallery file 441 */ 442 public void deleteTempGallery() { 443 Intent intent = new Intent().setClassName("com.android.facelock", 444 "com.android.facelock.SetupFaceLock"); 445 intent.putExtra("deleteTempGallery", true); 446 mContext.startActivity(intent); 447 } 448 449 /** 450 * Calls back SetupFaceLock to delete the gallery file when the lock type is changed 451 */ 452 void deleteGallery() { 453 if(usingBiometricWeak()) { 454 Intent intent = new Intent().setClassName("com.android.facelock", 455 "com.android.facelock.SetupFaceLock"); 456 intent.putExtra("deleteGallery", true); 457 mContext.startActivity(intent); 458 } 459 } 460 461 /** 462 * Save a lock pattern. 463 * @param pattern The new pattern to save. 464 * @param isFallback Specifies if this is a fallback to biometric weak 465 */ 466 public void saveLockPattern(List<LockPatternView.Cell> pattern, boolean isFallback) { 467 // Compute the hash 468 final byte[] hash = LockPatternUtils.patternToHash(pattern); 469 try { 470 // Write the hash to file 471 RandomAccessFile raf = new RandomAccessFile(sLockPatternFilename, "rw"); 472 // Truncate the file if pattern is null, to clear the lock 473 if (pattern == null) { 474 raf.setLength(0); 475 } else { 476 raf.write(hash, 0, hash.length); 477 } 478 raf.close(); 479 DevicePolicyManager dpm = getDevicePolicyManager(); 480 KeyStore keyStore = KeyStore.getInstance(); 481 if (pattern != null) { 482 keyStore.password(patternToString(pattern)); 483 setBoolean(PATTERN_EVER_CHOSEN_KEY, true); 484 if (!isFallback) { 485 deleteGallery(); 486 setLong(PASSWORD_TYPE_KEY, DevicePolicyManager.PASSWORD_QUALITY_SOMETHING); 487 } else { 488 setLong(PASSWORD_TYPE_KEY, DevicePolicyManager.PASSWORD_QUALITY_BIOMETRIC_WEAK); 489 setLong(PASSWORD_TYPE_ALTERNATE_KEY, 490 DevicePolicyManager.PASSWORD_QUALITY_SOMETHING); 491 finishBiometricWeak(); 492 } 493 dpm.setActivePasswordState(DevicePolicyManager.PASSWORD_QUALITY_SOMETHING, pattern 494 .size(), 0, 0, 0, 0, 0, 0); 495 } else { 496 if (keyStore.isEmpty()) { 497 keyStore.reset(); 498 } 499 dpm.setActivePasswordState(DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED, 0, 0, 500 0, 0, 0, 0, 0); 501 } 502 } catch (FileNotFoundException fnfe) { 503 // Cant do much, unless we want to fail over to using the settings 504 // provider 505 Log.e(TAG, "Unable to save lock pattern to " + sLockPatternFilename); 506 } catch (IOException ioe) { 507 // Cant do much 508 Log.e(TAG, "Unable to save lock pattern to " + sLockPatternFilename); 509 } 510 } 511 512 /** 513 * Compute the password quality from the given password string. 514 */ 515 static public int computePasswordQuality(String password) { 516 boolean hasDigit = false; 517 boolean hasNonDigit = false; 518 final int len = password.length(); 519 for (int i = 0; i < len; i++) { 520 if (Character.isDigit(password.charAt(i))) { 521 hasDigit = true; 522 } else { 523 hasNonDigit = true; 524 } 525 } 526 527 if (hasNonDigit && hasDigit) { 528 return DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC; 529 } 530 if (hasNonDigit) { 531 return DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC; 532 } 533 if (hasDigit) { 534 return DevicePolicyManager.PASSWORD_QUALITY_NUMERIC; 535 } 536 return DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED; 537 } 538 539 /** Update the encryption password if it is enabled **/ 540 private void updateEncryptionPassword(String password) { 541 DevicePolicyManager dpm = getDevicePolicyManager(); 542 if (dpm.getStorageEncryptionStatus() != DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE) { 543 return; 544 } 545 546 IBinder service = ServiceManager.getService("mount"); 547 if (service == null) { 548 Log.e(TAG, "Could not find the mount service to update the encryption password"); 549 return; 550 } 551 552 IMountService mountService = IMountService.Stub.asInterface(service); 553 try { 554 mountService.changeEncryptionPassword(password); 555 } catch (RemoteException e) { 556 Log.e(TAG, "Error changing encryption password", e); 557 } 558 } 559 560 /** 561 * Save a lock password. Does not ensure that the password is as good 562 * as the requested mode, but will adjust the mode to be as good as the 563 * pattern. 564 * @param password The password to save 565 * @param quality {@see DevicePolicyManager#getPasswordQuality(android.content.ComponentName)} 566 */ 567 public void saveLockPassword(String password, int quality) { 568 this.saveLockPassword(password, quality, false); 569 } 570 571 /** 572 * Save a lock password. Does not ensure that the password is as good 573 * as the requested mode, but will adjust the mode to be as good as the 574 * pattern. 575 * @param password The password to save 576 * @param quality {@see DevicePolicyManager#getPasswordQuality(android.content.ComponentName)} 577 * @param isFallback Specifies if this is a fallback to biometric weak 578 */ 579 public void saveLockPassword(String password, int quality, boolean isFallback) { 580 // Compute the hash 581 final byte[] hash = passwordToHash(password); 582 try { 583 // Write the hash to file 584 RandomAccessFile raf = new RandomAccessFile(sLockPasswordFilename, "rw"); 585 // Truncate the file if pattern is null, to clear the lock 586 if (password == null) { 587 raf.setLength(0); 588 } else { 589 raf.write(hash, 0, hash.length); 590 } 591 raf.close(); 592 DevicePolicyManager dpm = getDevicePolicyManager(); 593 KeyStore keyStore = KeyStore.getInstance(); 594 if (password != null) { 595 // Update the encryption password. 596 updateEncryptionPassword(password); 597 598 // Update the keystore password 599 keyStore.password(password); 600 601 int computedQuality = computePasswordQuality(password); 602 if (!isFallback) { 603 deleteGallery(); 604 setLong(PASSWORD_TYPE_KEY, Math.max(quality, computedQuality)); 605 } else { 606 setLong(PASSWORD_TYPE_KEY, DevicePolicyManager.PASSWORD_QUALITY_BIOMETRIC_WEAK); 607 setLong(PASSWORD_TYPE_ALTERNATE_KEY, Math.max(quality, computedQuality)); 608 finishBiometricWeak(); 609 } 610 if (computedQuality != DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED) { 611 int letters = 0; 612 int uppercase = 0; 613 int lowercase = 0; 614 int numbers = 0; 615 int symbols = 0; 616 int nonletter = 0; 617 for (int i = 0; i < password.length(); i++) { 618 char c = password.charAt(i); 619 if (c >= 'A' && c <= 'Z') { 620 letters++; 621 uppercase++; 622 } else if (c >= 'a' && c <= 'z') { 623 letters++; 624 lowercase++; 625 } else if (c >= '0' && c <= '9') { 626 numbers++; 627 nonletter++; 628 } else { 629 symbols++; 630 nonletter++; 631 } 632 } 633 dpm.setActivePasswordState(Math.max(quality, computedQuality), password 634 .length(), letters, uppercase, lowercase, numbers, symbols, nonletter); 635 } else { 636 // The password is not anything. 637 dpm.setActivePasswordState( 638 DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED, 0, 0, 0, 0, 0, 0, 0); 639 } 640 // Add the password to the password history. We assume all 641 // password 642 // hashes have the same length for simplicity of implementation. 643 String passwordHistory = getString(PASSWORD_HISTORY_KEY); 644 if (passwordHistory == null) { 645 passwordHistory = new String(); 646 } 647 int passwordHistoryLength = getRequestedPasswordHistoryLength(); 648 if (passwordHistoryLength == 0) { 649 passwordHistory = ""; 650 } else { 651 passwordHistory = new String(hash) + "," + passwordHistory; 652 // Cut it to contain passwordHistoryLength hashes 653 // and passwordHistoryLength -1 commas. 654 passwordHistory = passwordHistory.substring(0, Math.min(hash.length 655 * passwordHistoryLength + passwordHistoryLength - 1, passwordHistory 656 .length())); 657 } 658 setString(PASSWORD_HISTORY_KEY, passwordHistory); 659 } else { 660 // Conditionally reset the keystore if empty. If 661 // non-empty, we are just switching key guard type 662 if (keyStore.isEmpty()) { 663 keyStore.reset(); 664 } 665 dpm.setActivePasswordState( 666 DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED, 0, 0, 0, 0, 0, 0, 0); 667 } 668 } catch (FileNotFoundException fnfe) { 669 // Cant do much, unless we want to fail over to using the settings provider 670 Log.e(TAG, "Unable to save lock pattern to " + sLockPasswordFilename); 671 } catch (IOException ioe) { 672 // Cant do much 673 Log.e(TAG, "Unable to save lock pattern to " + sLockPasswordFilename); 674 } 675 } 676 677 /** 678 * Retrieves the quality mode we're in. 679 * {@see DevicePolicyManager#getPasswordQuality(android.content.ComponentName)} 680 * 681 * @return stored password quality 682 */ 683 public int getKeyguardStoredPasswordQuality() { 684 int quality = 685 (int) getLong(PASSWORD_TYPE_KEY, DevicePolicyManager.PASSWORD_QUALITY_SOMETHING); 686 // If the user has chosen to use weak biometric sensor, then return the backup locking 687 // method and treat biometric as a special case. 688 if (quality == DevicePolicyManager.PASSWORD_QUALITY_BIOMETRIC_WEAK) { 689 quality = 690 (int) getLong(PASSWORD_TYPE_ALTERNATE_KEY, 691 DevicePolicyManager.PASSWORD_QUALITY_SOMETHING); 692 } 693 return quality; 694 } 695 696 /** 697 * @return true if the lockscreen method is set to biometric weak 698 */ 699 public boolean usingBiometricWeak() { 700 int quality = 701 (int) getLong(PASSWORD_TYPE_KEY, DevicePolicyManager.PASSWORD_QUALITY_SOMETHING); 702 return quality == DevicePolicyManager.PASSWORD_QUALITY_BIOMETRIC_WEAK; 703 } 704 705 /** 706 * Deserialize a pattern. 707 * @param string The pattern serialized with {@link #patternToString} 708 * @return The pattern. 709 */ 710 public static List<LockPatternView.Cell> stringToPattern(String string) { 711 List<LockPatternView.Cell> result = Lists.newArrayList(); 712 713 final byte[] bytes = string.getBytes(); 714 for (int i = 0; i < bytes.length; i++) { 715 byte b = bytes[i]; 716 result.add(LockPatternView.Cell.of(b / 3, b % 3)); 717 } 718 return result; 719 } 720 721 /** 722 * Serialize a pattern. 723 * @param pattern The pattern. 724 * @return The pattern in string form. 725 */ 726 public static String patternToString(List<LockPatternView.Cell> pattern) { 727 if (pattern == null) { 728 return ""; 729 } 730 final int patternSize = pattern.size(); 731 732 byte[] res = new byte[patternSize]; 733 for (int i = 0; i < patternSize; i++) { 734 LockPatternView.Cell cell = pattern.get(i); 735 res[i] = (byte) (cell.getRow() * 3 + cell.getColumn()); 736 } 737 return new String(res); 738 } 739 740 /* 741 * Generate an SHA-1 hash for the pattern. Not the most secure, but it is 742 * at least a second level of protection. First level is that the file 743 * is in a location only readable by the system process. 744 * @param pattern the gesture pattern. 745 * @return the hash of the pattern in a byte array. 746 */ 747 private static byte[] patternToHash(List<LockPatternView.Cell> pattern) { 748 if (pattern == null) { 749 return null; 750 } 751 752 final int patternSize = pattern.size(); 753 byte[] res = new byte[patternSize]; 754 for (int i = 0; i < patternSize; i++) { 755 LockPatternView.Cell cell = pattern.get(i); 756 res[i] = (byte) (cell.getRow() * 3 + cell.getColumn()); 757 } 758 try { 759 MessageDigest md = MessageDigest.getInstance("SHA-1"); 760 byte[] hash = md.digest(res); 761 return hash; 762 } catch (NoSuchAlgorithmException nsa) { 763 return res; 764 } 765 } 766 767 private String getSalt() { 768 long salt = getLong(LOCK_PASSWORD_SALT_KEY, 0); 769 if (salt == 0) { 770 try { 771 salt = SecureRandom.getInstance("SHA1PRNG").nextLong(); 772 setLong(LOCK_PASSWORD_SALT_KEY, salt); 773 Log.v(TAG, "Initialized lock password salt"); 774 } catch (NoSuchAlgorithmException e) { 775 // Throw an exception rather than storing a password we'll never be able to recover 776 throw new IllegalStateException("Couldn't get SecureRandom number", e); 777 } 778 } 779 return Long.toHexString(salt); 780 } 781 782 /* 783 * Generate a hash for the given password. To avoid brute force attacks, we use a salted hash. 784 * Not the most secure, but it is at least a second level of protection. First level is that 785 * the file is in a location only readable by the system process. 786 * @param password the gesture pattern. 787 * @return the hash of the pattern in a byte array. 788 */ 789 public byte[] passwordToHash(String password) { 790 if (password == null) { 791 return null; 792 } 793 String algo = null; 794 byte[] hashed = null; 795 try { 796 byte[] saltedPassword = (password + getSalt()).getBytes(); 797 byte[] sha1 = MessageDigest.getInstance(algo = "SHA-1").digest(saltedPassword); 798 byte[] md5 = MessageDigest.getInstance(algo = "MD5").digest(saltedPassword); 799 hashed = (toHex(sha1) + toHex(md5)).getBytes(); 800 } catch (NoSuchAlgorithmException e) { 801 Log.w(TAG, "Failed to encode string because of missing algorithm: " + algo); 802 } 803 return hashed; 804 } 805 806 private static String toHex(byte[] ary) { 807 final String hex = "0123456789ABCDEF"; 808 String ret = ""; 809 for (int i = 0; i < ary.length; i++) { 810 ret += hex.charAt((ary[i] >> 4) & 0xf); 811 ret += hex.charAt(ary[i] & 0xf); 812 } 813 return ret; 814 } 815 816 /** 817 * @return Whether the lock password is enabled, or if it is set as a backup for biometric weak 818 */ 819 public boolean isLockPasswordEnabled() { 820 long mode = getLong(PASSWORD_TYPE_KEY, 0); 821 long backupMode = getLong(PASSWORD_TYPE_ALTERNATE_KEY, 0); 822 final boolean passwordEnabled = mode == DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC 823 || mode == DevicePolicyManager.PASSWORD_QUALITY_NUMERIC 824 || mode == DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC 825 || mode == DevicePolicyManager.PASSWORD_QUALITY_COMPLEX; 826 final boolean backupEnabled = backupMode == DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC 827 || backupMode == DevicePolicyManager.PASSWORD_QUALITY_NUMERIC 828 || backupMode == DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC 829 || backupMode == DevicePolicyManager.PASSWORD_QUALITY_COMPLEX; 830 831 return savedPasswordExists() && (passwordEnabled || 832 (usingBiometricWeak() && backupEnabled)); 833 } 834 835 /** 836 * @return Whether the lock pattern is enabled, or if it is set as a backup for biometric weak 837 */ 838 public boolean isLockPatternEnabled() { 839 final boolean backupEnabled = 840 getLong(PASSWORD_TYPE_ALTERNATE_KEY, DevicePolicyManager.PASSWORD_QUALITY_SOMETHING) 841 == DevicePolicyManager.PASSWORD_QUALITY_SOMETHING; 842 843 return getBoolean(Settings.Secure.LOCK_PATTERN_ENABLED, false) 844 && (getLong(PASSWORD_TYPE_KEY, DevicePolicyManager.PASSWORD_QUALITY_SOMETHING) 845 == DevicePolicyManager.PASSWORD_QUALITY_SOMETHING || 846 (usingBiometricWeak() && backupEnabled)); 847 } 848 849 /** 850 * @return Whether biometric weak lock is installed and that the front facing camera exists 851 */ 852 public boolean isBiometricWeakInstalled() { 853 // Check that the system flag was set 854 if (!OPTION_ENABLE_FACELOCK.equals(getString(LOCKSCREEN_OPTIONS))) { 855 return false; 856 } 857 858 // Check that it's installed 859 PackageManager pm = mContext.getPackageManager(); 860 try { 861 pm.getPackageInfo("com.android.facelock", PackageManager.GET_ACTIVITIES); 862 } catch (PackageManager.NameNotFoundException e) { 863 return false; 864 } 865 866 // Check that the camera is enabled 867 if (!pm.hasSystemFeature(PackageManager.FEATURE_CAMERA_FRONT)) { 868 return false; 869 } 870 if (getDevicePolicyManager().getCameraDisabled(null)) { 871 return false; 872 } 873 874 875 return true; 876 } 877 878 /** 879 * Set whether the lock pattern is enabled. 880 */ 881 public void setLockPatternEnabled(boolean enabled) { 882 setBoolean(Settings.Secure.LOCK_PATTERN_ENABLED, enabled); 883 } 884 885 /** 886 * @return Whether the visible pattern is enabled. 887 */ 888 public boolean isVisiblePatternEnabled() { 889 return getBoolean(Settings.Secure.LOCK_PATTERN_VISIBLE, false); 890 } 891 892 /** 893 * Set whether the visible pattern is enabled. 894 */ 895 public void setVisiblePatternEnabled(boolean enabled) { 896 setBoolean(Settings.Secure.LOCK_PATTERN_VISIBLE, enabled); 897 } 898 899 /** 900 * @return Whether tactile feedback for the pattern is enabled. 901 */ 902 public boolean isTactileFeedbackEnabled() { 903 return getBoolean(Settings.Secure.LOCK_PATTERN_TACTILE_FEEDBACK_ENABLED, false); 904 } 905 906 /** 907 * Set whether tactile feedback for the pattern is enabled. 908 */ 909 public void setTactileFeedbackEnabled(boolean enabled) { 910 setBoolean(Settings.Secure.LOCK_PATTERN_TACTILE_FEEDBACK_ENABLED, enabled); 911 } 912 913 /** 914 * Set and store the lockout deadline, meaning the user can't attempt his/her unlock 915 * pattern until the deadline has passed. 916 * @return the chosen deadline. 917 */ 918 public long setLockoutAttemptDeadline() { 919 final long deadline = SystemClock.elapsedRealtime() + FAILED_ATTEMPT_TIMEOUT_MS; 920 setLong(LOCKOUT_ATTEMPT_DEADLINE, deadline); 921 return deadline; 922 } 923 924 /** 925 * @return The elapsed time in millis in the future when the user is allowed to 926 * attempt to enter his/her lock pattern, or 0 if the user is welcome to 927 * enter a pattern. 928 */ 929 public long getLockoutAttemptDeadline() { 930 final long deadline = getLong(LOCKOUT_ATTEMPT_DEADLINE, 0L); 931 final long now = SystemClock.elapsedRealtime(); 932 if (deadline < now || deadline > (now + FAILED_ATTEMPT_TIMEOUT_MS)) { 933 return 0L; 934 } 935 return deadline; 936 } 937 938 /** 939 * @return Whether the user is permanently locked out until they verify their 940 * credentials. Occurs after {@link #FAILED_ATTEMPTS_BEFORE_RESET} failed 941 * attempts. 942 */ 943 public boolean isPermanentlyLocked() { 944 return getBoolean(LOCKOUT_PERMANENT_KEY, false); 945 } 946 947 /** 948 * Set the state of whether the device is permanently locked, meaning the user 949 * must authenticate via other means. 950 * 951 * @param locked Whether the user is permanently locked out until they verify their 952 * credentials. Occurs after {@link #FAILED_ATTEMPTS_BEFORE_RESET} failed 953 * attempts. 954 */ 955 public void setPermanentlyLocked(boolean locked) { 956 setBoolean(LOCKOUT_PERMANENT_KEY, locked); 957 } 958 959 public boolean isEmergencyCallCapable() { 960 return mContext.getResources().getBoolean( 961 com.android.internal.R.bool.config_voice_capable); 962 } 963 964 public boolean isPukUnlockScreenEnable() { 965 return mContext.getResources().getBoolean( 966 com.android.internal.R.bool.config_enable_puk_unlock_screen); 967 } 968 969 public boolean isEmergencyCallEnabledWhileSimLocked() { 970 return mContext.getResources().getBoolean( 971 com.android.internal.R.bool.config_enable_emergency_call_while_sim_locked); 972 } 973 974 /** 975 * @return A formatted string of the next alarm (for showing on the lock screen), 976 * or null if there is no next alarm. 977 */ 978 public String getNextAlarm() { 979 String nextAlarm = Settings.System.getString(mContentResolver, 980 Settings.System.NEXT_ALARM_FORMATTED); 981 if (nextAlarm == null || TextUtils.isEmpty(nextAlarm)) { 982 return null; 983 } 984 return nextAlarm; 985 } 986 987 private boolean getBoolean(String secureSettingKey, boolean defaultValue) { 988 return 1 == 989 android.provider.Settings.Secure.getInt(mContentResolver, secureSettingKey, 990 defaultValue ? 1 : 0); 991 } 992 993 private void setBoolean(String secureSettingKey, boolean enabled) { 994 android.provider.Settings.Secure.putInt(mContentResolver, secureSettingKey, 995 enabled ? 1 : 0); 996 } 997 998 private long getLong(String secureSettingKey, long def) { 999 return android.provider.Settings.Secure.getLong(mContentResolver, secureSettingKey, def); 1000 } 1001 1002 private void setLong(String secureSettingKey, long value) { 1003 android.provider.Settings.Secure.putLong(mContentResolver, secureSettingKey, value); 1004 } 1005 1006 private String getString(String secureSettingKey) { 1007 return android.provider.Settings.Secure.getString(mContentResolver, secureSettingKey); 1008 } 1009 1010 private void setString(String secureSettingKey, String value) { 1011 android.provider.Settings.Secure.putString(mContentResolver, secureSettingKey, value); 1012 } 1013 1014 public boolean isSecure() { 1015 long mode = getKeyguardStoredPasswordQuality(); 1016 final boolean isPattern = mode == DevicePolicyManager.PASSWORD_QUALITY_SOMETHING; 1017 final boolean isPassword = mode == DevicePolicyManager.PASSWORD_QUALITY_NUMERIC 1018 || mode == DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC 1019 || mode == DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC 1020 || mode == DevicePolicyManager.PASSWORD_QUALITY_COMPLEX; 1021 final boolean secure = isPattern && isLockPatternEnabled() && savedPatternExists() 1022 || isPassword && savedPasswordExists(); 1023 return secure; 1024 } 1025 1026 /** 1027 * Sets the emergency button visibility based on isEmergencyCallCapable(). 1028 * 1029 * If the emergency button is visible, sets the text on the emergency button 1030 * to indicate what action will be taken. 1031 * 1032 * If there's currently a call in progress, the button will take them to the call 1033 * @param button the button to update 1034 * @param the phone state: 1035 * {@link TelephonyManager#CALL_STATE_IDLE} 1036 * {@link TelephonyManager#CALL_STATE_RINGING} 1037 * {@link TelephonyManager#CALL_STATE_OFFHOOK} 1038 * @param shown indicates whether the given screen wants the emergency button to show at all 1039 */ 1040 public void updateEmergencyCallButtonState(Button button, int phoneState, boolean shown) { 1041 if (isEmergencyCallCapable() && shown) { 1042 button.setVisibility(View.VISIBLE); 1043 } else { 1044 button.setVisibility(View.GONE); 1045 return; 1046 } 1047 1048 int textId; 1049 if (phoneState == TelephonyManager.CALL_STATE_OFFHOOK) { 1050 // show "return to call" text and show phone icon 1051 textId = R.string.lockscreen_return_to_call; 1052 int phoneCallIcon = R.drawable.stat_sys_phone_call; 1053 button.setCompoundDrawablesWithIntrinsicBounds(phoneCallIcon, 0, 0, 0); 1054 } else { 1055 textId = R.string.lockscreen_emergency_call; 1056 int emergencyIcon = R.drawable.ic_emergency; 1057 button.setCompoundDrawablesWithIntrinsicBounds(emergencyIcon, 0, 0, 0); 1058 } 1059 button.setText(textId); 1060 } 1061 1062 /** 1063 * Resumes a call in progress. Typically launched from the EmergencyCall button 1064 * on various lockscreens. 1065 * 1066 * @return true if we were able to tell InCallScreen to show. 1067 */ 1068 public boolean resumeCall() { 1069 ITelephony phone = ITelephony.Stub.asInterface(ServiceManager.checkService("phone")); 1070 try { 1071 if (phone != null && phone.showCallScreen()) { 1072 return true; 1073 } 1074 } catch (RemoteException e) { 1075 // What can we do? 1076 } 1077 return false; 1078 } 1079 1080 private void finishBiometricWeak() { 1081 setBoolean(BIOMETRIC_WEAK_EVER_CHOSEN_KEY, true); 1082 1083 // Launch intent to show final screen, this also 1084 // moves the temporary gallery to the actual gallery 1085 Intent intent = new Intent(); 1086 intent.setClassName("com.android.facelock", 1087 "com.android.facelock.SetupEndScreen"); 1088 mContext.startActivity(intent); 1089 } 1090 1091 public void setPowerButtonInstantlyLocks(boolean enabled) { 1092 setBoolean(LOCKSCREEN_POWER_BUTTON_INSTANTLY_LOCKS, enabled); 1093 } 1094 1095 public boolean getPowerButtonInstantlyLocks() { 1096 return getBoolean(LOCKSCREEN_POWER_BUTTON_INSTANTLY_LOCKS, true); 1097 } 1098 1099} 1100