blob: e28a258b2db6fda7781596aa42bb2204f1ceaad4 [file] [log] [blame]
Amith Yamasani52c489c2012-03-28 11:42:42 -07001/*
2 * Copyright (C) 2012 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
Jeff Sharkey7a96c392012-11-15 14:01:46 -080017package com.android.server;
Amith Yamasani52c489c2012-03-28 11:42:42 -070018
19import android.content.ContentResolver;
20import android.content.ContentValues;
21import android.content.Context;
Jim Miller158fe192013-04-17 15:23:55 -070022import android.content.pm.PackageManager;
Jim Miller187ec582013-04-15 18:27:54 -070023import android.content.pm.UserInfo;
24
25import static android.content.Context.USER_SERVICE;
Jim Miller158fe192013-04-17 15:23:55 -070026import static android.Manifest.permission.READ_PROFILE;
Amith Yamasani52c489c2012-03-28 11:42:42 -070027import android.database.Cursor;
28import android.database.sqlite.SQLiteDatabase;
29import android.database.sqlite.SQLiteOpenHelper;
30import android.os.Binder;
Amith Yamasani61f57372012-08-31 12:12:28 -070031import android.os.Environment;
Amith Yamasani52c489c2012-03-28 11:42:42 -070032import android.os.RemoteException;
Amith Yamasanid1645f82012-06-12 11:53:26 -070033import android.os.SystemProperties;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070034import android.os.UserHandle;
Jim Miller187ec582013-04-15 18:27:54 -070035import android.os.UserManager;
Amith Yamasani52c489c2012-03-28 11:42:42 -070036import android.provider.Settings;
37import android.provider.Settings.Secure;
Jim Miller187ec582013-04-15 18:27:54 -070038import android.provider.Settings.SettingNotFoundException;
Amith Yamasani52c489c2012-03-28 11:42:42 -070039import android.text.TextUtils;
40import android.util.Slog;
41
Jeff Sharkey7a96c392012-11-15 14:01:46 -080042import com.android.internal.widget.ILockSettings;
43import com.android.internal.widget.LockPatternUtils;
44
Amith Yamasani52c489c2012-03-28 11:42:42 -070045import java.io.File;
46import java.io.FileNotFoundException;
47import java.io.IOException;
48import java.io.RandomAccessFile;
49import java.util.Arrays;
Jim Miller187ec582013-04-15 18:27:54 -070050import java.util.List;
Amith Yamasani52c489c2012-03-28 11:42:42 -070051
52/**
53 * Keeps the lock pattern/password data and related settings for each user.
54 * Used by LockPatternUtils. Needs to be a service because Settings app also needs
55 * to be able to save lockscreen information for secondary users.
56 * @hide
57 */
58public class LockSettingsService extends ILockSettings.Stub {
59
Jim Miller5ecd8112013-01-09 18:50:26 -080060 private static final String PERMISSION = "android.permission.ACCESS_KEYGUARD_SECURE_STORAGE";
Amith Yamasani52c489c2012-03-28 11:42:42 -070061 private final DatabaseHelper mOpenHelper;
62 private static final String TAG = "LockSettingsService";
63
64 private static final String TABLE = "locksettings";
65 private static final String COLUMN_KEY = "name";
66 private static final String COLUMN_USERID = "user";
67 private static final String COLUMN_VALUE = "value";
68
69 private static final String[] COLUMNS_FOR_QUERY = {
70 COLUMN_VALUE
71 };
72
73 private static final String SYSTEM_DIRECTORY = "/system/";
74 private static final String LOCK_PATTERN_FILE = "gesture.key";
75 private static final String LOCK_PASSWORD_FILE = "password.key";
76
77 private final Context mContext;
78
79 public LockSettingsService(Context context) {
80 mContext = context;
81 // Open the database
82 mOpenHelper = new DatabaseHelper(mContext);
83 }
84
85 public void systemReady() {
86 migrateOldData();
87 }
88
89 private void migrateOldData() {
90 try {
Jim Miller187ec582013-04-15 18:27:54 -070091 // These Settings moved before multi-user was enabled, so we only have to do it for the
92 // root user.
93 if (getString("migrated", null, 0) == null) {
94 final ContentResolver cr = mContext.getContentResolver();
95 for (String validSetting : VALID_SETTINGS) {
96 String value = Settings.Secure.getString(cr, validSetting);
97 if (value != null) {
98 setString(validSetting, value, 0);
99 }
100 }
101 // No need to move the password / pattern files. They're already in the right place.
102 setString("migrated", "true", 0);
103 Slog.i(TAG, "Migrated lock settings to new location");
Amith Yamasani52c489c2012-03-28 11:42:42 -0700104 }
105
Jim Miller187ec582013-04-15 18:27:54 -0700106 // These Settings changed after multi-user was enabled, hence need to be moved per user.
107 if (getString("migrated_user_specific", null, 0) == null) {
108 final UserManager um = (UserManager) mContext.getSystemService(USER_SERVICE);
109 final ContentResolver cr = mContext.getContentResolver();
110 List<UserInfo> users = um.getUsers();
111 for (int user = 0; user < users.size(); user++) {
Jim Miller2d8ecf9d2013-04-22 17:17:03 -0700112 // Migrate owner info
113 final int userId = users.get(user).id;
114 final String OWNER_INFO = Secure.LOCK_SCREEN_OWNER_INFO;
115 String ownerInfo = Settings.Secure.getStringForUser(cr, OWNER_INFO, userId);
116 if (ownerInfo != null) {
117 setString(OWNER_INFO, ownerInfo, userId);
118 Settings.Secure.putStringForUser(cr, ownerInfo, "", userId);
119 }
Jim Miller187ec582013-04-15 18:27:54 -0700120
Jim Miller2d8ecf9d2013-04-22 17:17:03 -0700121 // Migrate owner info enabled. Note there was a bug where older platforms only
122 // stored this value if the checkbox was toggled at least once. The code detects
123 // this case by handling the exception.
124 final String OWNER_INFO_ENABLED = Secure.LOCK_SCREEN_OWNER_INFO_ENABLED;
125 boolean enabled;
126 try {
127 int ivalue = Settings.Secure.getIntForUser(cr, OWNER_INFO_ENABLED, userId);
128 enabled = ivalue != 0;
129 setLong(OWNER_INFO_ENABLED, enabled ? 1 : 0, userId);
130 } catch (SettingNotFoundException e) {
131 // Setting was never stored. Store it if the string is not empty.
132 if (!TextUtils.isEmpty(ownerInfo)) {
133 setLong(OWNER_INFO_ENABLED, 1, userId);
Jim Miller187ec582013-04-15 18:27:54 -0700134 }
135 }
Jim Miller2d8ecf9d2013-04-22 17:17:03 -0700136 Settings.Secure.putIntForUser(cr, OWNER_INFO_ENABLED, 0, userId);
Amith Yamasani52c489c2012-03-28 11:42:42 -0700137 }
Jim Miller187ec582013-04-15 18:27:54 -0700138 // No need to move the password / pattern files. They're already in the right place.
139 setString("migrated_user_specific", "true", 0);
140 Slog.i(TAG, "Migrated per-user lock settings to new location");
Amith Yamasani52c489c2012-03-28 11:42:42 -0700141 }
Amith Yamasani52c489c2012-03-28 11:42:42 -0700142 } catch (RemoteException re) {
Jim Miller187ec582013-04-15 18:27:54 -0700143 Slog.e(TAG, "Unable to migrate old data", re);
Amith Yamasani52c489c2012-03-28 11:42:42 -0700144 }
145 }
146
Jim Miller5ecd8112013-01-09 18:50:26 -0800147 private final void checkWritePermission(int userId) {
148 mContext.checkCallingOrSelfPermission(PERMISSION);
Amith Yamasani52c489c2012-03-28 11:42:42 -0700149 }
150
Jim Miller5ecd8112013-01-09 18:50:26 -0800151 private final void checkPasswordReadPermission(int userId) {
152 mContext.checkCallingOrSelfPermission(PERMISSION);
Amith Yamasani52c489c2012-03-28 11:42:42 -0700153 }
154
Jim Miller158fe192013-04-17 15:23:55 -0700155 private final void checkReadPermission(String requestedKey, int userId) {
Amith Yamasani52c489c2012-03-28 11:42:42 -0700156 final int callingUid = Binder.getCallingUid();
Jim Miller158fe192013-04-17 15:23:55 -0700157 for (int i = 0; i < READ_PROFILE_PROTECTED_SETTINGS.length; i++) {
158 String key = READ_PROFILE_PROTECTED_SETTINGS[i];
159 if (key.equals(requestedKey) && mContext.checkCallingOrSelfPermission(READ_PROFILE)
160 != PackageManager.PERMISSION_GRANTED) {
161 throw new SecurityException("uid=" + callingUid
162 + " needs permission " + READ_PROFILE + " to read "
163 + requestedKey + " for user " + userId);
164 }
Amith Yamasani52c489c2012-03-28 11:42:42 -0700165 }
166 }
167
168 @Override
169 public void setBoolean(String key, boolean value, int userId) throws RemoteException {
170 checkWritePermission(userId);
171
172 writeToDb(key, value ? "1" : "0", userId);
173 }
174
175 @Override
176 public void setLong(String key, long value, int userId) throws RemoteException {
177 checkWritePermission(userId);
178
179 writeToDb(key, Long.toString(value), userId);
180 }
181
182 @Override
183 public void setString(String key, String value, int userId) throws RemoteException {
184 checkWritePermission(userId);
185
186 writeToDb(key, value, userId);
187 }
188
189 @Override
190 public boolean getBoolean(String key, boolean defaultValue, int userId) throws RemoteException {
Jim Miller158fe192013-04-17 15:23:55 -0700191 checkReadPermission(key, userId);
Amith Yamasani52c489c2012-03-28 11:42:42 -0700192
193 String value = readFromDb(key, null, userId);
194 return TextUtils.isEmpty(value) ?
195 defaultValue : (value.equals("1") || value.equals("true"));
196 }
197
198 @Override
199 public long getLong(String key, long defaultValue, int userId) throws RemoteException {
Jim Miller158fe192013-04-17 15:23:55 -0700200 checkReadPermission(key, userId);
Amith Yamasani52c489c2012-03-28 11:42:42 -0700201
202 String value = readFromDb(key, null, userId);
203 return TextUtils.isEmpty(value) ? defaultValue : Long.parseLong(value);
204 }
205
206 @Override
207 public String getString(String key, String defaultValue, int userId) throws RemoteException {
Jim Miller158fe192013-04-17 15:23:55 -0700208 checkReadPermission(key, userId);
Amith Yamasani52c489c2012-03-28 11:42:42 -0700209
210 return readFromDb(key, defaultValue, userId);
211 }
212
213 private String getLockPatternFilename(int userId) {
214 String dataSystemDirectory =
215 android.os.Environment.getDataDirectory().getAbsolutePath() +
216 SYSTEM_DIRECTORY;
217 if (userId == 0) {
218 // Leave it in the same place for user 0
219 return dataSystemDirectory + LOCK_PATTERN_FILE;
220 } else {
Amith Yamasani61f57372012-08-31 12:12:28 -0700221 return new File(Environment.getUserSystemDirectory(userId), LOCK_PATTERN_FILE)
222 .getAbsolutePath();
Amith Yamasani52c489c2012-03-28 11:42:42 -0700223 }
224 }
225
226 private String getLockPasswordFilename(int userId) {
227 String dataSystemDirectory =
228 android.os.Environment.getDataDirectory().getAbsolutePath() +
229 SYSTEM_DIRECTORY;
230 if (userId == 0) {
231 // Leave it in the same place for user 0
232 return dataSystemDirectory + LOCK_PASSWORD_FILE;
233 } else {
Amith Yamasani61f57372012-08-31 12:12:28 -0700234 return new File(Environment.getUserSystemDirectory(userId), LOCK_PASSWORD_FILE)
235 .getAbsolutePath();
Amith Yamasani52c489c2012-03-28 11:42:42 -0700236 }
237 }
238
239 @Override
240 public boolean havePassword(int userId) throws RemoteException {
241 // Do we need a permissions check here?
242
243 return new File(getLockPasswordFilename(userId)).length() > 0;
244 }
245
246 @Override
247 public boolean havePattern(int userId) throws RemoteException {
248 // Do we need a permissions check here?
249
250 return new File(getLockPatternFilename(userId)).length() > 0;
251 }
252
253 @Override
254 public void setLockPattern(byte[] hash, int userId) throws RemoteException {
255 checkWritePermission(userId);
256
257 writeFile(getLockPatternFilename(userId), hash);
258 }
259
260 @Override
261 public boolean checkPattern(byte[] hash, int userId) throws RemoteException {
262 checkPasswordReadPermission(userId);
263 try {
264 // Read all the bytes from the file
265 RandomAccessFile raf = new RandomAccessFile(getLockPatternFilename(userId), "r");
266 final byte[] stored = new byte[(int) raf.length()];
267 int got = raf.read(stored, 0, stored.length);
268 raf.close();
269 if (got <= 0) {
270 return true;
271 }
272 // Compare the hash from the file with the entered pattern's hash
273 return Arrays.equals(stored, hash);
274 } catch (FileNotFoundException fnfe) {
275 Slog.e(TAG, "Cannot read file " + fnfe);
276 return true;
277 } catch (IOException ioe) {
278 Slog.e(TAG, "Cannot read file " + ioe);
279 return true;
280 }
281 }
282
283 @Override
284 public void setLockPassword(byte[] hash, int userId) throws RemoteException {
285 checkWritePermission(userId);
286
287 writeFile(getLockPasswordFilename(userId), hash);
288 }
289
290 @Override
291 public boolean checkPassword(byte[] hash, int userId) throws RemoteException {
292 checkPasswordReadPermission(userId);
293
294 try {
295 // Read all the bytes from the file
296 RandomAccessFile raf = new RandomAccessFile(getLockPasswordFilename(userId), "r");
297 final byte[] stored = new byte[(int) raf.length()];
298 int got = raf.read(stored, 0, stored.length);
299 raf.close();
300 if (got <= 0) {
301 return true;
302 }
303 // Compare the hash from the file with the entered password's hash
304 return Arrays.equals(stored, hash);
305 } catch (FileNotFoundException fnfe) {
306 Slog.e(TAG, "Cannot read file " + fnfe);
307 return true;
308 } catch (IOException ioe) {
309 Slog.e(TAG, "Cannot read file " + ioe);
310 return true;
311 }
312 }
313
314 @Override
315 public void removeUser(int userId) {
316 checkWritePermission(userId);
317
318 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
319 try {
320 File file = new File(getLockPasswordFilename(userId));
321 if (file.exists()) {
322 file.delete();
323 }
324 file = new File(getLockPatternFilename(userId));
325 if (file.exists()) {
326 file.delete();
327 }
328
329 db.beginTransaction();
330 db.delete(TABLE, COLUMN_USERID + "='" + userId + "'", null);
331 db.setTransactionSuccessful();
332 } finally {
333 db.endTransaction();
334 }
335 }
336
337 private void writeFile(String name, byte[] hash) {
338 try {
339 // Write the hash to file
340 RandomAccessFile raf = new RandomAccessFile(name, "rw");
341 // Truncate the file if pattern is null, to clear the lock
342 if (hash == null || hash.length == 0) {
343 raf.setLength(0);
344 } else {
345 raf.write(hash, 0, hash.length);
346 }
347 raf.close();
348 } catch (IOException ioe) {
349 Slog.e(TAG, "Error writing to file " + ioe);
350 }
351 }
352
353 private void writeToDb(String key, String value, int userId) {
Amith Yamasanid1645f82012-06-12 11:53:26 -0700354 writeToDb(mOpenHelper.getWritableDatabase(), key, value, userId);
355 }
356
357 private void writeToDb(SQLiteDatabase db, String key, String value, int userId) {
Amith Yamasani52c489c2012-03-28 11:42:42 -0700358 ContentValues cv = new ContentValues();
359 cv.put(COLUMN_KEY, key);
360 cv.put(COLUMN_USERID, userId);
361 cv.put(COLUMN_VALUE, value);
362
Amith Yamasani52c489c2012-03-28 11:42:42 -0700363 db.beginTransaction();
364 try {
365 db.delete(TABLE, COLUMN_KEY + "=? AND " + COLUMN_USERID + "=?",
366 new String[] {key, Integer.toString(userId)});
367 db.insert(TABLE, null, cv);
368 db.setTransactionSuccessful();
369 } finally {
370 db.endTransaction();
371 }
372 }
373
374 private String readFromDb(String key, String defaultValue, int userId) {
375 Cursor cursor;
376 String result = defaultValue;
377 SQLiteDatabase db = mOpenHelper.getReadableDatabase();
378 if ((cursor = db.query(TABLE, COLUMNS_FOR_QUERY,
379 COLUMN_USERID + "=? AND " + COLUMN_KEY + "=?",
380 new String[] { Integer.toString(userId), key },
381 null, null, null)) != null) {
382 if (cursor.moveToFirst()) {
383 result = cursor.getString(0);
384 }
385 cursor.close();
386 }
387 return result;
388 }
389
390 class DatabaseHelper extends SQLiteOpenHelper {
391 private static final String TAG = "LockSettingsDB";
392 private static final String DATABASE_NAME = "locksettings.db";
393
394 private static final int DATABASE_VERSION = 1;
395
396 public DatabaseHelper(Context context) {
397 super(context, DATABASE_NAME, null, DATABASE_VERSION);
398 setWriteAheadLoggingEnabled(true);
399 }
400
401 private void createTable(SQLiteDatabase db) {
402 db.execSQL("CREATE TABLE " + TABLE + " (" +
403 "_id INTEGER PRIMARY KEY AUTOINCREMENT," +
404 COLUMN_KEY + " TEXT," +
405 COLUMN_USERID + " INTEGER," +
406 COLUMN_VALUE + " TEXT" +
407 ");");
408 }
409
410 @Override
411 public void onCreate(SQLiteDatabase db) {
412 createTable(db);
Amith Yamasanid1645f82012-06-12 11:53:26 -0700413 initializeDefaults(db);
414 }
415
416 private void initializeDefaults(SQLiteDatabase db) {
417 // Get the lockscreen default from a system property, if available
418 boolean lockScreenDisable = SystemProperties.getBoolean("ro.lockscreen.disable.default",
419 false);
420 if (lockScreenDisable) {
421 writeToDb(db, LockPatternUtils.DISABLE_LOCKSCREEN_KEY, "1", 0);
422 }
Amith Yamasani52c489c2012-03-28 11:42:42 -0700423 }
424
425 @Override
426 public void onUpgrade(SQLiteDatabase db, int oldVersion, int currentVersion) {
427 // Nothing yet
428 }
429 }
430
431 private static final String[] VALID_SETTINGS = new String[] {
432 LockPatternUtils.LOCKOUT_PERMANENT_KEY,
433 LockPatternUtils.LOCKOUT_ATTEMPT_DEADLINE,
434 LockPatternUtils.PATTERN_EVER_CHOSEN_KEY,
435 LockPatternUtils.PASSWORD_TYPE_KEY,
436 LockPatternUtils.PASSWORD_TYPE_ALTERNATE_KEY,
437 LockPatternUtils.LOCK_PASSWORD_SALT_KEY,
438 LockPatternUtils.DISABLE_LOCKSCREEN_KEY,
439 LockPatternUtils.LOCKSCREEN_OPTIONS,
440 LockPatternUtils.LOCKSCREEN_BIOMETRIC_WEAK_FALLBACK,
441 LockPatternUtils.BIOMETRIC_WEAK_EVER_CHOSEN_KEY,
442 LockPatternUtils.LOCKSCREEN_POWER_BUTTON_INSTANTLY_LOCKS,
443 LockPatternUtils.PASSWORD_HISTORY_KEY,
444 Secure.LOCK_PATTERN_ENABLED,
445 Secure.LOCK_BIOMETRIC_WEAK_FLAGS,
446 Secure.LOCK_PATTERN_VISIBLE,
447 Secure.LOCK_PATTERN_TACTILE_FEEDBACK_ENABLED
Jim Miller187ec582013-04-15 18:27:54 -0700448 };
449
Jim Miller2d8ecf9d2013-04-22 17:17:03 -0700450 // These are protected with a read permission
451 private static final String[] READ_PROFILE_PROTECTED_SETTINGS = new String[] {
Jim Miller187ec582013-04-15 18:27:54 -0700452 Secure.LOCK_SCREEN_OWNER_INFO_ENABLED,
453 Secure.LOCK_SCREEN_OWNER_INFO
454 };
Amith Yamasani52c489c2012-03-28 11:42:42 -0700455}