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