LockPatternUtils.java revision 69aa4a953f040277c19c23208bb830f52796c8c6
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 android.content.ContentResolver;
20import android.os.SystemClock;
21import android.provider.Settings;
22import android.security.MessageDigest;
23import android.text.TextUtils;
24import android.util.Log;
25
26import com.google.android.collect.Lists;
27
28import java.io.FileNotFoundException;
29import java.io.IOException;
30import java.io.RandomAccessFile;
31import java.security.NoSuchAlgorithmException;
32import java.util.Arrays;
33import java.util.List;
34
35/**
36 * Utilities for the lock patten and its settings.
37 */
38public class LockPatternUtils {
39
40    private static final String TAG = "LockPatternUtils";
41
42    private static final String LOCK_PATTERN_FILE = "/system/gesture.key";
43    private static final String LOCK_PASSWORD_FILE = "/system/password.key";
44
45    /**
46     * The maximum number of incorrect attempts before the user is prevented
47     * from trying again for {@link #FAILED_ATTEMPT_TIMEOUT_MS}.
48     */
49    public static final int FAILED_ATTEMPTS_BEFORE_TIMEOUT = 5;
50
51    /**
52     * The number of incorrect attempts before which we fall back on an alternative
53     * method of verifying the user, and resetting their lock pattern.
54     */
55    public static final int FAILED_ATTEMPTS_BEFORE_RESET = 20;
56
57    /**
58     * How long the user is prevented from trying again after entering the
59     * wrong pattern too many times.
60     */
61    public static final long FAILED_ATTEMPT_TIMEOUT_MS = 30000L;
62
63    /**
64     * The interval of the countdown for showing progress of the lockout.
65     */
66    public static final long FAILED_ATTEMPT_COUNTDOWN_INTERVAL_MS = 1000L;
67
68    /**
69     * The minimum number of dots in a valid pattern.
70     */
71    public static final int MIN_LOCK_PATTERN_SIZE = 4;
72
73    /**
74     * Type of password being stored.
75     * pattern = pattern screen
76     * pin = digit-only password
77     * password = alphanumeric password
78     */
79    public static final int MODE_PATTERN = 0;
80    public static final int MODE_PIN = 1;
81    public static final int MODE_PASSWORD = 2;
82
83    /**
84     * The minimum number of dots the user must include in a wrong pattern
85     * attempt for it to be counted against the counts that affect
86     * {@link #FAILED_ATTEMPTS_BEFORE_TIMEOUT} and {@link #FAILED_ATTEMPTS_BEFORE_RESET}
87     */
88    public static final int MIN_PATTERN_REGISTER_FAIL = 3;
89
90    private final static String LOCKOUT_PERMANENT_KEY = "lockscreen.lockedoutpermanently";
91    private final static String LOCKOUT_ATTEMPT_DEADLINE = "lockscreen.lockoutattemptdeadline";
92    private final static String PATTERN_EVER_CHOSEN_KEY = "lockscreen.patterneverchosen";
93    public final static String PASSWORD_TYPE_KEY = "lockscreen.password_type";
94
95    private final ContentResolver mContentResolver;
96
97    private static String sLockPatternFilename;
98    private static String sLockPasswordFilename;
99
100    /**
101     * @param contentResolver Used to look up and save settings.
102     */
103    public LockPatternUtils(ContentResolver contentResolver) {
104        mContentResolver = contentResolver;
105        // Initialize the location of gesture lock file
106        if (sLockPatternFilename == null) {
107            sLockPatternFilename = android.os.Environment.getDataDirectory()
108                    .getAbsolutePath() + LOCK_PATTERN_FILE;
109            sLockPasswordFilename = android.os.Environment.getDataDirectory()
110                    .getAbsolutePath() + LOCK_PASSWORD_FILE;
111        }
112
113    }
114
115    /**
116     * Check to see if a pattern matches the saved pattern.  If no pattern exists,
117     * always returns true.
118     * @param pattern The pattern to check.
119     * @return Whether the pattern matches the stored one.
120     */
121    public boolean checkPattern(List<LockPatternView.Cell> pattern) {
122        try {
123            // Read all the bytes from the file
124            RandomAccessFile raf = new RandomAccessFile(sLockPatternFilename, "r");
125            final byte[] stored = new byte[(int) raf.length()];
126            int got = raf.read(stored, 0, stored.length);
127            raf.close();
128            if (got <= 0) {
129                return true;
130            }
131            // Compare the hash from the file with the entered pattern's hash
132            return Arrays.equals(stored, LockPatternUtils.patternToHash(pattern));
133        } catch (FileNotFoundException fnfe) {
134            return true;
135        } catch (IOException ioe) {
136            return true;
137        }
138    }
139
140    /**
141     * Check to see if a password matches the saved password.  If no password exists,
142     * always returns true.
143     * @param password The password to check.
144     * @return Whether the password matches the stored one.
145     */
146    public boolean checkPassword(String password) {
147        try {
148            // Read all the bytes from the file
149            RandomAccessFile raf = new RandomAccessFile(sLockPasswordFilename, "r");
150            final byte[] stored = new byte[(int) raf.length()];
151            int got = raf.read(stored, 0, stored.length);
152            raf.close();
153            if (got <= 0) {
154                return true;
155            }
156            // Compare the hash from the file with the entered password's hash
157            return Arrays.equals(stored, LockPatternUtils.passwordToHash(password));
158        } catch (FileNotFoundException fnfe) {
159            return true;
160        } catch (IOException ioe) {
161            return true;
162        }
163    }
164
165    /**
166     * Checks to see if the given file exists and contains any data. Returns true if it does,
167     * false otherwise.
168     * @param filename
169     * @return true if file exists and is non-empty.
170     */
171    private boolean nonEmptyFileExists(String filename) {
172        try {
173            // Check if we can read a byte from the file
174            RandomAccessFile raf = new RandomAccessFile(filename, "r");
175            byte first = raf.readByte();
176            raf.close();
177            return true;
178        } catch (FileNotFoundException fnfe) {
179            return false;
180        } catch (IOException ioe) {
181            return false;
182        }
183    }
184
185    /**
186     * Check to see if the user has stored a lock pattern.
187     * @return Whether a saved pattern exists.
188     */
189    public boolean savedPatternExists() {
190        return nonEmptyFileExists(sLockPatternFilename);
191    }
192
193    /**
194     * Check to see if the user has stored a lock pattern.
195     * @return Whether a saved pattern exists.
196     */
197    public boolean savedPasswordExists() {
198        return nonEmptyFileExists(sLockPasswordFilename);
199    }
200
201    /**
202     * Return true if the user has ever chosen a pattern.  This is true even if the pattern is
203     * currently cleared.
204     *
205     * @return True if the user has ever chosen a pattern.
206     */
207    public boolean isPatternEverChosen() {
208        return getBoolean(PATTERN_EVER_CHOSEN_KEY);
209    }
210
211    /**
212     * Save a lock pattern.
213     * @param pattern The new pattern to save.
214     */
215    public void saveLockPattern(List<LockPatternView.Cell> pattern) {
216        // Compute the hash
217        final byte[] hash  = LockPatternUtils.patternToHash(pattern);
218        try {
219            // Write the hash to file
220            RandomAccessFile raf = new RandomAccessFile(sLockPatternFilename, "rw");
221            // Truncate the file if pattern is null, to clear the lock
222            if (pattern == null) {
223                raf.setLength(0);
224            } else {
225                raf.write(hash, 0, hash.length);
226            }
227            raf.close();
228            setBoolean(PATTERN_EVER_CHOSEN_KEY, true);
229            setLong(PASSWORD_TYPE_KEY, MODE_PATTERN);
230        } catch (FileNotFoundException fnfe) {
231            // Cant do much, unless we want to fail over to using the settings provider
232            Log.e(TAG, "Unable to save lock pattern to " + sLockPatternFilename);
233        } catch (IOException ioe) {
234            // Cant do much
235            Log.e(TAG, "Unable to save lock pattern to " + sLockPatternFilename);
236        }
237    }
238
239    /**
240     * Save a lock password.
241     * @param password The password to save
242     */
243    public void saveLockPassword(String password) {
244        // Compute the hash
245        boolean numericHint = password != null ? TextUtils.isDigitsOnly(password) : false;
246        final byte[] hash  = LockPatternUtils.passwordToHash(password);
247        try {
248            // Write the hash to file
249            RandomAccessFile raf = new RandomAccessFile(sLockPasswordFilename, "rw");
250            // Truncate the file if pattern is null, to clear the lock
251            if (password == null) {
252                raf.setLength(0);
253            } else {
254                raf.write(hash, 0, hash.length);
255            }
256            raf.close();
257            setLong(PASSWORD_TYPE_KEY, numericHint ? MODE_PIN : MODE_PASSWORD);
258        } catch (FileNotFoundException fnfe) {
259            // Cant do much, unless we want to fail over to using the settings provider
260            Log.e(TAG, "Unable to save lock pattern to " + sLockPasswordFilename);
261        } catch (IOException ioe) {
262            // Cant do much
263            Log.e(TAG, "Unable to save lock pattern to " + sLockPasswordFilename);
264        }
265    }
266
267    public int getPasswordMode() {
268        return (int) getLong(PASSWORD_TYPE_KEY, MODE_PATTERN);
269    }
270
271    /**
272     * Deserialize a pattern.
273     * @param string The pattern serialized with {@link #patternToString}
274     * @return The pattern.
275     */
276    public static List<LockPatternView.Cell> stringToPattern(String string) {
277        List<LockPatternView.Cell> result = Lists.newArrayList();
278
279        final byte[] bytes = string.getBytes();
280        for (int i = 0; i < bytes.length; i++) {
281            byte b = bytes[i];
282            result.add(LockPatternView.Cell.of(b / 3, b % 3));
283        }
284        return result;
285    }
286
287    /**
288     * Serialize a pattern.
289     * @param pattern The pattern.
290     * @return The pattern in string form.
291     */
292    public static String patternToString(List<LockPatternView.Cell> pattern) {
293        if (pattern == null) {
294            return "";
295        }
296        final int patternSize = pattern.size();
297
298        byte[] res = new byte[patternSize];
299        for (int i = 0; i < patternSize; i++) {
300            LockPatternView.Cell cell = pattern.get(i);
301            res[i] = (byte) (cell.getRow() * 3 + cell.getColumn());
302        }
303        return new String(res);
304    }
305
306    /*
307     * Generate an SHA-1 hash for the pattern. Not the most secure, but it is
308     * at least a second level of protection. First level is that the file
309     * is in a location only readable by the system process.
310     * @param pattern the gesture pattern.
311     * @return the hash of the pattern in a byte array.
312     */
313    private static byte[] patternToHash(List<LockPatternView.Cell> pattern) {
314        if (pattern == null) {
315            return null;
316        }
317
318        final int patternSize = pattern.size();
319        byte[] res = new byte[patternSize];
320        for (int i = 0; i < patternSize; i++) {
321            LockPatternView.Cell cell = pattern.get(i);
322            res[i] = (byte) (cell.getRow() * 3 + cell.getColumn());
323        }
324        try {
325            MessageDigest md = MessageDigest.getInstance("SHA-1");
326            byte[] hash = md.digest(res);
327            return hash;
328        } catch (NoSuchAlgorithmException nsa) {
329            return res;
330        }
331    }
332
333    /*
334     * Generate a hash for the given password. To avoid brute force attacks, we use a salted hash.
335     * Not the most secure, but it is at least a second level of protection. First level is that
336     * the file is in a location only readable by the system process.
337     * @param password the gesture pattern.
338     * @return the hash of the pattern in a byte array.
339     */
340     public static byte[] passwordToHash(String password) {
341        if (password == null) {
342            return null;
343        }
344        String algo = null;
345        byte[] hashed = null;
346        try {
347            long salt = 0x2374868151054924L; // TODO: make this unique to device
348            byte[] saltedPassword = (password + Long.toString(salt)).getBytes();
349            byte[] sha1 = MessageDigest.getInstance(algo = "SHA-1").digest(saltedPassword);
350            byte[] md5 = MessageDigest.getInstance(algo = "MD5").digest(saltedPassword);
351            hashed = (toHex(sha1) + toHex(md5)).getBytes();
352        } catch (NoSuchAlgorithmException e) {
353            Log.w(TAG, "Failed to encode string because of missing algorithm: " + algo);
354        }
355        return hashed;
356    }
357
358    private static String toHex(byte[] ary) {
359        final String hex = "0123456789ABCDEF";
360        String ret = "";
361        for (int i = 0; i < ary.length; i++) {
362            ret += hex.charAt((ary[i] >> 4) & 0xf);
363            ret += hex.charAt(ary[i] & 0xf);
364        }
365        return ret;
366    }
367
368    /**
369     * @return Whether the lock password is enabled.
370     */
371    public boolean isLockPasswordEnabled() {
372        long mode = getLong(PASSWORD_TYPE_KEY, 0);
373        return savedPasswordExists() && (mode == MODE_PASSWORD || mode == MODE_PIN);
374    }
375
376    /**
377     * @return Whether the lock pattern is enabled.
378     */
379    public boolean isLockPatternEnabled() {
380        return getBoolean(Settings.System.LOCK_PATTERN_ENABLED)
381                && getLong(PASSWORD_TYPE_KEY, MODE_PATTERN) == MODE_PATTERN;
382    }
383
384    /**
385     * Set whether the lock pattern is enabled.
386     */
387    public void setLockPatternEnabled(boolean enabled) {
388        setBoolean(Settings.System.LOCK_PATTERN_ENABLED, enabled);
389    }
390
391    /**
392     * @return Whether the visible pattern is enabled.
393     */
394    public boolean isVisiblePatternEnabled() {
395        return getBoolean(Settings.System.LOCK_PATTERN_VISIBLE);
396    }
397
398    /**
399     * Set whether the visible pattern is enabled.
400     */
401    public void setVisiblePatternEnabled(boolean enabled) {
402        setBoolean(Settings.System.LOCK_PATTERN_VISIBLE, enabled);
403    }
404
405    /**
406     * @return Whether tactile feedback for the pattern is enabled.
407     */
408    public boolean isTactileFeedbackEnabled() {
409        return getBoolean(Settings.System.LOCK_PATTERN_TACTILE_FEEDBACK_ENABLED);
410    }
411
412    /**
413     * Set whether tactile feedback for the pattern is enabled.
414     */
415    public void setTactileFeedbackEnabled(boolean enabled) {
416        setBoolean(Settings.System.LOCK_PATTERN_TACTILE_FEEDBACK_ENABLED, enabled);
417    }
418
419    /**
420     * Set and store the lockout deadline, meaning the user can't attempt his/her unlock
421     * pattern until the deadline has passed.
422     * @return the chosen deadline.
423     */
424    public long setLockoutAttemptDeadline() {
425        final long deadline = SystemClock.elapsedRealtime() + FAILED_ATTEMPT_TIMEOUT_MS;
426        setLong(LOCKOUT_ATTEMPT_DEADLINE, deadline);
427        return deadline;
428    }
429
430    /**
431     * @return The elapsed time in millis in the future when the user is allowed to
432     *   attempt to enter his/her lock pattern, or 0 if the user is welcome to
433     *   enter a pattern.
434     */
435    public long getLockoutAttemptDeadline() {
436        final long deadline = getLong(LOCKOUT_ATTEMPT_DEADLINE, 0L);
437        final long now = SystemClock.elapsedRealtime();
438        if (deadline < now || deadline > (now + FAILED_ATTEMPT_TIMEOUT_MS)) {
439            return 0L;
440        }
441        return deadline;
442    }
443
444    /**
445     * @return Whether the user is permanently locked out until they verify their
446     *   credentials.  Occurs after {@link #FAILED_ATTEMPTS_BEFORE_RESET} failed
447     *   attempts.
448     */
449    public boolean isPermanentlyLocked() {
450        return getBoolean(LOCKOUT_PERMANENT_KEY);
451    }
452
453    /**
454     * Set the state of whether the device is permanently locked, meaning the user
455     * must authenticate via other means.
456     *
457     * @param locked Whether the user is permanently locked out until they verify their
458     *   credentials.  Occurs after {@link #FAILED_ATTEMPTS_BEFORE_RESET} failed
459     *   attempts.
460     */
461    public void setPermanentlyLocked(boolean locked) {
462        setBoolean(LOCKOUT_PERMANENT_KEY, locked);
463    }
464
465    /**
466     * @return A formatted string of the next alarm (for showing on the lock screen),
467     *   or null if there is no next alarm.
468     */
469    public String getNextAlarm() {
470        String nextAlarm = Settings.System.getString(mContentResolver,
471                Settings.System.NEXT_ALARM_FORMATTED);
472        if (nextAlarm == null || TextUtils.isEmpty(nextAlarm)) {
473            return null;
474        }
475        return nextAlarm;
476    }
477
478    private boolean getBoolean(String systemSettingKey) {
479        return 1 ==
480                android.provider.Settings.System.getInt(
481                        mContentResolver,
482                        systemSettingKey, 0);
483    }
484
485    private void setBoolean(String systemSettingKey, boolean enabled) {
486        android.provider.Settings.System.putInt(
487                        mContentResolver,
488                        systemSettingKey,
489                        enabled ? 1 : 0);
490    }
491
492    private long getLong(String systemSettingKey, long def) {
493        return android.provider.Settings.System.getLong(mContentResolver, systemSettingKey, def);
494    }
495
496    private void setLong(String systemSettingKey, long value) {
497        android.provider.Settings.System.putLong(mContentResolver, systemSettingKey, value);
498    }
499
500    public boolean isSecure() {
501        long mode = getPasswordMode();
502        boolean secure = mode == MODE_PATTERN && isLockPatternEnabled() && savedPatternExists()
503            || (mode == MODE_PIN || mode == MODE_PASSWORD) && savedPasswordExists();
504        return secure;
505    }
506}
507