blob: a2b44e8b82158a83062f3c7aa783488d6aabc0df [file] [log] [blame]
Brian Carlstrom3e6251d2011-04-11 09:05:06 -07001/*
2 * Copyright (C) 2011 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.keychain;
18
Fred Quintanafb2e18e2011-07-13 14:54:05 -070019import android.app.IntentService;
20import android.content.ContentValues;
Brian Carlstrom3e6251d2011-04-11 09:05:06 -070021import android.content.Context;
22import android.content.Intent;
Fred Quintanafb2e18e2011-07-13 14:54:05 -070023import android.content.pm.PackageManager;
24import android.database.Cursor;
25import android.database.DatabaseUtils;
26import android.database.sqlite.SQLiteDatabase;
27import android.database.sqlite.SQLiteOpenHelper;
Kenny Root6f1f03b2012-03-08 10:30:39 -080028import android.os.Binder;
Brian Carlstrom3e6251d2011-04-11 09:05:06 -070029import android.os.IBinder;
Kenny Root6f1f03b2012-03-08 10:30:39 -080030import android.os.Process;
Brian Carlstrom3e6251d2011-04-11 09:05:06 -070031import android.security.Credentials;
32import android.security.IKeyChainService;
Selim Gurun39e36e52012-02-14 10:50:42 -080033import android.security.KeyChain;
Brian Carlstrom3e6251d2011-04-11 09:05:06 -070034import android.security.KeyStore;
35import android.util.Log;
36import java.io.ByteArrayInputStream;
Brian Carlstroma58db542011-05-11 23:02:20 -070037import java.io.IOException;
Brian Carlstrom3e6251d2011-04-11 09:05:06 -070038import java.security.cert.CertificateException;
39import java.security.cert.CertificateFactory;
40import java.security.cert.X509Certificate;
Fred Quintanafb2e18e2011-07-13 14:54:05 -070041
Brian Carlstroma58db542011-05-11 23:02:20 -070042import org.apache.harmony.xnet.provider.jsse.TrustedCertificateStore;
Brian Carlstrom3e6251d2011-04-11 09:05:06 -070043
Fred Quintanafb2e18e2011-07-13 14:54:05 -070044public class KeyChainService extends IntentService {
Selim Gurun39e36e52012-02-14 10:50:42 -080045
Fred Quintanafb2e18e2011-07-13 14:54:05 -070046 private static final String TAG = "KeyChain";
Brian Carlstrom3e6251d2011-04-11 09:05:06 -070047
Fred Quintanafb2e18e2011-07-13 14:54:05 -070048 private static final String DATABASE_NAME = "grants.db";
49 private static final int DATABASE_VERSION = 1;
50 private static final String TABLE_GRANTS = "grants";
51 private static final String GRANTS_ALIAS = "alias";
52 private static final String GRANTS_GRANTEE_UID = "uid";
Brian Carlstrom3e6251d2011-04-11 09:05:06 -070053
Fred Quintanafb2e18e2011-07-13 14:54:05 -070054 /** created in onCreate(), closed in onDestroy() */
55 public DatabaseHelper mDatabaseHelper;
Brian Carlstrom3e6251d2011-04-11 09:05:06 -070056
Fred Quintanafb2e18e2011-07-13 14:54:05 -070057 private static final String SELECTION_COUNT_OF_MATCHING_GRANTS =
58 "SELECT COUNT(*) FROM " + TABLE_GRANTS
59 + " WHERE " + GRANTS_GRANTEE_UID + "=? AND " + GRANTS_ALIAS + "=?";
60
61 private static final String SELECT_GRANTS_BY_UID_AND_ALIAS =
62 GRANTS_GRANTEE_UID + "=? AND " + GRANTS_ALIAS + "=?";
63
64 private static final String SELECTION_GRANTS_BY_UID = GRANTS_GRANTEE_UID + "=?";
65
66 public KeyChainService() {
67 super(KeyChainService.class.getSimpleName());
68 }
Brian Carlstrom3e6251d2011-04-11 09:05:06 -070069
70 @Override public void onCreate() {
71 super.onCreate();
Fred Quintanafb2e18e2011-07-13 14:54:05 -070072 mDatabaseHelper = new DatabaseHelper(this);
73 }
74
75 @Override
76 public void onDestroy() {
77 super.onDestroy();
78 mDatabaseHelper.close();
79 mDatabaseHelper = null;
Brian Carlstrom3e6251d2011-04-11 09:05:06 -070080 }
81
82 private final IKeyChainService.Stub mIKeyChainService = new IKeyChainService.Stub() {
Brian Carlstrom3e6251d2011-04-11 09:05:06 -070083 private final KeyStore mKeyStore = KeyStore.getInstance();
Brian Carlstroma58db542011-05-11 23:02:20 -070084 private final TrustedCertificateStore mTrustedCertificateStore
85 = new TrustedCertificateStore();
Brian Carlstrom3e6251d2011-04-11 09:05:06 -070086
Kenny Root6f1f03b2012-03-08 10:30:39 -080087 @Override
88 public String requestPrivateKey(String alias) {
89 checkArgs(alias);
90
91 final String keystoreAlias = Credentials.USER_PRIVATE_KEY + alias;
92 final int uid = Binder.getCallingUid();
93 if (!mKeyStore.grant(keystoreAlias, uid)) {
94 return null;
95 }
96
97 final StringBuilder sb = new StringBuilder();
98 sb.append(Process.SYSTEM_UID);
99 sb.append('_');
100 sb.append(keystoreAlias);
101
102 return sb.toString();
Brian Carlstrom3e6251d2011-04-11 09:05:06 -0700103 }
104
Fred Quintanafb2e18e2011-07-13 14:54:05 -0700105 @Override public byte[] getCertificate(String alias) {
Kenny Root6f1f03b2012-03-08 10:30:39 -0800106 checkArgs(alias);
107 return mKeyStore.get(Credentials.USER_CERTIFICATE + alias);
Brian Carlstrom3e6251d2011-04-11 09:05:06 -0700108 }
109
Kenny Root6f1f03b2012-03-08 10:30:39 -0800110 private void checkArgs(String alias) {
Brian Carlstrom3e6251d2011-04-11 09:05:06 -0700111 if (alias == null) {
112 throw new NullPointerException("alias == null");
113 }
Kenny Root4ff22962013-02-14 10:17:06 -0800114 if (!mKeyStore.isUnlocked()) {
Nick Kralevichc8b04632012-05-21 15:13:07 -0700115 throw new IllegalStateException("keystore is "
116 + mKeyStore.state().toString());
Brian Carlstrom3e6251d2011-04-11 09:05:06 -0700117 }
Nick Kralevichc8b04632012-05-21 15:13:07 -0700118
Fred Quintanafb2e18e2011-07-13 14:54:05 -0700119 final int callingUid = getCallingUid();
120 if (!hasGrantInternal(mDatabaseHelper.getReadableDatabase(), callingUid, alias)) {
121 throw new IllegalStateException("uid " + callingUid
122 + " doesn't have permission to access the requested alias");
Brian Carlstrom3e6251d2011-04-11 09:05:06 -0700123 }
Brian Carlstrom3e6251d2011-04-11 09:05:06 -0700124 }
125
Brian Carlstroma58db542011-05-11 23:02:20 -0700126 @Override public void installCaCertificate(byte[] caCertificate) {
Brian Carlstrom43f5b772011-06-27 02:27:16 -0700127 checkCertInstallerOrSystemCaller();
Brian Carlstroma58db542011-05-11 23:02:20 -0700128 try {
129 synchronized (mTrustedCertificateStore) {
130 mTrustedCertificateStore.installCertificate(parseCertificate(caCertificate));
131 }
132 } catch (IOException e) {
133 throw new IllegalStateException(e);
134 } catch (CertificateException e) {
135 throw new IllegalStateException(e);
136 }
Selim Gurun39e36e52012-02-14 10:50:42 -0800137 broadcastStorageChange();
Brian Carlstroma58db542011-05-11 23:02:20 -0700138 }
Brian Carlstrom5aeadd92011-05-17 00:40:33 -0700139
140 private X509Certificate parseCertificate(byte[] bytes) throws CertificateException {
141 CertificateFactory cf = CertificateFactory.getInstance("X.509");
142 return (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(bytes));
143 }
144
Brian Carlstroma58db542011-05-11 23:02:20 -0700145 @Override public boolean reset() {
146 // only Settings should be able to reset
Brian Carlstrom43f5b772011-06-27 02:27:16 -0700147 checkSystemCaller();
Fred Quintanafb2e18e2011-07-13 14:54:05 -0700148 removeAllGrants(mDatabaseHelper.getWritableDatabase());
Brian Carlstroma58db542011-05-11 23:02:20 -0700149 boolean ok = true;
Brian Carlstroma58db542011-05-11 23:02:20 -0700150 synchronized (mTrustedCertificateStore) {
151 // delete user-installed CA certs
152 for (String alias : mTrustedCertificateStore.aliases()) {
153 if (TrustedCertificateStore.isUser(alias)) {
Brian Carlstrom43f5b772011-06-27 02:27:16 -0700154 if (!deleteCertificateEntry(alias)) {
Brian Carlstroma58db542011-05-11 23:02:20 -0700155 ok = false;
156 }
157 }
158 }
Brian Carlstroma58db542011-05-11 23:02:20 -0700159 }
Selim Gurun39e36e52012-02-14 10:50:42 -0800160 broadcastStorageChange();
161 return ok;
Brian Carlstroma58db542011-05-11 23:02:20 -0700162 }
Brian Carlstrom43f5b772011-06-27 02:27:16 -0700163
164 @Override public boolean deleteCaCertificate(String alias) {
165 // only Settings should be able to delete
166 checkSystemCaller();
Selim Gurun39e36e52012-02-14 10:50:42 -0800167 boolean ok = true;
168 synchronized (mTrustedCertificateStore) {
169 ok = deleteCertificateEntry(alias);
170 }
171 broadcastStorageChange();
172 return ok;
Brian Carlstrom43f5b772011-06-27 02:27:16 -0700173 }
174
175 private boolean deleteCertificateEntry(String alias) {
176 try {
177 mTrustedCertificateStore.deleteCertificateEntry(alias);
178 return true;
179 } catch (IOException e) {
180 Log.w(TAG, "Problem removing CA certificate " + alias, e);
181 return false;
182 } catch (CertificateException e) {
183 Log.w(TAG, "Problem removing CA certificate " + alias, e);
184 return false;
185 }
186 }
187
188 private void checkCertInstallerOrSystemCaller() {
189 String actual = checkCaller("com.android.certinstaller");
190 if (actual == null) {
191 return;
192 }
193 checkSystemCaller();
194 }
195 private void checkSystemCaller() {
196 String actual = checkCaller("android.uid.system:1000");
197 if (actual != null) {
198 throw new IllegalStateException(actual);
199 }
200 }
201 /**
202 * Returns null if actually caller is expected, otherwise return bad package to report
203 */
204 private String checkCaller(String expectedPackage) {
205 String actualPackage = getPackageManager().getNameForUid(getCallingUid());
206 return (!expectedPackage.equals(actualPackage)) ? actualPackage : null;
207 }
Brian Carlstrom3e6251d2011-04-11 09:05:06 -0700208
Fred Quintanafb2e18e2011-07-13 14:54:05 -0700209 @Override public boolean hasGrant(int uid, String alias) {
210 checkSystemCaller();
211 return hasGrantInternal(mDatabaseHelper.getReadableDatabase(), uid, alias);
Brian Carlstrom3e6251d2011-04-11 09:05:06 -0700212 }
213
Fred Quintanafb2e18e2011-07-13 14:54:05 -0700214 @Override public void setGrant(int uid, String alias, boolean value) {
215 checkSystemCaller();
216 setGrantInternal(mDatabaseHelper.getWritableDatabase(), uid, alias, value);
Selim Gurun39e36e52012-02-14 10:50:42 -0800217 broadcastStorageChange();
Brian Carlstrom3e6251d2011-04-11 09:05:06 -0700218 }
219 };
220
Fred Quintanafb2e18e2011-07-13 14:54:05 -0700221 private boolean hasGrantInternal(final SQLiteDatabase db, final int uid, final String alias) {
222 final long numMatches = DatabaseUtils.longForQuery(db, SELECTION_COUNT_OF_MATCHING_GRANTS,
223 new String[]{String.valueOf(uid), alias});
224 return numMatches > 0;
225 }
Brian Carlstrom3e6251d2011-04-11 09:05:06 -0700226
Fred Quintanafb2e18e2011-07-13 14:54:05 -0700227 private void setGrantInternal(final SQLiteDatabase db,
228 final int uid, final String alias, final boolean value) {
229 if (value) {
230 if (!hasGrantInternal(db, uid, alias)) {
231 final ContentValues values = new ContentValues();
232 values.put(GRANTS_ALIAS, alias);
233 values.put(GRANTS_GRANTEE_UID, uid);
234 db.insert(TABLE_GRANTS, GRANTS_ALIAS, values);
235 }
236 } else {
237 db.delete(TABLE_GRANTS, SELECT_GRANTS_BY_UID_AND_ALIAS,
238 new String[]{String.valueOf(uid), alias});
239 }
240 }
241
242 private void removeAllGrants(final SQLiteDatabase db) {
243 db.delete(TABLE_GRANTS, null /* whereClause */, null /* whereArgs */);
244 }
245
246 private class DatabaseHelper extends SQLiteOpenHelper {
247 public DatabaseHelper(Context context) {
248 super(context, DATABASE_NAME, null /* CursorFactory */, DATABASE_VERSION);
249 }
250
251 @Override
252 public void onCreate(final SQLiteDatabase db) {
253 db.execSQL("CREATE TABLE " + TABLE_GRANTS + " ( "
254 + GRANTS_ALIAS + " STRING NOT NULL, "
255 + GRANTS_GRANTEE_UID + " INTEGER NOT NULL, "
256 + "UNIQUE (" + GRANTS_ALIAS + "," + GRANTS_GRANTEE_UID + "))");
257 }
258
259 @Override
260 public void onUpgrade(final SQLiteDatabase db, int oldVersion, final int newVersion) {
261 Log.e(TAG, "upgrade from version " + oldVersion + " to version " + newVersion);
262
263 if (oldVersion == 1) {
264 // the first upgrade step goes here
265 oldVersion++;
Brian Carlstrom3e6251d2011-04-11 09:05:06 -0700266 }
Brian Carlstrom7037b732011-06-30 15:04:49 -0700267 }
Fred Quintanafb2e18e2011-07-13 14:54:05 -0700268 }
269
270 @Override public IBinder onBind(Intent intent) {
Brian Carlstrom7037b732011-06-30 15:04:49 -0700271 if (IKeyChainService.class.getName().equals(intent.getAction())) {
Brian Carlstrom3e6251d2011-04-11 09:05:06 -0700272 return mIKeyChainService;
273 }
Brian Carlstrom3e6251d2011-04-11 09:05:06 -0700274 return null;
275 }
Fred Quintanafb2e18e2011-07-13 14:54:05 -0700276
277 @Override
278 protected void onHandleIntent(final Intent intent) {
279 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) {
280 purgeOldGrants();
281 }
282 }
283
284 private void purgeOldGrants() {
285 final PackageManager packageManager = getPackageManager();
286 final SQLiteDatabase db = mDatabaseHelper.getWritableDatabase();
287 Cursor cursor = null;
288 db.beginTransaction();
289 try {
290 cursor = db.query(TABLE_GRANTS,
291 new String[]{GRANTS_GRANTEE_UID}, null, null, GRANTS_GRANTEE_UID, null, null);
292 while (cursor.moveToNext()) {
293 final int uid = cursor.getInt(0);
294 final boolean packageExists = packageManager.getPackagesForUid(uid) != null;
295 if (packageExists) {
296 continue;
297 }
298 Log.d(TAG, "deleting grants for UID " + uid
299 + " because its package is no longer installed");
300 db.delete(TABLE_GRANTS, SELECTION_GRANTS_BY_UID,
301 new String[]{Integer.toString(uid)});
302 }
303 db.setTransactionSuccessful();
304 } finally {
305 if (cursor != null) {
306 cursor.close();
307 }
308 db.endTransaction();
309 }
310 }
Selim Gurun39e36e52012-02-14 10:50:42 -0800311
312 private void broadcastStorageChange() {
313 Intent intent = new Intent(KeyChain.ACTION_STORAGE_CHANGED);
314 sendBroadcast(intent);
315 }
316
Brian Carlstrom3e6251d2011-04-11 09:05:06 -0700317}