LockPatternUtils.java revision 9066cfe9886ac131c34d59ed0e2d287b0e3c0087
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
44    /**
45     * The maximum number of incorrect attempts before the user is prevented
46     * from trying again for {@link #FAILED_ATTEMPT_TIMEOUT_MS}.
47     */
48    public static final int FAILED_ATTEMPTS_BEFORE_TIMEOUT = 5;
49
50    /**
51     * The number of incorrect attempts before which we fall back on an alternative
52     * method of verifying the user, and resetting their lock pattern.
53     */
54    public static final int FAILED_ATTEMPTS_BEFORE_RESET = 20;
55
56    /**
57     * How long the user is prevented from trying again after entering the
58     * wrong pattern too many times.
59     */
60    public static final long FAILED_ATTEMPT_TIMEOUT_MS = 30000L;
61
62    /**
63     * The interval of the countdown for showing progress of the lockout.
64     */
65    public static final long FAILED_ATTEMPT_COUNTDOWN_INTERVAL_MS = 1000L;
66
67    /**
68     * The minimum number of dots in a valid pattern.
69     */
70    public static final int MIN_LOCK_PATTERN_SIZE = 4;
71
72    /**
73     * The minimum number of dots the user must include in a wrong pattern
74     * attempt for it to be counted against the counts that affect
75     * {@link #FAILED_ATTEMPTS_BEFORE_TIMEOUT} and {@link #FAILED_ATTEMPTS_BEFORE_RESET}
76     */
77    public static final int MIN_PATTERN_REGISTER_FAIL = 3;
78
79    private final static String LOCKOUT_PERMANENT_KEY = "lockscreen.lockedoutpermanently";
80    private final static String LOCKOUT_ATTEMPT_DEADLINE = "lockscreen.lockoutattemptdeadline";
81
82    private final ContentResolver mContentResolver;
83
84    private static String sLockPatternFilename;
85
86    /**
87     * @param contentResolver Used to look up and save settings.
88     */
89    public LockPatternUtils(ContentResolver contentResolver) {
90        mContentResolver = contentResolver;
91        // Initialize the location of gesture lock file
92        if (sLockPatternFilename == null) {
93            sLockPatternFilename = android.os.Environment.getDataDirectory()
94                    .getAbsolutePath() + LOCK_PATTERN_FILE;
95        }
96    }
97
98    /**
99     * Check to see if a pattern matches the saved pattern.  If no pattern exists,
100     * always returns true.
101     * @param pattern The pattern to check.
102     * @return Whether the pattern matchees the stored one.
103     */
104    public boolean checkPattern(List<LockPatternView.Cell> pattern) {
105        try {
106            // Read all the bytes from the file
107            RandomAccessFile raf = new RandomAccessFile(sLockPatternFilename, "r");
108            final byte[] stored = new byte[(int) raf.length()];
109            int got = raf.read(stored, 0, stored.length);
110            raf.close();
111            if (got <= 0) {
112                return true;
113            }
114            // Compare the hash from the file with the entered pattern's hash
115            return Arrays.equals(stored, LockPatternUtils.patternToHash(pattern));
116        } catch (FileNotFoundException fnfe) {
117            return true;
118        } catch (IOException ioe) {
119            return true;
120        }
121    }
122
123    /**
124     * Check to see if the user has stored a lock pattern.
125     * @return Whether a saved pattern exists.
126     */
127    public boolean savedPatternExists() {
128        try {
129            // Check if we can read a byte from the file
130            RandomAccessFile raf = new RandomAccessFile(sLockPatternFilename, "r");
131            byte first = raf.readByte();
132            raf.close();
133            return true;
134        } catch (FileNotFoundException fnfe) {
135            return false;
136        } catch (IOException ioe) {
137            return false;
138        }
139    }
140
141    /**
142     * Save a lock pattern.
143     * @param pattern The new pattern to save.
144     */
145    public void saveLockPattern(List<LockPatternView.Cell> pattern) {
146        // Compute the hash
147        final byte[] hash  = LockPatternUtils.patternToHash(pattern);
148        try {
149            // Write the hash to file
150            RandomAccessFile raf = new RandomAccessFile(sLockPatternFilename, "rw");
151            // Truncate the file if pattern is null, to clear the lock
152            if (pattern == null) {
153                raf.setLength(0);
154            } else {
155                raf.write(hash, 0, hash.length);
156            }
157            raf.close();
158        } catch (FileNotFoundException fnfe) {
159            // Cant do much, unless we want to fail over to using the settings provider
160            Log.e(TAG, "Unable to save lock pattern to " + sLockPatternFilename);
161        } catch (IOException ioe) {
162            // Cant do much
163            Log.e(TAG, "Unable to save lock pattern to " + sLockPatternFilename);
164        }
165    }
166
167    /**
168     * Deserialize a pattern.
169     * @param string The pattern serialized with {@link #patternToString}
170     * @return The pattern.
171     */
172    public static List<LockPatternView.Cell> stringToPattern(String string) {
173        List<LockPatternView.Cell> result = Lists.newArrayList();
174
175        final byte[] bytes = string.getBytes();
176        for (int i = 0; i < bytes.length; i++) {
177            byte b = bytes[i];
178            result.add(LockPatternView.Cell.of(b / 3, b % 3));
179        }
180        return result;
181    }
182
183    /**
184     * Serialize a pattern.
185     * @param pattern The pattern.
186     * @return The pattern in string form.
187     */
188    public static String patternToString(List<LockPatternView.Cell> pattern) {
189        if (pattern == null) {
190            return "";
191        }
192        final int patternSize = pattern.size();
193
194        byte[] res = new byte[patternSize];
195        for (int i = 0; i < patternSize; i++) {
196            LockPatternView.Cell cell = pattern.get(i);
197            res[i] = (byte) (cell.getRow() * 3 + cell.getColumn());
198        }
199        return new String(res);
200    }
201
202    /*
203     * Generate an SHA-1 hash for the pattern. Not the most secure, but it is
204     * at least a second level of protection. First level is that the file
205     * is in a location only readable by the system process.
206     * @param pattern the gesture pattern.
207     * @return the hash of the pattern in a byte array.
208     */
209    static byte[] patternToHash(List<LockPatternView.Cell> pattern) {
210        if (pattern == null) {
211            return null;
212        }
213
214        final int patternSize = pattern.size();
215        byte[] res = new byte[patternSize];
216        for (int i = 0; i < patternSize; i++) {
217            LockPatternView.Cell cell = pattern.get(i);
218            res[i] = (byte) (cell.getRow() * 3 + cell.getColumn());
219        }
220        try {
221            MessageDigest md = MessageDigest.getInstance("SHA-1");
222            byte[] hash = md.digest(res);
223            return hash;
224        } catch (NoSuchAlgorithmException nsa) {
225            return res;
226        }
227    }
228
229    /**
230     * @return Whether the lock pattern is enabled.
231     */
232    public boolean isLockPatternEnabled() {
233        return getBoolean(Settings.System.LOCK_PATTERN_ENABLED);
234    }
235
236    /**
237     * Set whether the lock pattern is enabled.
238     */
239    public void setLockPatternEnabled(boolean enabled) {
240        setBoolean(Settings.System.LOCK_PATTERN_ENABLED, enabled);
241    }
242
243    /**
244     * @return Whether the visible pattern is enabled.
245     */
246    public boolean isVisiblePatternEnabled() {
247        return getBoolean(Settings.System.LOCK_PATTERN_VISIBLE);
248    }
249
250    /**
251     * Set whether the visible pattern is enabled.
252     */
253    public void setVisiblePatternEnabled(boolean enabled) {
254        setBoolean(Settings.System.LOCK_PATTERN_VISIBLE, enabled);
255    }
256
257    /**
258     * @return Whether tactile feedback for the pattern is enabled.
259     */
260    public boolean isTactileFeedbackEnabled() {
261        return getBoolean(Settings.System.LOCK_PATTERN_TACTILE_FEEDBACK_ENABLED);
262    }
263
264    /**
265     * Set whether tactile feedback for the pattern is enabled.
266     */
267    public void setTactileFeedbackEnabled(boolean enabled) {
268        setBoolean(Settings.System.LOCK_PATTERN_TACTILE_FEEDBACK_ENABLED, enabled);
269    }
270
271    /**
272     * Set and store the lockout deadline, meaning the user can't attempt his/her unlock
273     * pattern until the deadline has passed.
274     * @return the chosen deadline.
275     */
276    public long setLockoutAttemptDeadline() {
277        final long deadline = SystemClock.elapsedRealtime() + FAILED_ATTEMPT_TIMEOUT_MS;
278        setLong(LOCKOUT_ATTEMPT_DEADLINE, deadline);
279        return deadline;
280    }
281
282    /**
283     * @return The elapsed time in millis in the future when the user is allowed to
284     *   attempt to enter his/her lock pattern, or 0 if the user is welcome to
285     *   enter a pattern.
286     */
287    public long getLockoutAttemptDeadline() {
288        final long deadline = getLong(LOCKOUT_ATTEMPT_DEADLINE, 0L);
289        final long now = SystemClock.elapsedRealtime();
290        if (deadline < now || deadline > (now + FAILED_ATTEMPT_TIMEOUT_MS)) {
291            return 0L;
292        }
293        return deadline;
294    }
295
296    /**
297     * @return Whether the user is permanently locked out until they verify their
298     *   credentials.  Occurs after {@link #FAILED_ATTEMPTS_BEFORE_RESET} failed
299     *   attempts.
300     */
301    public boolean isPermanentlyLocked() {
302        return getBoolean(LOCKOUT_PERMANENT_KEY);
303    }
304
305    /**
306     * Set the state of whether the device is permanently locked, meaning the user
307     * must authenticate via other means.  If false, that means the user has gone
308     * out of permanent lock, so the existing (forgotten) lock pattern needs to
309     * be cleared.
310     * @param locked Whether the user is permanently locked out until they verify their
311     *   credentials.  Occurs after {@link #FAILED_ATTEMPTS_BEFORE_RESET} failed
312     *   attempts.
313     */
314    public void setPermanentlyLocked(boolean locked) {
315        setBoolean(LOCKOUT_PERMANENT_KEY, locked);
316
317        if (!locked) {
318            setLockPatternEnabled(false);
319            saveLockPattern(null);
320        }
321    }
322
323    /**
324     * @return A formatted string of the next alarm (for showing on the lock screen),
325     *   or null if there is no next alarm.
326     */
327    public String getNextAlarm() {
328        String nextAlarm = Settings.System.getString(mContentResolver,
329                Settings.System.NEXT_ALARM_FORMATTED);
330        if (nextAlarm == null || TextUtils.isEmpty(nextAlarm)) {
331            return null;
332        }
333        return nextAlarm;
334    }
335
336    private boolean getBoolean(String systemSettingKey) {
337        return 1 ==
338                android.provider.Settings.System.getInt(
339                        mContentResolver,
340                        systemSettingKey, 0);
341    }
342
343    private void setBoolean(String systemSettingKey, boolean enabled) {
344        android.provider.Settings.System.putInt(
345                        mContentResolver,
346                        systemSettingKey,
347                        enabled ? 1 : 0);
348    }
349
350    private long getLong(String systemSettingKey, long def) {
351        return android.provider.Settings.System.getLong(mContentResolver, systemSettingKey, def);
352    }
353
354    private void setLong(String systemSettingKey, long value) {
355        android.provider.Settings.System.putLong(mContentResolver, systemSettingKey, value);
356    }
357
358
359}
360