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