blob: 6351cd07b6ab0f8ae68255e98ad44f576343def5 [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
Chad Brubaker2099a7d2016-05-02 13:13:23 -070019import android.app.BroadcastOptions;
Fred Quintanafb2e18e2011-07-13 14:54:05 -070020import android.app.IntentService;
21import android.content.ContentValues;
Brian Carlstrom3e6251d2011-04-11 09:05:06 -070022import android.content.Context;
23import android.content.Intent;
Fred Quintanafb2e18e2011-07-13 14:54:05 -070024import android.content.pm.PackageManager;
Robin Lee7e9d0452017-02-20 20:57:41 +000025import android.content.pm.StringParceledListSlice;
Fred Quintanafb2e18e2011-07-13 14:54:05 -070026import android.database.Cursor;
27import android.database.DatabaseUtils;
28import android.database.sqlite.SQLiteDatabase;
29import android.database.sqlite.SQLiteOpenHelper;
Kenny Root6f1f03b2012-03-08 10:30:39 -080030import android.os.Binder;
Chad Brubaker2099a7d2016-05-02 13:13:23 -070031import android.os.Build;
Brian Carlstrom3e6251d2011-04-11 09:05:06 -070032import android.os.IBinder;
Kenny Root6f1f03b2012-03-08 10:30:39 -080033import android.os.Process;
Robin Lee93772c32014-09-02 14:53:50 +010034import android.os.UserHandle;
Brian Carlstrom3e6251d2011-04-11 09:05:06 -070035import android.security.Credentials;
36import android.security.IKeyChainService;
Selim Gurun39e36e52012-02-14 10:50:42 -080037import android.security.KeyChain;
Brian Carlstrom3e6251d2011-04-11 09:05:06 -070038import android.security.KeyStore;
39import android.util.Log;
40import java.io.ByteArrayInputStream;
Brian Carlstroma58db542011-05-11 23:02:20 -070041import java.io.IOException;
Brian Carlstrom3e6251d2011-04-11 09:05:06 -070042import java.security.cert.CertificateException;
Zoltan Szatmary-Ban3d25b312014-08-18 10:54:19 +010043import java.security.cert.CertificateEncodingException;
Brian Carlstrom3e6251d2011-04-11 09:05:06 -070044import java.security.cert.CertificateFactory;
45import java.security.cert.X509Certificate;
Zoltan Szatmary-Ban3d25b312014-08-18 10:54:19 +010046import java.util.Set;
47import java.util.List;
48import java.util.ArrayList;
49import java.util.Collections;
Fred Quintanafb2e18e2011-07-13 14:54:05 -070050
Kenny Root3048b6c2013-04-23 22:38:11 -070051import com.android.org.conscrypt.TrustedCertificateStore;
Brian Carlstrom3e6251d2011-04-11 09:05:06 -070052
Fred Quintanafb2e18e2011-07-13 14:54:05 -070053public class KeyChainService extends IntentService {
Selim Gurun39e36e52012-02-14 10:50:42 -080054
Fred Quintanafb2e18e2011-07-13 14:54:05 -070055 private static final String TAG = "KeyChain";
Brian Carlstrom3e6251d2011-04-11 09:05:06 -070056
Fred Quintanafb2e18e2011-07-13 14:54:05 -070057 private static final String DATABASE_NAME = "grants.db";
58 private static final int DATABASE_VERSION = 1;
59 private static final String TABLE_GRANTS = "grants";
60 private static final String GRANTS_ALIAS = "alias";
61 private static final String GRANTS_GRANTEE_UID = "uid";
Brian Carlstrom3e6251d2011-04-11 09:05:06 -070062
Fred Quintanafb2e18e2011-07-13 14:54:05 -070063 /** created in onCreate(), closed in onDestroy() */
64 public DatabaseHelper mDatabaseHelper;
Brian Carlstrom3e6251d2011-04-11 09:05:06 -070065
Fred Quintanafb2e18e2011-07-13 14:54:05 -070066 private static final String SELECTION_COUNT_OF_MATCHING_GRANTS =
67 "SELECT COUNT(*) FROM " + TABLE_GRANTS
68 + " WHERE " + GRANTS_GRANTEE_UID + "=? AND " + GRANTS_ALIAS + "=?";
69
70 private static final String SELECT_GRANTS_BY_UID_AND_ALIAS =
71 GRANTS_GRANTEE_UID + "=? AND " + GRANTS_ALIAS + "=?";
72
73 private static final String SELECTION_GRANTS_BY_UID = GRANTS_GRANTEE_UID + "=?";
74
Robin Leeba755b12016-02-24 15:27:43 +000075 private static final String SELECTION_GRANTS_BY_ALIAS = GRANTS_ALIAS + "=?";
76
Fred Quintanafb2e18e2011-07-13 14:54:05 -070077 public KeyChainService() {
78 super(KeyChainService.class.getSimpleName());
79 }
Brian Carlstrom3e6251d2011-04-11 09:05:06 -070080
81 @Override public void onCreate() {
82 super.onCreate();
Fred Quintanafb2e18e2011-07-13 14:54:05 -070083 mDatabaseHelper = new DatabaseHelper(this);
84 }
85
86 @Override
87 public void onDestroy() {
88 super.onDestroy();
89 mDatabaseHelper.close();
90 mDatabaseHelper = null;
Brian Carlstrom3e6251d2011-04-11 09:05:06 -070091 }
92
93 private final IKeyChainService.Stub mIKeyChainService = new IKeyChainService.Stub() {
Brian Carlstrom3e6251d2011-04-11 09:05:06 -070094 private final KeyStore mKeyStore = KeyStore.getInstance();
Brian Carlstroma58db542011-05-11 23:02:20 -070095 private final TrustedCertificateStore mTrustedCertificateStore
96 = new TrustedCertificateStore();
Brian Carlstrom3e6251d2011-04-11 09:05:06 -070097
Kenny Root6f1f03b2012-03-08 10:30:39 -080098 @Override
99 public String requestPrivateKey(String alias) {
100 checkArgs(alias);
101
102 final String keystoreAlias = Credentials.USER_PRIVATE_KEY + alias;
103 final int uid = Binder.getCallingUid();
104 if (!mKeyStore.grant(keystoreAlias, uid)) {
105 return null;
106 }
Robin Lee93772c32014-09-02 14:53:50 +0100107 final int userHandle = UserHandle.getUserId(uid);
108 final int systemUidForUser = UserHandle.getUid(userHandle, Process.SYSTEM_UID);
Kenny Root6f1f03b2012-03-08 10:30:39 -0800109
110 final StringBuilder sb = new StringBuilder();
Robin Lee93772c32014-09-02 14:53:50 +0100111 sb.append(systemUidForUser);
Kenny Root6f1f03b2012-03-08 10:30:39 -0800112 sb.append('_');
113 sb.append(keystoreAlias);
114
115 return sb.toString();
Brian Carlstrom3e6251d2011-04-11 09:05:06 -0700116 }
117
Fred Quintanafb2e18e2011-07-13 14:54:05 -0700118 @Override public byte[] getCertificate(String alias) {
Kenny Root6f1f03b2012-03-08 10:30:39 -0800119 checkArgs(alias);
120 return mKeyStore.get(Credentials.USER_CERTIFICATE + alias);
Brian Carlstrom3e6251d2011-04-11 09:05:06 -0700121 }
122
Rubin Xu8714f062016-03-23 12:37:10 +0000123 @Override public byte[] getCaCertificates(String alias) {
124 checkArgs(alias);
125 return mKeyStore.get(Credentials.CA_CERTIFICATE + alias);
126 }
127
Kenny Root6f1f03b2012-03-08 10:30:39 -0800128 private void checkArgs(String alias) {
Brian Carlstrom3e6251d2011-04-11 09:05:06 -0700129 if (alias == null) {
130 throw new NullPointerException("alias == null");
131 }
Kenny Root4ff22962013-02-14 10:17:06 -0800132 if (!mKeyStore.isUnlocked()) {
Nick Kralevichc8b04632012-05-21 15:13:07 -0700133 throw new IllegalStateException("keystore is "
134 + mKeyStore.state().toString());
Brian Carlstrom3e6251d2011-04-11 09:05:06 -0700135 }
Nick Kralevichc8b04632012-05-21 15:13:07 -0700136
Fred Quintanafb2e18e2011-07-13 14:54:05 -0700137 final int callingUid = getCallingUid();
138 if (!hasGrantInternal(mDatabaseHelper.getReadableDatabase(), callingUid, alias)) {
139 throw new IllegalStateException("uid " + callingUid
140 + " doesn't have permission to access the requested alias");
Brian Carlstrom3e6251d2011-04-11 09:05:06 -0700141 }
Brian Carlstrom3e6251d2011-04-11 09:05:06 -0700142 }
143
Bartosz Fabianowski9bacf2b2017-02-10 02:26:45 +0100144 @Override public String installCaCertificate(byte[] caCertificate) {
Brian Carlstrom43f5b772011-06-27 02:27:16 -0700145 checkCertInstallerOrSystemCaller();
Bartosz Fabianowski9bacf2b2017-02-10 02:26:45 +0100146 final String alias;
Brian Carlstroma58db542011-05-11 23:02:20 -0700147 try {
Bartosz Fabianowski9bacf2b2017-02-10 02:26:45 +0100148 final X509Certificate cert = parseCertificate(caCertificate);
Brian Carlstroma58db542011-05-11 23:02:20 -0700149 synchronized (mTrustedCertificateStore) {
Bartosz Fabianowski9bacf2b2017-02-10 02:26:45 +0100150 mTrustedCertificateStore.installCertificate(cert);
151 alias = mTrustedCertificateStore.getCertificateAlias(cert);
Brian Carlstroma58db542011-05-11 23:02:20 -0700152 }
153 } catch (IOException e) {
154 throw new IllegalStateException(e);
155 } catch (CertificateException e) {
156 throw new IllegalStateException(e);
157 }
Chad Brubaker2099a7d2016-05-02 13:13:23 -0700158 broadcastLegacyStorageChange();
159 broadcastTrustStoreChange();
Bartosz Fabianowski9bacf2b2017-02-10 02:26:45 +0100160 return alias;
Brian Carlstroma58db542011-05-11 23:02:20 -0700161 }
Brian Carlstrom5aeadd92011-05-17 00:40:33 -0700162
Rubin Xu8714f062016-03-23 12:37:10 +0000163 /**
164 * Install a key pair to the keystore.
165 *
166 * @param privateKey The private key associated with the client certificate
167 * @param userCertificate The client certificate to be installed
168 * @param userCertificateChain The rest of the chain for the client certificate
169 * @param alias The alias under which the key pair is installed
170 * @return Whether the operation succeeded or not.
171 */
Bernhard Bauerd300fc52014-07-21 15:32:30 +0100172 @Override public boolean installKeyPair(byte[] privateKey, byte[] userCertificate,
Rubin Xu8714f062016-03-23 12:37:10 +0000173 byte[] userCertificateChain, String alias) {
Bernhard Bauerd300fc52014-07-21 15:32:30 +0100174 checkCertInstallerOrSystemCaller();
Robin Lee8847b122015-07-27 12:50:28 +0100175 if (!mKeyStore.isUnlocked()) {
176 Log.e(TAG, "Keystore is " + mKeyStore.state().toString() + ". Credentials cannot"
177 + " be installed until device is unlocked");
178 return false;
179 }
Robin Leeba755b12016-02-24 15:27:43 +0000180 if (!removeKeyPair(alias)) {
181 return false;
182 }
Bernhard Bauerd300fc52014-07-21 15:32:30 +0100183 if (!mKeyStore.importKey(Credentials.USER_PRIVATE_KEY + alias, privateKey, -1,
184 KeyStore.FLAG_ENCRYPTED)) {
185 Log.e(TAG, "Failed to import private key " + alias);
186 return false;
187 }
188 if (!mKeyStore.put(Credentials.USER_CERTIFICATE + alias, userCertificate, -1,
189 KeyStore.FLAG_ENCRYPTED)) {
190 Log.e(TAG, "Failed to import user certificate " + userCertificate);
Alex Klyubin44c777b2015-06-08 09:46:15 -0700191 if (!mKeyStore.delete(Credentials.USER_PRIVATE_KEY + alias)) {
Bernhard Bauerd300fc52014-07-21 15:32:30 +0100192 Log.e(TAG, "Failed to delete private key after certificate importing failed");
193 }
194 return false;
195 }
Rubin Xu8714f062016-03-23 12:37:10 +0000196 if (userCertificateChain != null && userCertificateChain.length > 0) {
197 if (!mKeyStore.put(Credentials.CA_CERTIFICATE + alias, userCertificateChain, -1,
198 KeyStore.FLAG_ENCRYPTED)) {
199 Log.e(TAG, "Failed to import certificate chain" + userCertificateChain);
200 if (!removeKeyPair(alias)) {
201 Log.e(TAG, "Failed to clean up key chain after certificate chain"
202 + " importing failed");
203 }
204 return false;
205 }
206 }
Chad Brubaker2099a7d2016-05-02 13:13:23 -0700207 broadcastKeychainChange();
208 broadcastLegacyStorageChange();
Bernhard Bauerd300fc52014-07-21 15:32:30 +0100209 return true;
210 }
211
Robin Leef44a5192015-08-03 17:18:02 +0100212 @Override public boolean removeKeyPair(String alias) {
213 checkCertInstallerOrSystemCaller();
Robin Leeba755b12016-02-24 15:27:43 +0000214 if (!Credentials.deleteAllTypesForAlias(mKeyStore, alias)) {
215 return false;
216 }
217 removeGrantsForAlias(alias);
Chad Brubaker2099a7d2016-05-02 13:13:23 -0700218 broadcastKeychainChange();
219 broadcastLegacyStorageChange();
Robin Leeba755b12016-02-24 15:27:43 +0000220 return true;
Robin Leef44a5192015-08-03 17:18:02 +0100221 }
222
Brian Carlstrom5aeadd92011-05-17 00:40:33 -0700223 private X509Certificate parseCertificate(byte[] bytes) throws CertificateException {
224 CertificateFactory cf = CertificateFactory.getInstance("X.509");
225 return (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(bytes));
226 }
227
Brian Carlstroma58db542011-05-11 23:02:20 -0700228 @Override public boolean reset() {
229 // only Settings should be able to reset
Brian Carlstrom43f5b772011-06-27 02:27:16 -0700230 checkSystemCaller();
Fred Quintanafb2e18e2011-07-13 14:54:05 -0700231 removeAllGrants(mDatabaseHelper.getWritableDatabase());
Brian Carlstroma58db542011-05-11 23:02:20 -0700232 boolean ok = true;
Brian Carlstroma58db542011-05-11 23:02:20 -0700233 synchronized (mTrustedCertificateStore) {
234 // delete user-installed CA certs
235 for (String alias : mTrustedCertificateStore.aliases()) {
236 if (TrustedCertificateStore.isUser(alias)) {
Brian Carlstrom43f5b772011-06-27 02:27:16 -0700237 if (!deleteCertificateEntry(alias)) {
Brian Carlstroma58db542011-05-11 23:02:20 -0700238 ok = false;
239 }
240 }
241 }
Brian Carlstroma58db542011-05-11 23:02:20 -0700242 }
Chad Brubaker2099a7d2016-05-02 13:13:23 -0700243 broadcastTrustStoreChange();
244 broadcastLegacyStorageChange();
Selim Gurun39e36e52012-02-14 10:50:42 -0800245 return ok;
Brian Carlstroma58db542011-05-11 23:02:20 -0700246 }
Brian Carlstrom43f5b772011-06-27 02:27:16 -0700247
248 @Override public boolean deleteCaCertificate(String alias) {
249 // only Settings should be able to delete
250 checkSystemCaller();
Selim Gurun39e36e52012-02-14 10:50:42 -0800251 boolean ok = true;
252 synchronized (mTrustedCertificateStore) {
253 ok = deleteCertificateEntry(alias);
254 }
Chad Brubaker2099a7d2016-05-02 13:13:23 -0700255 broadcastTrustStoreChange();
256 broadcastLegacyStorageChange();
Selim Gurun39e36e52012-02-14 10:50:42 -0800257 return ok;
Brian Carlstrom43f5b772011-06-27 02:27:16 -0700258 }
259
260 private boolean deleteCertificateEntry(String alias) {
261 try {
262 mTrustedCertificateStore.deleteCertificateEntry(alias);
263 return true;
264 } catch (IOException e) {
265 Log.w(TAG, "Problem removing CA certificate " + alias, e);
266 return false;
267 } catch (CertificateException e) {
268 Log.w(TAG, "Problem removing CA certificate " + alias, e);
269 return false;
270 }
271 }
272
273 private void checkCertInstallerOrSystemCaller() {
274 String actual = checkCaller("com.android.certinstaller");
275 if (actual == null) {
276 return;
277 }
278 checkSystemCaller();
279 }
280 private void checkSystemCaller() {
281 String actual = checkCaller("android.uid.system:1000");
282 if (actual != null) {
283 throw new IllegalStateException(actual);
284 }
285 }
286 /**
287 * Returns null if actually caller is expected, otherwise return bad package to report
288 */
289 private String checkCaller(String expectedPackage) {
290 String actualPackage = getPackageManager().getNameForUid(getCallingUid());
291 return (!expectedPackage.equals(actualPackage)) ? actualPackage : null;
292 }
Brian Carlstrom3e6251d2011-04-11 09:05:06 -0700293
Fred Quintanafb2e18e2011-07-13 14:54:05 -0700294 @Override public boolean hasGrant(int uid, String alias) {
295 checkSystemCaller();
296 return hasGrantInternal(mDatabaseHelper.getReadableDatabase(), uid, alias);
Brian Carlstrom3e6251d2011-04-11 09:05:06 -0700297 }
298
Fred Quintanafb2e18e2011-07-13 14:54:05 -0700299 @Override public void setGrant(int uid, String alias, boolean value) {
300 checkSystemCaller();
301 setGrantInternal(mDatabaseHelper.getWritableDatabase(), uid, alias, value);
Chad Brubaker2099a7d2016-05-02 13:13:23 -0700302 broadcastPermissionChange(uid, alias, value);
303 broadcastLegacyStorageChange();
Brian Carlstrom3e6251d2011-04-11 09:05:06 -0700304 }
Zoltan Szatmary-Ban3d25b312014-08-18 10:54:19 +0100305
Zoltan Szatmary-Ban3d25b312014-08-18 10:54:19 +0100306 @Override
Robin Lee7e9d0452017-02-20 20:57:41 +0000307 public StringParceledListSlice getUserCaAliases() {
Zoltan Szatmary-Ban3d25b312014-08-18 10:54:19 +0100308 synchronized (mTrustedCertificateStore) {
Robin Lee7e9d0452017-02-20 20:57:41 +0000309 return new StringParceledListSlice(new ArrayList<String>(
310 mTrustedCertificateStore.userAliases()));
Zoltan Szatmary-Ban3d25b312014-08-18 10:54:19 +0100311 }
312 }
313
314 @Override
Robin Lee7e9d0452017-02-20 20:57:41 +0000315 public StringParceledListSlice getSystemCaAliases() {
Zoltan Szatmary-Ban3d25b312014-08-18 10:54:19 +0100316 synchronized (mTrustedCertificateStore) {
Robin Lee7e9d0452017-02-20 20:57:41 +0000317 return new StringParceledListSlice(new ArrayList<String>(
318 mTrustedCertificateStore.allSystemAliases()));
Zoltan Szatmary-Ban3d25b312014-08-18 10:54:19 +0100319 }
320 }
321
322 @Override
323 public boolean containsCaAlias(String alias) {
324 return mTrustedCertificateStore.containsAlias(alias);
325 }
326
327 @Override
328 public byte[] getEncodedCaCertificate(String alias, boolean includeDeletedSystem) {
329 synchronized (mTrustedCertificateStore) {
330 X509Certificate certificate = (X509Certificate) mTrustedCertificateStore
331 .getCertificate(alias, includeDeletedSystem);
332 if (certificate == null) {
333 Log.w(TAG, "Could not find CA certificate " + alias);
334 return null;
335 }
336 try {
337 return certificate.getEncoded();
338 } catch (CertificateEncodingException e) {
339 Log.w(TAG, "Error while encoding CA certificate " + alias);
340 return null;
341 }
342 }
343 }
344
345 @Override
346 public List<String> getCaCertificateChainAliases(String rootAlias,
347 boolean includeDeletedSystem) {
348 synchronized (mTrustedCertificateStore) {
349 X509Certificate root = (X509Certificate) mTrustedCertificateStore.getCertificate(
350 rootAlias, includeDeletedSystem);
351 try {
352 List<X509Certificate> chain = mTrustedCertificateStore.getCertificateChain(
353 root);
354 List<String> aliases = new ArrayList<String>(chain.size());
355 final int n = chain.size();
356 for (int i = 0; i < n; ++i) {
357 String alias = mTrustedCertificateStore.getCertificateAlias(chain.get(i),
358 true);
359 if (alias != null) {
360 aliases.add(alias);
361 }
362 }
363 return aliases;
364 } catch (CertificateException e) {
365 Log.w(TAG, "Error retrieving cert chain for root " + rootAlias);
366 return Collections.emptyList();
367 }
368 }
369 }
Brian Carlstrom3e6251d2011-04-11 09:05:06 -0700370 };
371
Fred Quintanafb2e18e2011-07-13 14:54:05 -0700372 private boolean hasGrantInternal(final SQLiteDatabase db, final int uid, final String alias) {
373 final long numMatches = DatabaseUtils.longForQuery(db, SELECTION_COUNT_OF_MATCHING_GRANTS,
374 new String[]{String.valueOf(uid), alias});
375 return numMatches > 0;
376 }
Brian Carlstrom3e6251d2011-04-11 09:05:06 -0700377
Fred Quintanafb2e18e2011-07-13 14:54:05 -0700378 private void setGrantInternal(final SQLiteDatabase db,
379 final int uid, final String alias, final boolean value) {
380 if (value) {
381 if (!hasGrantInternal(db, uid, alias)) {
382 final ContentValues values = new ContentValues();
383 values.put(GRANTS_ALIAS, alias);
384 values.put(GRANTS_GRANTEE_UID, uid);
385 db.insert(TABLE_GRANTS, GRANTS_ALIAS, values);
386 }
387 } else {
388 db.delete(TABLE_GRANTS, SELECT_GRANTS_BY_UID_AND_ALIAS,
389 new String[]{String.valueOf(uid), alias});
390 }
391 }
392
Robin Leeba755b12016-02-24 15:27:43 +0000393 private void removeGrantsForAlias(String alias) {
394 final SQLiteDatabase db = mDatabaseHelper.getWritableDatabase();
395 db.delete(TABLE_GRANTS, SELECTION_GRANTS_BY_ALIAS, new String[] {alias});
396 }
397
Fred Quintanafb2e18e2011-07-13 14:54:05 -0700398 private void removeAllGrants(final SQLiteDatabase db) {
399 db.delete(TABLE_GRANTS, null /* whereClause */, null /* whereArgs */);
400 }
401
402 private class DatabaseHelper extends SQLiteOpenHelper {
403 public DatabaseHelper(Context context) {
404 super(context, DATABASE_NAME, null /* CursorFactory */, DATABASE_VERSION);
405 }
406
407 @Override
408 public void onCreate(final SQLiteDatabase db) {
409 db.execSQL("CREATE TABLE " + TABLE_GRANTS + " ( "
410 + GRANTS_ALIAS + " STRING NOT NULL, "
411 + GRANTS_GRANTEE_UID + " INTEGER NOT NULL, "
412 + "UNIQUE (" + GRANTS_ALIAS + "," + GRANTS_GRANTEE_UID + "))");
413 }
414
415 @Override
416 public void onUpgrade(final SQLiteDatabase db, int oldVersion, final int newVersion) {
417 Log.e(TAG, "upgrade from version " + oldVersion + " to version " + newVersion);
418
419 if (oldVersion == 1) {
420 // the first upgrade step goes here
421 oldVersion++;
Brian Carlstrom3e6251d2011-04-11 09:05:06 -0700422 }
Brian Carlstrom7037b732011-06-30 15:04:49 -0700423 }
Fred Quintanafb2e18e2011-07-13 14:54:05 -0700424 }
425
426 @Override public IBinder onBind(Intent intent) {
Brian Carlstrom7037b732011-06-30 15:04:49 -0700427 if (IKeyChainService.class.getName().equals(intent.getAction())) {
Brian Carlstrom3e6251d2011-04-11 09:05:06 -0700428 return mIKeyChainService;
429 }
Brian Carlstrom3e6251d2011-04-11 09:05:06 -0700430 return null;
431 }
Fred Quintanafb2e18e2011-07-13 14:54:05 -0700432
433 @Override
434 protected void onHandleIntent(final Intent intent) {
435 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) {
436 purgeOldGrants();
437 }
438 }
439
440 private void purgeOldGrants() {
441 final PackageManager packageManager = getPackageManager();
442 final SQLiteDatabase db = mDatabaseHelper.getWritableDatabase();
443 Cursor cursor = null;
444 db.beginTransaction();
445 try {
446 cursor = db.query(TABLE_GRANTS,
447 new String[]{GRANTS_GRANTEE_UID}, null, null, GRANTS_GRANTEE_UID, null, null);
448 while (cursor.moveToNext()) {
449 final int uid = cursor.getInt(0);
450 final boolean packageExists = packageManager.getPackagesForUid(uid) != null;
451 if (packageExists) {
452 continue;
453 }
454 Log.d(TAG, "deleting grants for UID " + uid
455 + " because its package is no longer installed");
456 db.delete(TABLE_GRANTS, SELECTION_GRANTS_BY_UID,
457 new String[]{Integer.toString(uid)});
458 }
459 db.setTransactionSuccessful();
460 } finally {
461 if (cursor != null) {
462 cursor.close();
463 }
464 db.endTransaction();
465 }
466 }
Selim Gurun39e36e52012-02-14 10:50:42 -0800467
Chad Brubaker2099a7d2016-05-02 13:13:23 -0700468 private void broadcastLegacyStorageChange() {
Selim Gurun39e36e52012-02-14 10:50:42 -0800469 Intent intent = new Intent(KeyChain.ACTION_STORAGE_CHANGED);
Chad Brubaker2099a7d2016-05-02 13:13:23 -0700470 BroadcastOptions opts = BroadcastOptions.makeBasic();
Chad Brubaker04028072016-07-08 10:48:54 -0700471 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.N_MR1);
Chad Brubakere5a5dd12016-07-25 14:34:54 -0700472 sendBroadcastAsUser(intent, UserHandle.of(UserHandle.myUserId()), null, opts.toBundle());
Selim Gurun39e36e52012-02-14 10:50:42 -0800473 }
474
Chad Brubaker2099a7d2016-05-02 13:13:23 -0700475 private void broadcastKeychainChange() {
476 Intent intent = new Intent(KeyChain.ACTION_KEYCHAIN_CHANGED);
Chad Brubakere5a5dd12016-07-25 14:34:54 -0700477 sendBroadcastAsUser(intent, UserHandle.of(UserHandle.myUserId()));
Chad Brubaker2099a7d2016-05-02 13:13:23 -0700478 }
479
480 private void broadcastTrustStoreChange() {
481 Intent intent = new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED);
Chad Brubakere5a5dd12016-07-25 14:34:54 -0700482 sendBroadcastAsUser(intent, UserHandle.of(UserHandle.myUserId()));
Chad Brubaker2099a7d2016-05-02 13:13:23 -0700483 }
484
485 private void broadcastPermissionChange(int uid, String alias, boolean access) {
486 // Since the permission change only impacts one uid only send to that uid's packages.
487 final PackageManager packageManager = getPackageManager();
488 String[] packages = packageManager.getPackagesForUid(uid);
489 if (packages == null) {
490 return;
491 }
492 for (String pckg : packages) {
493 Intent intent = new Intent(KeyChain.ACTION_KEY_ACCESS_CHANGED);
494 intent.putExtra(KeyChain.EXTRA_KEY_ALIAS, alias);
495 intent.putExtra(KeyChain.EXTRA_KEY_ACCESSIBLE, access);
496 intent.setPackage(pckg);
Chad Brubakere5a5dd12016-07-25 14:34:54 -0700497 sendBroadcastAsUser(intent, UserHandle.of(UserHandle.myUserId()));
Chad Brubaker2099a7d2016-05-02 13:13:23 -0700498 }
499 }
Brian Carlstrom3e6251d2011-04-11 09:05:06 -0700500}