blob: 7de26d6965383d11aa4254c8c2d254edd7e5e508 [file] [log] [blame]
Brian Carlstromb9a07c12011-04-11 09:03:51 -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 */
16package android.security;
17
Alex Klyubin54bb1592015-05-11 12:30:03 -070018import android.annotation.NonNull;
19import android.annotation.Nullable;
Robin Lee59e3baa2015-06-30 10:48:06 -070020import android.annotation.WorkerThread;
Brian Carlstromba1a6672011-05-24 21:54:37 -070021import android.app.Activity;
Brian Carlstrom67c30df2011-06-24 02:13:23 -070022import android.app.PendingIntent;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070023import android.content.ComponentName;
24import android.content.Context;
25import android.content.Intent;
26import android.content.ServiceConnection;
Robin Lee39087b12015-05-05 15:57:17 +010027import android.net.Uri;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070028import android.os.IBinder;
29import android.os.Looper;
Robin Lee306fe082014-06-19 14:04:24 +000030import android.os.Process;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070031import android.os.RemoteException;
Robin Lee306fe082014-06-19 14:04:24 +000032import android.os.UserHandle;
Alex Klyubin4a0ff7c2015-06-09 13:25:20 -070033import android.security.keystore.AndroidKeyStoreProvider;
Alex Klyubin3f8d4d82015-05-13 09:15:00 -070034import android.security.keystore.KeyProperties;
35
Brian Carlstromb9a07c12011-04-11 09:03:51 -070036import java.io.ByteArrayInputStream;
Brian Carlstromd7524722011-05-17 16:20:36 -070037import java.io.Closeable;
Brian Carlstrom93201f52011-06-09 15:05:35 -070038import java.security.Principal;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070039import java.security.PrivateKey;
Alex Klyubin4a0ff7c2015-06-09 13:25:20 -070040import java.security.UnrecoverableKeyException;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070041import java.security.cert.Certificate;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070042import java.security.cert.CertificateException;
43import java.security.cert.CertificateFactory;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070044import java.security.cert.X509Certificate;
Brian Carlstromdb93b782011-07-01 00:12:17 -070045import java.util.List;
Kenny Rootb91773b2013-09-05 13:03:16 -070046import java.util.Locale;
Brian Carlstrom8e9929c2011-05-17 00:40:28 -070047import java.util.concurrent.BlockingQueue;
48import java.util.concurrent.LinkedBlockingQueue;
Kenny Root5423e682011-11-14 08:43:13 -080049
Kenny Root12e75222013-04-23 22:34:24 -070050import com.android.org.conscrypt.TrustedCertificateStore;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070051
52/**
Brian Carlstrom93201f52011-06-09 15:05:35 -070053 * The {@code KeyChain} class provides access to private keys and
54 * their corresponding certificate chains in credential storage.
55 *
56 * <p>Applications accessing the {@code KeyChain} normally go through
57 * these steps:
58 *
59 * <ol>
60 *
61 * <li>Receive a callback from an {@link javax.net.ssl.X509KeyManager
62 * X509KeyManager} that a private key is requested.
63 *
64 * <li>Call {@link #choosePrivateKeyAlias
65 * choosePrivateKeyAlias} to allow the user to select from a
66 * list of currently available private keys and corresponding
67 * certificate chains. The chosen alias will be returned by the
68 * callback {@link KeyChainAliasCallback#alias}, or null if no private
69 * key is available or the user cancels the request.
70 *
71 * <li>Call {@link #getPrivateKey} and {@link #getCertificateChain} to
72 * retrieve the credentials to return to the corresponding {@link
73 * javax.net.ssl.X509KeyManager} callbacks.
74 *
75 * </ol>
76 *
77 * <p>An application may remember the value of a selected alias to
78 * avoid prompting the user with {@link #choosePrivateKeyAlias
79 * choosePrivateKeyAlias} on subsequent connections. If the alias is
80 * no longer valid, null will be returned on lookups using that value
Brian Carlstromca43c452011-06-29 18:53:17 -070081 *
82 * <p>An application can request the installation of private keys and
83 * certificates via the {@code Intent} provided by {@link
84 * #createInstallIntent}. Private keys installed via this {@code
85 * Intent} will be accessible via {@link #choosePrivateKeyAlias} while
86 * Certificate Authority (CA) certificates will be trusted by all
87 * applications through the default {@code X509TrustManager}.
Brian Carlstromb9a07c12011-04-11 09:03:51 -070088 */
Brian Carlstrom93201f52011-06-09 15:05:35 -070089// TODO reference intent for credential installation when public
Brian Carlstromb9a07c12011-04-11 09:03:51 -070090public final class KeyChain {
91
Brian Carlstromb9a07c12011-04-11 09:03:51 -070092 /**
93 * @hide Also used by KeyChainService implementation
94 */
95 public static final String ACCOUNT_TYPE = "com.android.keychain";
96
97 /**
Kenny Roota3659062014-03-17 16:21:53 -070098 * Package name for KeyChain chooser.
99 */
100 private static final String KEYCHAIN_PACKAGE = "com.android.keychain";
101
102 /**
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700103 * Action to bring up the KeyChainActivity
104 */
105 private static final String ACTION_CHOOSER = "com.android.keychain.CHOOSER";
106
107 /**
Kenny Root1a88d832014-02-07 09:12:48 -0800108 * Package name for the Certificate Installer.
109 */
110 private static final String CERT_INSTALLER_PACKAGE = "com.android.certinstaller";
111
112 /**
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700113 * Extra for use with {@link #ACTION_CHOOSER}
Brian Carlstromba1a6672011-05-24 21:54:37 -0700114 * @hide Also used by KeyChainActivity implementation
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700115 */
Brian Carlstromba1a6672011-05-24 21:54:37 -0700116 public static final String EXTRA_RESPONSE = "response";
117
118 /**
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700119 * Extra for use with {@link #ACTION_CHOOSER}
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700120 * @hide Also used by KeyChainActivity implementation
121 */
Robin Lee39087b12015-05-05 15:57:17 +0100122 public static final String EXTRA_URI = "uri";
Robin Lee3798ed52015-02-03 17:55:31 +0000123
124 /**
125 * Extra for use with {@link #ACTION_CHOOSER}
126 * @hide Also used by KeyChainActivity implementation
127 */
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700128 public static final String EXTRA_ALIAS = "alias";
129
130 /**
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700131 * Extra for use with {@link #ACTION_CHOOSER}
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700132 * @hide Also used by KeyChainActivity implementation
133 */
134 public static final String EXTRA_SENDER = "sender";
135
136 /**
Selim Gurun93ba4fe2012-02-14 11:48:49 -0800137 * Action to bring up the CertInstaller.
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700138 */
139 private static final String ACTION_INSTALL = "android.credentials.INSTALL";
140
141 /**
142 * Optional extra to specify a {@code String} credential name on
143 * the {@code Intent} returned by {@link #createInstallIntent}.
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700144 */
145 // Compatible with old com.android.certinstaller.CredentialHelper.CERT_NAME_KEY
146 public static final String EXTRA_NAME = "name";
147
148 /**
149 * Optional extra to specify an X.509 certificate to install on
150 * the {@code Intent} returned by {@link #createInstallIntent}.
151 * The extra value should be a PEM or ASN.1 DER encoded {@code
152 * byte[]}. An {@link X509Certificate} can be converted to DER
153 * encoded bytes with {@link X509Certificate#getEncoded}.
154 *
155 * <p>{@link #EXTRA_NAME} may be used to provide a default alias
156 * name for the installed certificate.
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700157 */
158 // Compatible with old android.security.Credentials.CERTIFICATE
159 public static final String EXTRA_CERTIFICATE = "CERT";
160
161 /**
162 * Optional extra for use with the {@code Intent} returned by
163 * {@link #createInstallIntent} to specify a PKCS#12 key store to
164 * install. The extra value should be a {@code byte[]}. The bytes
165 * may come from an external source or be generated with {@link
Brian Carlstromca43c452011-06-29 18:53:17 -0700166 * java.security.KeyStore#store} on a "PKCS12" instance.
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700167 *
168 * <p>The user will be prompted for the password to load the key store.
169 *
170 * <p>The key store will be scanned for {@link
171 * java.security.KeyStore.PrivateKeyEntry} entries and both the
172 * private key and associated certificate chain will be installed.
173 *
174 * <p>{@link #EXTRA_NAME} may be used to provide a default alias
175 * name for the installed credentials.
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700176 */
177 // Compatible with old android.security.Credentials.PKCS12
178 public static final String EXTRA_PKCS12 = "PKCS12";
179
Selim Gurun93ba4fe2012-02-14 11:48:49 -0800180
181 /**
Selim Gurun93ba4fe2012-02-14 11:48:49 -0800182 * Broadcast Action: Indicates the trusted storage has changed. Sent when
183 * one of this happens:
184 *
185 * <ul>
186 * <li>a new CA is added,
187 * <li>an existing CA is removed or disabled,
188 * <li>a disabled CA is enabled,
189 * <li>trusted storage is reset (all user certs are cleared),
190 * <li>when permission to access a private key is changed.
191 * </ul>
192 */
193 public static final String ACTION_STORAGE_CHANGED = "android.security.STORAGE_CHANGED";
194
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700195 /**
196 * Returns an {@code Intent} that can be used for credential
197 * installation. The intent may be used without any extras, in
198 * which case the user will be able to install credentials from
199 * their own source.
200 *
201 * <p>Alternatively, {@link #EXTRA_CERTIFICATE} or {@link
202 * #EXTRA_PKCS12} maybe used to specify the bytes of an X.509
203 * certificate or a PKCS#12 key store for installation. These
Brian Carlstromca43c452011-06-29 18:53:17 -0700204 * extras may be combined with {@link #EXTRA_NAME} to provide a
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700205 * default alias name for credentials being installed.
206 *
207 * <p>When used with {@link Activity#startActivityForResult},
208 * {@link Activity#RESULT_OK} will be returned if a credential was
209 * successfully installed, otherwise {@link
210 * Activity#RESULT_CANCELED} will be returned.
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700211 */
Alex Klyubin54bb1592015-05-11 12:30:03 -0700212 @NonNull
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700213 public static Intent createInstallIntent() {
214 Intent intent = new Intent(ACTION_INSTALL);
Kenny Root1a88d832014-02-07 09:12:48 -0800215 intent.setClassName(CERT_INSTALLER_PACKAGE,
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700216 "com.android.certinstaller.CertInstallerMain");
217 return intent;
218 }
219
220 /**
Brian Carlstromba1a6672011-05-24 21:54:37 -0700221 * Launches an {@code Activity} for the user to select the alias
222 * for a private key and certificate pair for authentication. The
223 * selected alias or null will be returned via the
Brian Carlstrom93201f52011-06-09 15:05:35 -0700224 * KeyChainAliasCallback callback.
225 *
Robin Lee3798ed52015-02-03 17:55:31 +0000226 * <p>The device or profile owner can intercept this before the activity
227 * is shown, to pick a specific private key alias.
228 *
229 * <p>{@code keyTypes} and {@code issuers} may be used to
230 * highlight suggested choices to the user, although to cope with
231 * sometimes erroneous values provided by servers, the user may be
232 * able to override these suggestions.
233 *
234 * <p>{@code host} and {@code port} may be used to give the user
235 * more context about the server requesting the credentials.
236 *
237 * <p>{@code alias} allows the chooser to preselect an existing
238 * alias which will still be subject to user confirmation.
239 *
240 * @param activity The {@link Activity} context to use for
241 * launching the new sub-Activity to prompt the user to select
242 * a private key; used only to call startActivity(); must not
243 * be null.
244 * @param response Callback to invoke when the request completes;
245 * must not be null
246 * @param keyTypes The acceptable types of asymmetric keys such as
247 * "RSA" or "DSA", or a null array.
248 * @param issuers The acceptable certificate issuers for the
249 * certificate matching the private key, or null.
250 * @param host The host name of the server requesting the
251 * certificate, or null if unavailable.
252 * @param port The port number of the server requesting the
253 * certificate, or -1 if unavailable.
254 * @param alias The alias to preselect if available, or null if
255 * unavailable.
256 */
Alex Klyubin54bb1592015-05-11 12:30:03 -0700257 public static void choosePrivateKeyAlias(@NonNull Activity activity,
258 @NonNull KeyChainAliasCallback response,
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700259 @KeyProperties.KeyAlgorithmEnum String[] keyTypes, Principal[] issuers,
Alex Klyubin54bb1592015-05-11 12:30:03 -0700260 @Nullable String host, int port, @Nullable String alias) {
Robin Lee39087b12015-05-05 15:57:17 +0100261 Uri uri = null;
262 if (host != null) {
263 uri = new Uri.Builder()
264 .authority(host + (port != -1 ? ":" + port : ""))
265 .build();
266 }
267 choosePrivateKeyAlias(activity, response, keyTypes, issuers, uri, alias);
Robin Lee3798ed52015-02-03 17:55:31 +0000268 }
269
270 /**
271 * Launches an {@code Activity} for the user to select the alias
272 * for a private key and certificate pair for authentication. The
273 * selected alias or null will be returned via the
274 * KeyChainAliasCallback callback.
275 *
276 * <p>The device or profile owner can intercept this before the activity
277 * is shown, to pick a specific private key alias.</p>
278 *
Brian Carlstrom93201f52011-06-09 15:05:35 -0700279 * <p>{@code keyTypes} and {@code issuers} may be used to
280 * highlight suggested choices to the user, although to cope with
281 * sometimes erroneous values provided by servers, the user may be
282 * able to override these suggestions.
283 *
284 * <p>{@code host} and {@code port} may be used to give the user
285 * more context about the server requesting the credentials.
286 *
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700287 * <p>{@code alias} allows the chooser to preselect an existing
288 * alias which will still be subject to user confirmation.
289 *
Brian Carlstrom93201f52011-06-09 15:05:35 -0700290 * @param activity The {@link Activity} context to use for
291 * launching the new sub-Activity to prompt the user to select
292 * a private key; used only to call startActivity(); must not
293 * be null.
294 * @param response Callback to invoke when the request completes;
295 * must not be null
296 * @param keyTypes The acceptable types of asymmetric keys such as
Alex Klyubincd2329d2015-01-14 16:45:51 -0800297 * "EC" or "RSA", or a null array.
Brian Carlstrom93201f52011-06-09 15:05:35 -0700298 * @param issuers The acceptable certificate issuers for the
299 * certificate matching the private key, or null.
Robin Lee39087b12015-05-05 15:57:17 +0100300 * @param uri The full URI the server is requesting the certificate
Robin Lee3798ed52015-02-03 17:55:31 +0000301 * for, or null if unavailable.
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700302 * @param alias The alias to preselect if available, or null if
303 * unavailable.
Brian Carlstromba1a6672011-05-24 21:54:37 -0700304 */
Alex Klyubin54bb1592015-05-11 12:30:03 -0700305 public static void choosePrivateKeyAlias(@NonNull Activity activity,
306 @NonNull KeyChainAliasCallback response,
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700307 @KeyProperties.KeyAlgorithmEnum String[] keyTypes, Principal[] issuers,
Robin Lee39087b12015-05-05 15:57:17 +0100308 @Nullable Uri uri, @Nullable String alias) {
Brian Carlstrom93201f52011-06-09 15:05:35 -0700309 /*
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700310 * TODO currently keyTypes, issuers are unused. They are meant
311 * to follow the semantics and purpose of X509KeyManager
312 * method arguments.
Brian Carlstrom93201f52011-06-09 15:05:35 -0700313 *
314 * keyTypes would allow the list to be filtered and typically
315 * will be set correctly by the server. In practice today,
Alex Klyubincd2329d2015-01-14 16:45:51 -0800316 * most all users will want only RSA or EC, and usually
Brian Carlstrom93201f52011-06-09 15:05:35 -0700317 * only a small number of certs will be available.
318 *
319 * issuers is typically not useful. Some servers historically
320 * will send the entire list of public CAs known to the
321 * server. Others will send none. If this is used, if there
322 * are no matches after applying the constraint, it should be
323 * ignored.
Brian Carlstrom93201f52011-06-09 15:05:35 -0700324 */
Brian Carlstromba1a6672011-05-24 21:54:37 -0700325 if (activity == null) {
326 throw new NullPointerException("activity == null");
327 }
328 if (response == null) {
329 throw new NullPointerException("response == null");
330 }
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700331 Intent intent = new Intent(ACTION_CHOOSER);
Kenny Roota3659062014-03-17 16:21:53 -0700332 intent.setPackage(KEYCHAIN_PACKAGE);
Fred Quintanaab8b84a2011-07-13 14:55:39 -0700333 intent.putExtra(EXTRA_RESPONSE, new AliasResponse(response));
Robin Lee39087b12015-05-05 15:57:17 +0100334 intent.putExtra(EXTRA_URI, uri);
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700335 intent.putExtra(EXTRA_ALIAS, alias);
336 // the PendingIntent is used to get calling package name
337 intent.putExtra(EXTRA_SENDER, PendingIntent.getActivity(activity, 0, new Intent(), 0));
Brian Carlstromba1a6672011-05-24 21:54:37 -0700338 activity.startActivity(intent);
339 }
340
Brian Carlstrom93201f52011-06-09 15:05:35 -0700341 private static class AliasResponse extends IKeyChainAliasCallback.Stub {
Brian Carlstrom93201f52011-06-09 15:05:35 -0700342 private final KeyChainAliasCallback keyChainAliasResponse;
Fred Quintanaab8b84a2011-07-13 14:55:39 -0700343 private AliasResponse(KeyChainAliasCallback keyChainAliasResponse) {
Brian Carlstromba1a6672011-05-24 21:54:37 -0700344 this.keyChainAliasResponse = keyChainAliasResponse;
345 }
346 @Override public void alias(String alias) {
Fred Quintanaab8b84a2011-07-13 14:55:39 -0700347 keyChainAliasResponse.alias(alias);
Brian Carlstromba1a6672011-05-24 21:54:37 -0700348 }
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700349 }
350
351 /**
Brian Carlstromba1a6672011-05-24 21:54:37 -0700352 * Returns the {@code PrivateKey} for the requested alias, or null
353 * if no there is no result.
Brian Carlstrom93201f52011-06-09 15:05:35 -0700354 *
Robin Lee59e3baa2015-06-30 10:48:06 -0700355 * <p> This method may block while waiting for a connection to another process, and must never
356 * be called from the main thread.
357 *
358 * @param alias The alias of the desired private key, typically returned via
359 * {@link KeyChainAliasCallback#alias}.
Brian Carlstrom93201f52011-06-09 15:05:35 -0700360 * @throws KeyChainException if the alias was valid but there was some problem accessing it.
Robin Lee59e3baa2015-06-30 10:48:06 -0700361 * @throws IllegalStateException if called from the main thread.
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700362 */
Robin Lee59e3baa2015-06-30 10:48:06 -0700363 @Nullable @WorkerThread
Alex Klyubin54bb1592015-05-11 12:30:03 -0700364 public static PrivateKey getPrivateKey(@NonNull Context context, @NonNull String alias)
Brian Carlstrom93201f52011-06-09 15:05:35 -0700365 throws KeyChainException, InterruptedException {
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700366 if (alias == null) {
367 throw new NullPointerException("alias == null");
368 }
Brian Carlstromd7524722011-05-17 16:20:36 -0700369 KeyChainConnection keyChainConnection = bind(context);
Brian Carlstrom8e9929c2011-05-17 00:40:28 -0700370 try {
Kenny Root5423e682011-11-14 08:43:13 -0800371 final IKeyChainService keyChainService = keyChainConnection.getService();
372 final String keyId = keyChainService.requestPrivateKey(alias);
373 if (keyId == null) {
374 throw new KeyChainException("keystore had a problem");
375 }
Alex Klyubin4a0ff7c2015-06-09 13:25:20 -0700376 return AndroidKeyStoreProvider.loadAndroidKeyStorePrivateKeyFromKeystore(
377 KeyStore.getInstance(), keyId);
Brian Carlstrom93201f52011-06-09 15:05:35 -0700378 } catch (RemoteException e) {
379 throw new KeyChainException(e);
380 } catch (RuntimeException e) {
381 // only certain RuntimeExceptions can be propagated across the IKeyChainService call
382 throw new KeyChainException(e);
Alex Klyubin4a0ff7c2015-06-09 13:25:20 -0700383 } catch (UnrecoverableKeyException e) {
Kenny Root5423e682011-11-14 08:43:13 -0800384 throw new KeyChainException(e);
Brian Carlstromba1a6672011-05-24 21:54:37 -0700385 } finally {
386 keyChainConnection.close();
387 }
388 }
389
390 /**
391 * Returns the {@code X509Certificate} chain for the requested
392 * alias, or null if no there is no result.
Brian Carlstrom93201f52011-06-09 15:05:35 -0700393 *
Robin Lee59e3baa2015-06-30 10:48:06 -0700394 * <p> This method may block while waiting for a connection to another process, and must never
395 * be called from the main thread.
396 *
Brian Carlstrom93201f52011-06-09 15:05:35 -0700397 * @param alias The alias of the desired certificate chain, typically
398 * returned via {@link KeyChainAliasCallback#alias}.
399 * @throws KeyChainException if the alias was valid but there was some problem accessing it.
Robin Lee59e3baa2015-06-30 10:48:06 -0700400 * @throws IllegalStateException if called from the main thread.
Brian Carlstromba1a6672011-05-24 21:54:37 -0700401 */
Robin Lee59e3baa2015-06-30 10:48:06 -0700402 @Nullable @WorkerThread
Alex Klyubin54bb1592015-05-11 12:30:03 -0700403 public static X509Certificate[] getCertificateChain(@NonNull Context context,
404 @NonNull String alias) throws KeyChainException, InterruptedException {
Brian Carlstromba1a6672011-05-24 21:54:37 -0700405 if (alias == null) {
406 throw new NullPointerException("alias == null");
407 }
408 KeyChainConnection keyChainConnection = bind(context);
409 try {
Brian Carlstromba1a6672011-05-24 21:54:37 -0700410 IKeyChainService keyChainService = keyChainConnection.getService();
Kenny Root0150e482013-02-13 15:22:50 -0800411
412 final byte[] certificateBytes = keyChainService.getCertificate(alias);
413 if (certificateBytes == null) {
414 return null;
415 }
416
Brian Carlstromdb93b782011-07-01 00:12:17 -0700417 TrustedCertificateStore store = new TrustedCertificateStore();
Kenny Root54e03af2012-08-07 10:04:26 -0700418 List<X509Certificate> chain = store
419 .getCertificateChain(toCertificate(certificateBytes));
Brian Carlstromdb93b782011-07-01 00:12:17 -0700420 return chain.toArray(new X509Certificate[chain.size()]);
Kenny Rootcfba6a02013-05-06 15:00:58 -0700421 } catch (CertificateException e) {
422 throw new KeyChainException(e);
Brian Carlstrom93201f52011-06-09 15:05:35 -0700423 } catch (RemoteException e) {
424 throw new KeyChainException(e);
425 } catch (RuntimeException e) {
426 // only certain RuntimeExceptions can be propagated across the IKeyChainService call
427 throw new KeyChainException(e);
Brian Carlstrom8e9929c2011-05-17 00:40:28 -0700428 } finally {
Brian Carlstromd7524722011-05-17 16:20:36 -0700429 keyChainConnection.close();
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700430 }
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700431 }
432
Kenny Rootbf556ac2013-04-01 15:10:22 -0700433 /**
434 * Returns {@code true} if the current device's {@code KeyChain} supports a
435 * specific {@code PrivateKey} type indicated by {@code algorithm} (e.g.,
436 * "RSA").
437 */
Alex Klyubin4d5443f2015-05-06 15:43:52 -0700438 public static boolean isKeyAlgorithmSupported(
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700439 @NonNull @KeyProperties.KeyAlgorithmEnum String algorithm) {
Kenny Rootb91773b2013-09-05 13:03:16 -0700440 final String algUpper = algorithm.toUpperCase(Locale.US);
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700441 return KeyProperties.KEY_ALGORITHM_EC.equals(algUpper)
442 || KeyProperties.KEY_ALGORITHM_RSA.equals(algUpper);
Kenny Rootbf556ac2013-04-01 15:10:22 -0700443 }
444
445 /**
446 * Returns {@code true} if the current device's {@code KeyChain} binds any
447 * {@code PrivateKey} of the given {@code algorithm} to the device once
448 * imported or generated. This can be used to tell if there is special
449 * hardware support that can be used to bind keys to the device in a way
450 * that makes it non-exportable.
Alex Klyubin469cbf52015-06-04 12:36:27 -0700451 *
452 * @deprecated Whether the key is bound to the secure hardware is known only
453 * once the key has been imported. To find out, use:
454 * <pre>{@code
455 * PrivateKey key = ...; // private key from KeyChain
456 *
457 * KeyFactory keyFactory =
458 * KeyFactory.getInstance(key.getAlgorithm(), "AndroidKeyStore");
459 * KeyInfo keyInfo = keyFactory.getKeySpec(key, KeyInfo.class);
460 * if (keyInfo.isInsideSecureHardware()) &#123;
461 * // The key is bound to the secure hardware of this Android
462 * &#125;}</pre>
Kenny Rootbf556ac2013-04-01 15:10:22 -0700463 */
Alex Klyubin469cbf52015-06-04 12:36:27 -0700464 @Deprecated
Alex Klyubin4d5443f2015-05-06 15:43:52 -0700465 public static boolean isBoundKeyAlgorithm(
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700466 @NonNull @KeyProperties.KeyAlgorithmEnum String algorithm) {
Kenny Root5b7e90a2013-04-02 11:23:41 -0700467 if (!isKeyAlgorithmSupported(algorithm)) {
Kenny Rootbf556ac2013-04-01 15:10:22 -0700468 return false;
469 }
470
Kenny Rootb91773b2013-09-05 13:03:16 -0700471 return KeyStore.getInstance().isHardwareBacked(algorithm);
Kenny Rootbf556ac2013-04-01 15:10:22 -0700472 }
473
Zoltan Szatmary-Banf0ae1352014-08-18 10:48:33 +0100474 /** @hide */
Alex Klyubin54bb1592015-05-11 12:30:03 -0700475 @NonNull
476 public static X509Certificate toCertificate(@NonNull byte[] bytes) {
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700477 if (bytes == null) {
Brian Carlstrom8e9929c2011-05-17 00:40:28 -0700478 throw new IllegalArgumentException("bytes == null");
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700479 }
480 try {
481 CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
482 Certificate cert = certFactory.generateCertificate(new ByteArrayInputStream(bytes));
483 return (X509Certificate) cert;
484 } catch (CertificateException e) {
485 throw new AssertionError(e);
486 }
487 }
488
Brian Carlstromd7524722011-05-17 16:20:36 -0700489 /**
490 * @hide for reuse by CertInstaller and Settings.
491 * @see KeyChain#bind
492 */
493 public final static class KeyChainConnection implements Closeable {
494 private final Context context;
495 private final ServiceConnection serviceConnection;
496 private final IKeyChainService service;
497 private KeyChainConnection(Context context,
498 ServiceConnection serviceConnection,
499 IKeyChainService service) {
500 this.context = context;
501 this.serviceConnection = serviceConnection;
502 this.service = service;
503 }
504 @Override public void close() {
505 context.unbindService(serviceConnection);
506 }
507 public IKeyChainService getService() {
508 return service;
509 }
510 }
511
512 /**
513 * @hide for reuse by CertInstaller and Settings.
514 *
515 * Caller should call unbindService on the result when finished.
516 */
Robin Lee59e3baa2015-06-30 10:48:06 -0700517 @WorkerThread
Alex Klyubin54bb1592015-05-11 12:30:03 -0700518 public static KeyChainConnection bind(@NonNull Context context) throws InterruptedException {
Robin Lee306fe082014-06-19 14:04:24 +0000519 return bindAsUser(context, Process.myUserHandle());
520 }
521
522 /**
523 * @hide
524 */
Robin Lee59e3baa2015-06-30 10:48:06 -0700525 @WorkerThread
Alex Klyubin54bb1592015-05-11 12:30:03 -0700526 public static KeyChainConnection bindAsUser(@NonNull Context context, UserHandle user)
Robin Lee306fe082014-06-19 14:04:24 +0000527 throws InterruptedException {
Brian Carlstromd7524722011-05-17 16:20:36 -0700528 if (context == null) {
529 throw new NullPointerException("context == null");
530 }
531 ensureNotOnMainThread(context);
532 final BlockingQueue<IKeyChainService> q = new LinkedBlockingQueue<IKeyChainService>(1);
533 ServiceConnection keyChainServiceConnection = new ServiceConnection() {
Fred Quintanaab8b84a2011-07-13 14:55:39 -0700534 volatile boolean mConnectedAtLeastOnce = false;
Brian Carlstromd7524722011-05-17 16:20:36 -0700535 @Override public void onServiceConnected(ComponentName name, IBinder service) {
Fred Quintanaab8b84a2011-07-13 14:55:39 -0700536 if (!mConnectedAtLeastOnce) {
537 mConnectedAtLeastOnce = true;
538 try {
539 q.put(IKeyChainService.Stub.asInterface(service));
540 } catch (InterruptedException e) {
541 // will never happen, since the queue starts with one available slot
542 }
Brian Carlstromd7524722011-05-17 16:20:36 -0700543 }
544 }
545 @Override public void onServiceDisconnected(ComponentName name) {}
546 };
Maggie Benthallda51e682013-08-08 22:35:44 -0400547 Intent intent = new Intent(IKeyChainService.class.getName());
548 ComponentName comp = intent.resolveSystemService(context.getPackageManager(), 0);
549 intent.setComponent(comp);
Robin Lee306fe082014-06-19 14:04:24 +0000550 boolean isBound = context.bindServiceAsUser(intent,
551 keyChainServiceConnection,
552 Context.BIND_AUTO_CREATE,
553 user);
Brian Carlstromd7524722011-05-17 16:20:36 -0700554 if (!isBound) {
555 throw new AssertionError("could not bind to KeyChainService");
556 }
557 return new KeyChainConnection(context, keyChainServiceConnection, q.take());
558 }
559
Alex Klyubin54bb1592015-05-11 12:30:03 -0700560 private static void ensureNotOnMainThread(@NonNull Context context) {
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700561 Looper looper = Looper.myLooper();
Brian Carlstrom8e9929c2011-05-17 00:40:28 -0700562 if (looper != null && looper == context.getMainLooper()) {
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700563 throw new IllegalStateException(
564 "calling this from your main thread can lead to deadlock");
565 }
566 }
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700567}