blob: 8e45415d6b8095ed64271852b5165cf773e690eb [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 Miller187ec582013-04-15 18:27:54 -070022import android.content.pm.UserInfo;
23
24import static android.content.Context.USER_SERVICE;
Amith Yamasani52c489c2012-03-28 11:42:42 -070025import android.database.Cursor;
26import android.database.sqlite.SQLiteDatabase;
27import android.database.sqlite.SQLiteOpenHelper;
28import android.os.Binder;
Amith Yamasani61f57372012-08-31 12:12:28 -070029import android.os.Environment;
Amith Yamasani52c489c2012-03-28 11:42:42 -070030import android.os.RemoteException;
Amith Yamasanid1645f82012-06-12 11:53:26 -070031import android.os.SystemProperties;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070032import android.os.UserHandle;
Jim Miller187ec582013-04-15 18:27:54 -070033import android.os.UserManager;
Amith Yamasani52c489c2012-03-28 11:42:42 -070034import android.provider.Settings;
35import android.provider.Settings.Secure;
Jim Miller187ec582013-04-15 18:27:54 -070036import android.provider.Settings.SettingNotFoundException;
Amith Yamasani52c489c2012-03-28 11:42:42 -070037import android.text.TextUtils;
38import android.util.Slog;
39
Jeff Sharkey7a96c392012-11-15 14:01:46 -080040import com.android.internal.widget.ILockSettings;
41import com.android.internal.widget.LockPatternUtils;
42
Amith Yamasani52c489c2012-03-28 11:42:42 -070043import java.io.File;
44import java.io.FileNotFoundException;
45import java.io.IOException;
46import java.io.RandomAccessFile;
47import java.util.Arrays;
Jim Miller187ec582013-04-15 18:27:54 -070048import java.util.List;
Amith Yamasani52c489c2012-03-28 11:42:42 -070049
50/**
51 * Keeps the lock pattern/password data and related settings for each user.
52 * Used by LockPatternUtils. Needs to be a service because Settings app also needs
53 * to be able to save lockscreen information for secondary users.
54 * @hide
55 */
56public class LockSettingsService extends ILockSettings.Stub {
57
58 private final DatabaseHelper mOpenHelper;
59 private static final String TAG = "LockSettingsService";
60
61 private static final String TABLE = "locksettings";
62 private static final String COLUMN_KEY = "name";
63 private static final String COLUMN_USERID = "user";
64 private static final String COLUMN_VALUE = "value";
65
66 private static final String[] COLUMNS_FOR_QUERY = {
67 COLUMN_VALUE
68 };
69
70 private static final String SYSTEM_DIRECTORY = "/system/";
71 private static final String LOCK_PATTERN_FILE = "gesture.key";
72 private static final String LOCK_PASSWORD_FILE = "password.key";
73
74 private final Context mContext;
75
76 public LockSettingsService(Context context) {
77 mContext = context;
78 // Open the database
79 mOpenHelper = new DatabaseHelper(mContext);
80 }
81
82 public void systemReady() {
83 migrateOldData();
84 }
85
86 private void migrateOldData() {
87 try {
Jim Miller187ec582013-04-15 18:27:54 -070088 // These Settings moved before multi-user was enabled, so we only have to do it for the
89 // root user.
90 if (getString("migrated", null, 0) == null) {
91 final ContentResolver cr = mContext.getContentResolver();
92 for (String validSetting : VALID_SETTINGS) {
93 String value = Settings.Secure.getString(cr, validSetting);
94 if (value != null) {
95 setString(validSetting, value, 0);
96 }
97 }
98 // No need to move the password / pattern files. They're already in the right place.
99 setString("migrated", "true", 0);
100 Slog.i(TAG, "Migrated lock settings to new location");
Amith Yamasani52c489c2012-03-28 11:42:42 -0700101 }
102
Jim Miller187ec582013-04-15 18:27:54 -0700103 // These Settings changed after multi-user was enabled, hence need to be moved per user.
104 if (getString("migrated_user_specific", null, 0) == null) {
105 final UserManager um = (UserManager) mContext.getSystemService(USER_SERVICE);
106 final ContentResolver cr = mContext.getContentResolver();
107 List<UserInfo> users = um.getUsers();
108 for (int user = 0; user < users.size(); user++) {
109 int userId = users.get(user).getUserHandle().getIdentifier();
110 for (String perUserSetting : MIGRATE_SETTINGS_PER_USER) {
111 // Handle Strings
112 String value = Settings.Secure.getStringForUser(cr, perUserSetting, userId);
113 if (value != null) {
114 setString(perUserSetting, value, userId);
115 Settings.Secure.putStringForUser(cr, perUserSetting, "", userId);
116 continue;
117 }
118
119 // Handle integers
120 try {
121 int ivalue = Settings.Secure.getIntForUser(cr, perUserSetting, userId);
122 setLong(perUserSetting, ivalue, userId);
123 Settings.Secure.putIntForUser(cr, perUserSetting, 0, userId);
124 } catch (SettingNotFoundException e) {
125 }
126 }
Amith Yamasani52c489c2012-03-28 11:42:42 -0700127 }
Jim Miller187ec582013-04-15 18:27:54 -0700128 // No need to move the password / pattern files. They're already in the right place.
129 setString("migrated_user_specific", "true", 0);
130 Slog.i(TAG, "Migrated per-user lock settings to new location");
Amith Yamasani52c489c2012-03-28 11:42:42 -0700131 }
Amith Yamasani52c489c2012-03-28 11:42:42 -0700132 } catch (RemoteException re) {
Jim Miller187ec582013-04-15 18:27:54 -0700133 Slog.e(TAG, "Unable to migrate old data", re);
Amith Yamasani52c489c2012-03-28 11:42:42 -0700134 }
135 }
136
137 private static final void checkWritePermission(int userId) {
138 final int callingUid = Binder.getCallingUid();
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700139 if (UserHandle.getAppId(callingUid) != android.os.Process.SYSTEM_UID) {
Amith Yamasani52c489c2012-03-28 11:42:42 -0700140 throw new SecurityException("uid=" + callingUid
141 + " not authorized to write lock settings");
142 }
143 }
144
145 private static final void checkPasswordReadPermission(int userId) {
146 final int callingUid = Binder.getCallingUid();
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700147 if (UserHandle.getAppId(callingUid) != android.os.Process.SYSTEM_UID) {
Amith Yamasani52c489c2012-03-28 11:42:42 -0700148 throw new SecurityException("uid=" + callingUid
149 + " not authorized to read lock password");
150 }
151 }
152
153 private static final void checkReadPermission(int userId) {
154 final int callingUid = Binder.getCallingUid();
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700155 if (UserHandle.getAppId(callingUid) != android.os.Process.SYSTEM_UID
156 && UserHandle.getUserId(callingUid) != userId) {
Amith Yamasani52c489c2012-03-28 11:42:42 -0700157 throw new SecurityException("uid=" + callingUid
158 + " not authorized to read settings of user " + userId);
159 }
160 }
161
162 @Override
163 public void setBoolean(String key, boolean value, int userId) throws RemoteException {
164 checkWritePermission(userId);
165
166 writeToDb(key, value ? "1" : "0", userId);
167 }
168
169 @Override
170 public void setLong(String key, long value, int userId) throws RemoteException {
171 checkWritePermission(userId);
172
173 writeToDb(key, Long.toString(value), userId);
174 }
175
176 @Override
177 public void setString(String key, String value, int userId) throws RemoteException {
178 checkWritePermission(userId);
179
180 writeToDb(key, value, userId);
181 }
182
183 @Override
184 public boolean getBoolean(String key, boolean defaultValue, int userId) throws RemoteException {
185 //checkReadPermission(userId);
186
187 String value = readFromDb(key, null, userId);
188 return TextUtils.isEmpty(value) ?
189 defaultValue : (value.equals("1") || value.equals("true"));
190 }
191
192 @Override
193 public long getLong(String key, long defaultValue, int userId) throws RemoteException {
194 //checkReadPermission(userId);
195
196 String value = readFromDb(key, null, userId);
197 return TextUtils.isEmpty(value) ? defaultValue : Long.parseLong(value);
198 }
199
200 @Override
201 public String getString(String key, String defaultValue, int userId) throws RemoteException {
202 //checkReadPermission(userId);
203
204 return readFromDb(key, defaultValue, userId);
205 }
206
207 private String getLockPatternFilename(int userId) {
208 String dataSystemDirectory =
209 android.os.Environment.getDataDirectory().getAbsolutePath() +
210 SYSTEM_DIRECTORY;
211 if (userId == 0) {
212 // Leave it in the same place for user 0
213 return dataSystemDirectory + LOCK_PATTERN_FILE;
214 } else {
Amith Yamasani61f57372012-08-31 12:12:28 -0700215 return new File(Environment.getUserSystemDirectory(userId), LOCK_PATTERN_FILE)
216 .getAbsolutePath();
Amith Yamasani52c489c2012-03-28 11:42:42 -0700217 }
218 }
219
220 private String getLockPasswordFilename(int userId) {
221 String dataSystemDirectory =
222 android.os.Environment.getDataDirectory().getAbsolutePath() +
223 SYSTEM_DIRECTORY;
224 if (userId == 0) {
225 // Leave it in the same place for user 0
226 return dataSystemDirectory + LOCK_PASSWORD_FILE;
227 } else {
Amith Yamasani61f57372012-08-31 12:12:28 -0700228 return new File(Environment.getUserSystemDirectory(userId), LOCK_PASSWORD_FILE)
229 .getAbsolutePath();
Amith Yamasani52c489c2012-03-28 11:42:42 -0700230 }
231 }
232
233 @Override
234 public boolean havePassword(int userId) throws RemoteException {
235 // Do we need a permissions check here?
236
237 return new File(getLockPasswordFilename(userId)).length() > 0;
238 }
239
240 @Override
241 public boolean havePattern(int userId) throws RemoteException {
242 // Do we need a permissions check here?
243
244 return new File(getLockPatternFilename(userId)).length() > 0;
245 }
246
247 @Override
248 public void setLockPattern(byte[] hash, int userId) throws RemoteException {
249 checkWritePermission(userId);
250
251 writeFile(getLockPatternFilename(userId), hash);
252 }
253
254 @Override
255 public boolean checkPattern(byte[] hash, int userId) throws RemoteException {
256 checkPasswordReadPermission(userId);
257 try {
258 // Read all the bytes from the file
259 RandomAccessFile raf = new RandomAccessFile(getLockPatternFilename(userId), "r");
260 final byte[] stored = new byte[(int) raf.length()];
261 int got = raf.read(stored, 0, stored.length);
262 raf.close();
263 if (got <= 0) {
264 return true;
265 }
266 // Compare the hash from the file with the entered pattern's hash
267 return Arrays.equals(stored, hash);
268 } catch (FileNotFoundException fnfe) {
269 Slog.e(TAG, "Cannot read file " + fnfe);
270 return true;
271 } catch (IOException ioe) {
272 Slog.e(TAG, "Cannot read file " + ioe);
273 return true;
274 }
275 }
276
277 @Override
278 public void setLockPassword(byte[] hash, int userId) throws RemoteException {
279 checkWritePermission(userId);
280
281 writeFile(getLockPasswordFilename(userId), hash);
282 }
283
284 @Override
285 public boolean checkPassword(byte[] hash, int userId) throws RemoteException {
286 checkPasswordReadPermission(userId);
287
288 try {
289 // Read all the bytes from the file
290 RandomAccessFile raf = new RandomAccessFile(getLockPasswordFilename(userId), "r");
291 final byte[] stored = new byte[(int) raf.length()];
292 int got = raf.read(stored, 0, stored.length);
293 raf.close();
294 if (got <= 0) {
295 return true;
296 }
297 // Compare the hash from the file with the entered password's hash
298 return Arrays.equals(stored, hash);
299 } catch (FileNotFoundException fnfe) {
300 Slog.e(TAG, "Cannot read file " + fnfe);
301 return true;
302 } catch (IOException ioe) {
303 Slog.e(TAG, "Cannot read file " + ioe);
304 return true;
305 }
306 }
307
308 @Override
309 public void removeUser(int userId) {
310 checkWritePermission(userId);
311
312 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
313 try {
314 File file = new File(getLockPasswordFilename(userId));
315 if (file.exists()) {
316 file.delete();
317 }
318 file = new File(getLockPatternFilename(userId));
319 if (file.exists()) {
320 file.delete();
321 }
322
323 db.beginTransaction();
324 db.delete(TABLE, COLUMN_USERID + "='" + userId + "'", null);
325 db.setTransactionSuccessful();
326 } finally {
327 db.endTransaction();
328 }
329 }
330
331 private void writeFile(String name, byte[] hash) {
332 try {
333 // Write the hash to file
334 RandomAccessFile raf = new RandomAccessFile(name, "rw");
335 // Truncate the file if pattern is null, to clear the lock
336 if (hash == null || hash.length == 0) {
337 raf.setLength(0);
338 } else {
339 raf.write(hash, 0, hash.length);
340 }
341 raf.close();
342 } catch (IOException ioe) {
343 Slog.e(TAG, "Error writing to file " + ioe);
344 }
345 }
346
347 private void writeToDb(String key, String value, int userId) {
Amith Yamasanid1645f82012-06-12 11:53:26 -0700348 writeToDb(mOpenHelper.getWritableDatabase(), key, value, userId);
349 }
350
351 private void writeToDb(SQLiteDatabase db, String key, String value, int userId) {
Amith Yamasani52c489c2012-03-28 11:42:42 -0700352 ContentValues cv = new ContentValues();
353 cv.put(COLUMN_KEY, key);
354 cv.put(COLUMN_USERID, userId);
355 cv.put(COLUMN_VALUE, value);
356
Amith Yamasani52c489c2012-03-28 11:42:42 -0700357 db.beginTransaction();
358 try {
359 db.delete(TABLE, COLUMN_KEY + "=? AND " + COLUMN_USERID + "=?",
360 new String[] {key, Integer.toString(userId)});
361 db.insert(TABLE, null, cv);
362 db.setTransactionSuccessful();
363 } finally {
364 db.endTransaction();
365 }
366 }
367
368 private String readFromDb(String key, String defaultValue, int userId) {
369 Cursor cursor;
370 String result = defaultValue;
371 SQLiteDatabase db = mOpenHelper.getReadableDatabase();
372 if ((cursor = db.query(TABLE, COLUMNS_FOR_QUERY,
373 COLUMN_USERID + "=? AND " + COLUMN_KEY + "=?",
374 new String[] { Integer.toString(userId), key },
375 null, null, null)) != null) {
376 if (cursor.moveToFirst()) {
377 result = cursor.getString(0);
378 }
379 cursor.close();
380 }
381 return result;
382 }
383
384 class DatabaseHelper extends SQLiteOpenHelper {
385 private static final String TAG = "LockSettingsDB";
386 private static final String DATABASE_NAME = "locksettings.db";
387
388 private static final int DATABASE_VERSION = 1;
389
390 public DatabaseHelper(Context context) {
391 super(context, DATABASE_NAME, null, DATABASE_VERSION);
392 setWriteAheadLoggingEnabled(true);
393 }
394
395 private void createTable(SQLiteDatabase db) {
396 db.execSQL("CREATE TABLE " + TABLE + " (" +
397 "_id INTEGER PRIMARY KEY AUTOINCREMENT," +
398 COLUMN_KEY + " TEXT," +
399 COLUMN_USERID + " INTEGER," +
400 COLUMN_VALUE + " TEXT" +
401 ");");
402 }
403
404 @Override
405 public void onCreate(SQLiteDatabase db) {
406 createTable(db);
Amith Yamasanid1645f82012-06-12 11:53:26 -0700407 initializeDefaults(db);
408 }
409
410 private void initializeDefaults(SQLiteDatabase db) {
411 // Get the lockscreen default from a system property, if available
412 boolean lockScreenDisable = SystemProperties.getBoolean("ro.lockscreen.disable.default",
413 false);
414 if (lockScreenDisable) {
415 writeToDb(db, LockPatternUtils.DISABLE_LOCKSCREEN_KEY, "1", 0);
416 }
Amith Yamasani52c489c2012-03-28 11:42:42 -0700417 }
418
419 @Override
420 public void onUpgrade(SQLiteDatabase db, int oldVersion, int currentVersion) {
421 // Nothing yet
422 }
423 }
424
425 private static final String[] VALID_SETTINGS = new String[] {
426 LockPatternUtils.LOCKOUT_PERMANENT_KEY,
427 LockPatternUtils.LOCKOUT_ATTEMPT_DEADLINE,
428 LockPatternUtils.PATTERN_EVER_CHOSEN_KEY,
429 LockPatternUtils.PASSWORD_TYPE_KEY,
430 LockPatternUtils.PASSWORD_TYPE_ALTERNATE_KEY,
431 LockPatternUtils.LOCK_PASSWORD_SALT_KEY,
432 LockPatternUtils.DISABLE_LOCKSCREEN_KEY,
433 LockPatternUtils.LOCKSCREEN_OPTIONS,
434 LockPatternUtils.LOCKSCREEN_BIOMETRIC_WEAK_FALLBACK,
435 LockPatternUtils.BIOMETRIC_WEAK_EVER_CHOSEN_KEY,
436 LockPatternUtils.LOCKSCREEN_POWER_BUTTON_INSTANTLY_LOCKS,
437 LockPatternUtils.PASSWORD_HISTORY_KEY,
438 Secure.LOCK_PATTERN_ENABLED,
439 Secure.LOCK_BIOMETRIC_WEAK_FLAGS,
440 Secure.LOCK_PATTERN_VISIBLE,
441 Secure.LOCK_PATTERN_TACTILE_FEEDBACK_ENABLED
Jim Miller187ec582013-04-15 18:27:54 -0700442 };
443
444 private static final String[] MIGRATE_SETTINGS_PER_USER = new String[] {
445 Secure.LOCK_SCREEN_OWNER_INFO_ENABLED,
446 Secure.LOCK_SCREEN_OWNER_INFO
447 };
Amith Yamasani52c489c2012-03-28 11:42:42 -0700448}