blob: 3853ecad12e1d98e28575421df1e037dfad741c0 [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;
Brian Carlstromba1a6672011-05-24 21:54:37 -070020import android.app.Activity;
Brian Carlstrom67c30df2011-06-24 02:13:23 -070021import android.app.PendingIntent;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070022import android.content.ComponentName;
23import android.content.Context;
24import android.content.Intent;
25import android.content.ServiceConnection;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070026import android.os.IBinder;
27import android.os.Looper;
Robin Lee306fe082014-06-19 14:04:24 +000028import android.os.Process;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070029import android.os.RemoteException;
Robin Lee306fe082014-06-19 14:04:24 +000030import android.os.UserHandle;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070031import java.io.ByteArrayInputStream;
Brian Carlstromd7524722011-05-17 16:20:36 -070032import java.io.Closeable;
Kenny Root5423e682011-11-14 08:43:13 -080033import java.security.InvalidKeyException;
Brian Carlstrom93201f52011-06-09 15:05:35 -070034import java.security.Principal;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070035import java.security.PrivateKey;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070036import java.security.cert.Certificate;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070037import java.security.cert.CertificateException;
38import java.security.cert.CertificateFactory;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070039import java.security.cert.X509Certificate;
Brian Carlstromdb93b782011-07-01 00:12:17 -070040import java.util.List;
Kenny Rootb91773b2013-09-05 13:03:16 -070041import java.util.Locale;
Brian Carlstrom8e9929c2011-05-17 00:40:28 -070042import java.util.concurrent.BlockingQueue;
43import java.util.concurrent.LinkedBlockingQueue;
Kenny Root5423e682011-11-14 08:43:13 -080044
Kenny Root12e75222013-04-23 22:34:24 -070045import com.android.org.conscrypt.OpenSSLEngine;
46import com.android.org.conscrypt.TrustedCertificateStore;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070047
48/**
Brian Carlstrom93201f52011-06-09 15:05:35 -070049 * The {@code KeyChain} class provides access to private keys and
50 * their corresponding certificate chains in credential storage.
51 *
52 * <p>Applications accessing the {@code KeyChain} normally go through
53 * these steps:
54 *
55 * <ol>
56 *
57 * <li>Receive a callback from an {@link javax.net.ssl.X509KeyManager
58 * X509KeyManager} that a private key is requested.
59 *
60 * <li>Call {@link #choosePrivateKeyAlias
61 * choosePrivateKeyAlias} to allow the user to select from a
62 * list of currently available private keys and corresponding
63 * certificate chains. The chosen alias will be returned by the
64 * callback {@link KeyChainAliasCallback#alias}, or null if no private
65 * key is available or the user cancels the request.
66 *
67 * <li>Call {@link #getPrivateKey} and {@link #getCertificateChain} to
68 * retrieve the credentials to return to the corresponding {@link
69 * javax.net.ssl.X509KeyManager} callbacks.
70 *
71 * </ol>
72 *
73 * <p>An application may remember the value of a selected alias to
74 * avoid prompting the user with {@link #choosePrivateKeyAlias
75 * choosePrivateKeyAlias} on subsequent connections. If the alias is
76 * no longer valid, null will be returned on lookups using that value
Brian Carlstromca43c452011-06-29 18:53:17 -070077 *
78 * <p>An application can request the installation of private keys and
79 * certificates via the {@code Intent} provided by {@link
80 * #createInstallIntent}. Private keys installed via this {@code
81 * Intent} will be accessible via {@link #choosePrivateKeyAlias} while
82 * Certificate Authority (CA) certificates will be trusted by all
83 * applications through the default {@code X509TrustManager}.
Brian Carlstromb9a07c12011-04-11 09:03:51 -070084 */
Brian Carlstrom93201f52011-06-09 15:05:35 -070085// TODO reference intent for credential installation when public
Brian Carlstromb9a07c12011-04-11 09:03:51 -070086public final class KeyChain {
87
88 private static final String TAG = "KeyChain";
89
90 /**
91 * @hide Also used by KeyChainService implementation
92 */
93 public static final String ACCOUNT_TYPE = "com.android.keychain";
94
95 /**
Kenny Roota3659062014-03-17 16:21:53 -070096 * Package name for KeyChain chooser.
97 */
98 private static final String KEYCHAIN_PACKAGE = "com.android.keychain";
99
100 /**
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700101 * Action to bring up the KeyChainActivity
102 */
103 private static final String ACTION_CHOOSER = "com.android.keychain.CHOOSER";
104
105 /**
Kenny Root1a88d832014-02-07 09:12:48 -0800106 * Package name for the Certificate Installer.
107 */
108 private static final String CERT_INSTALLER_PACKAGE = "com.android.certinstaller";
109
110 /**
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700111 * Extra for use with {@link #ACTION_CHOOSER}
Brian Carlstromba1a6672011-05-24 21:54:37 -0700112 * @hide Also used by KeyChainActivity implementation
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700113 */
Brian Carlstromba1a6672011-05-24 21:54:37 -0700114 public static final String EXTRA_RESPONSE = "response";
115
116 /**
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700117 * Extra for use with {@link #ACTION_CHOOSER}
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700118 * @hide Also used by KeyChainActivity implementation
119 */
120 public static final String EXTRA_HOST = "host";
121
122 /**
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700123 * Extra for use with {@link #ACTION_CHOOSER}
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700124 * @hide Also used by KeyChainActivity implementation
125 */
126 public static final String EXTRA_PORT = "port";
127
128 /**
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700129 * Extra for use with {@link #ACTION_CHOOSER}
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700130 * @hide Also used by KeyChainActivity implementation
131 */
Robin Lee3798ed52015-02-03 17:55:31 +0000132 public static final String EXTRA_URL = "url";
133
134 /**
135 * Extra for use with {@link #ACTION_CHOOSER}
136 * @hide Also used by KeyChainActivity implementation
137 */
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700138 public static final String EXTRA_ALIAS = "alias";
139
140 /**
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700141 * Extra for use with {@link #ACTION_CHOOSER}
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700142 * @hide Also used by KeyChainActivity implementation
143 */
144 public static final String EXTRA_SENDER = "sender";
145
146 /**
Selim Gurun93ba4fe2012-02-14 11:48:49 -0800147 * Action to bring up the CertInstaller.
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700148 */
149 private static final String ACTION_INSTALL = "android.credentials.INSTALL";
150
151 /**
152 * Optional extra to specify a {@code String} credential name on
153 * the {@code Intent} returned by {@link #createInstallIntent}.
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700154 */
155 // Compatible with old com.android.certinstaller.CredentialHelper.CERT_NAME_KEY
156 public static final String EXTRA_NAME = "name";
157
158 /**
159 * Optional extra to specify an X.509 certificate to install on
160 * the {@code Intent} returned by {@link #createInstallIntent}.
161 * The extra value should be a PEM or ASN.1 DER encoded {@code
162 * byte[]}. An {@link X509Certificate} can be converted to DER
163 * encoded bytes with {@link X509Certificate#getEncoded}.
164 *
165 * <p>{@link #EXTRA_NAME} may be used to provide a default alias
166 * name for the installed certificate.
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700167 */
168 // Compatible with old android.security.Credentials.CERTIFICATE
169 public static final String EXTRA_CERTIFICATE = "CERT";
170
171 /**
172 * Optional extra for use with the {@code Intent} returned by
173 * {@link #createInstallIntent} to specify a PKCS#12 key store to
174 * install. The extra value should be a {@code byte[]}. The bytes
175 * may come from an external source or be generated with {@link
Brian Carlstromca43c452011-06-29 18:53:17 -0700176 * java.security.KeyStore#store} on a "PKCS12" instance.
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700177 *
178 * <p>The user will be prompted for the password to load the key store.
179 *
180 * <p>The key store will be scanned for {@link
181 * java.security.KeyStore.PrivateKeyEntry} entries and both the
182 * private key and associated certificate chain will be installed.
183 *
184 * <p>{@link #EXTRA_NAME} may be used to provide a default alias
185 * name for the installed credentials.
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700186 */
187 // Compatible with old android.security.Credentials.PKCS12
188 public static final String EXTRA_PKCS12 = "PKCS12";
189
Selim Gurun93ba4fe2012-02-14 11:48:49 -0800190
191 /**
Selim Gurun93ba4fe2012-02-14 11:48:49 -0800192 * Broadcast Action: Indicates the trusted storage has changed. Sent when
193 * one of this happens:
194 *
195 * <ul>
196 * <li>a new CA is added,
197 * <li>an existing CA is removed or disabled,
198 * <li>a disabled CA is enabled,
199 * <li>trusted storage is reset (all user certs are cleared),
200 * <li>when permission to access a private key is changed.
201 * </ul>
202 */
203 public static final String ACTION_STORAGE_CHANGED = "android.security.STORAGE_CHANGED";
204
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700205 /**
206 * Returns an {@code Intent} that can be used for credential
207 * installation. The intent may be used without any extras, in
208 * which case the user will be able to install credentials from
209 * their own source.
210 *
211 * <p>Alternatively, {@link #EXTRA_CERTIFICATE} or {@link
212 * #EXTRA_PKCS12} maybe used to specify the bytes of an X.509
213 * certificate or a PKCS#12 key store for installation. These
Brian Carlstromca43c452011-06-29 18:53:17 -0700214 * extras may be combined with {@link #EXTRA_NAME} to provide a
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700215 * default alias name for credentials being installed.
216 *
217 * <p>When used with {@link Activity#startActivityForResult},
218 * {@link Activity#RESULT_OK} will be returned if a credential was
219 * successfully installed, otherwise {@link
220 * Activity#RESULT_CANCELED} will be returned.
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700221 */
Alex Klyubin54bb1592015-05-11 12:30:03 -0700222 @NonNull
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700223 public static Intent createInstallIntent() {
224 Intent intent = new Intent(ACTION_INSTALL);
Kenny Root1a88d832014-02-07 09:12:48 -0800225 intent.setClassName(CERT_INSTALLER_PACKAGE,
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700226 "com.android.certinstaller.CertInstallerMain");
227 return intent;
228 }
229
230 /**
Brian Carlstromba1a6672011-05-24 21:54:37 -0700231 * Launches an {@code Activity} for the user to select the alias
232 * for a private key and certificate pair for authentication. The
233 * selected alias or null will be returned via the
Brian Carlstrom93201f52011-06-09 15:05:35 -0700234 * KeyChainAliasCallback callback.
235 *
Robin Lee3798ed52015-02-03 17:55:31 +0000236 * <p>The device or profile owner can intercept this before the activity
237 * is shown, to pick a specific private key alias.
238 *
239 * <p>{@code keyTypes} and {@code issuers} may be used to
240 * highlight suggested choices to the user, although to cope with
241 * sometimes erroneous values provided by servers, the user may be
242 * able to override these suggestions.
243 *
244 * <p>{@code host} and {@code port} may be used to give the user
245 * more context about the server requesting the credentials.
246 *
247 * <p>{@code alias} allows the chooser to preselect an existing
248 * alias which will still be subject to user confirmation.
249 *
250 * @param activity The {@link Activity} context to use for
251 * launching the new sub-Activity to prompt the user to select
252 * a private key; used only to call startActivity(); must not
253 * be null.
254 * @param response Callback to invoke when the request completes;
255 * must not be null
256 * @param keyTypes The acceptable types of asymmetric keys such as
257 * "RSA" or "DSA", or a null array.
258 * @param issuers The acceptable certificate issuers for the
259 * certificate matching the private key, or null.
260 * @param host The host name of the server requesting the
261 * certificate, or null if unavailable.
262 * @param port The port number of the server requesting the
263 * certificate, or -1 if unavailable.
264 * @param alias The alias to preselect if available, or null if
265 * unavailable.
266 */
Alex Klyubin54bb1592015-05-11 12:30:03 -0700267 public static void choosePrivateKeyAlias(@NonNull Activity activity,
268 @NonNull KeyChainAliasCallback response,
Alex Klyubin622fd932015-05-12 12:53:23 -0700269 @KeyStoreKeyProperties.KeyAlgorithmEnum String[] keyTypes, Principal[] issuers,
Alex Klyubin54bb1592015-05-11 12:30:03 -0700270 @Nullable String host, int port, @Nullable String alias) {
Robin Lee3798ed52015-02-03 17:55:31 +0000271 choosePrivateKeyAlias(activity, response, keyTypes, issuers, host, port, null, alias);
272 }
273
274 /**
275 * Launches an {@code Activity} for the user to select the alias
276 * for a private key and certificate pair for authentication. The
277 * selected alias or null will be returned via the
278 * KeyChainAliasCallback callback.
279 *
280 * <p>The device or profile owner can intercept this before the activity
281 * is shown, to pick a specific private key alias.</p>
282 *
Brian Carlstrom93201f52011-06-09 15:05:35 -0700283 * <p>{@code keyTypes} and {@code issuers} may be used to
284 * highlight suggested choices to the user, although to cope with
285 * sometimes erroneous values provided by servers, the user may be
286 * able to override these suggestions.
287 *
288 * <p>{@code host} and {@code port} may be used to give the user
289 * more context about the server requesting the credentials.
290 *
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700291 * <p>{@code alias} allows the chooser to preselect an existing
292 * alias which will still be subject to user confirmation.
293 *
Brian Carlstrom93201f52011-06-09 15:05:35 -0700294 * @param activity The {@link Activity} context to use for
295 * launching the new sub-Activity to prompt the user to select
296 * a private key; used only to call startActivity(); must not
297 * be null.
298 * @param response Callback to invoke when the request completes;
299 * must not be null
300 * @param keyTypes The acceptable types of asymmetric keys such as
Alex Klyubincd2329d2015-01-14 16:45:51 -0800301 * "EC" or "RSA", or a null array.
Brian Carlstrom93201f52011-06-09 15:05:35 -0700302 * @param issuers The acceptable certificate issuers for the
303 * certificate matching the private key, or null.
304 * @param host The host name of the server requesting the
305 * certificate, or null if unavailable.
306 * @param port The port number of the server requesting the
307 * certificate, or -1 if unavailable.
Robin Lee3798ed52015-02-03 17:55:31 +0000308 * @param url The full url the server is requesting the certificate
309 * for, or null if unavailable.
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700310 * @param alias The alias to preselect if available, or null if
311 * unavailable.
Brian Carlstromba1a6672011-05-24 21:54:37 -0700312 */
Alex Klyubin54bb1592015-05-11 12:30:03 -0700313 public static void choosePrivateKeyAlias(@NonNull Activity activity,
314 @NonNull KeyChainAliasCallback response,
Alex Klyubin622fd932015-05-12 12:53:23 -0700315 @KeyStoreKeyProperties.KeyAlgorithmEnum String[] keyTypes, Principal[] issuers,
Alex Klyubin54bb1592015-05-11 12:30:03 -0700316 @Nullable String host, int port, @Nullable String url, @Nullable String alias) {
Brian Carlstrom93201f52011-06-09 15:05:35 -0700317 /*
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700318 * TODO currently keyTypes, issuers are unused. They are meant
319 * to follow the semantics and purpose of X509KeyManager
320 * method arguments.
Brian Carlstrom93201f52011-06-09 15:05:35 -0700321 *
322 * keyTypes would allow the list to be filtered and typically
323 * will be set correctly by the server. In practice today,
Alex Klyubincd2329d2015-01-14 16:45:51 -0800324 * most all users will want only RSA or EC, and usually
Brian Carlstrom93201f52011-06-09 15:05:35 -0700325 * only a small number of certs will be available.
326 *
327 * issuers is typically not useful. Some servers historically
328 * will send the entire list of public CAs known to the
329 * server. Others will send none. If this is used, if there
330 * are no matches after applying the constraint, it should be
331 * ignored.
Brian Carlstrom93201f52011-06-09 15:05:35 -0700332 */
Brian Carlstromba1a6672011-05-24 21:54:37 -0700333 if (activity == null) {
334 throw new NullPointerException("activity == null");
335 }
336 if (response == null) {
337 throw new NullPointerException("response == null");
338 }
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700339 Intent intent = new Intent(ACTION_CHOOSER);
Kenny Roota3659062014-03-17 16:21:53 -0700340 intent.setPackage(KEYCHAIN_PACKAGE);
Fred Quintanaab8b84a2011-07-13 14:55:39 -0700341 intent.putExtra(EXTRA_RESPONSE, new AliasResponse(response));
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700342 intent.putExtra(EXTRA_HOST, host);
343 intent.putExtra(EXTRA_PORT, port);
Robin Lee3798ed52015-02-03 17:55:31 +0000344 intent.putExtra(EXTRA_URL, url);
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700345 intent.putExtra(EXTRA_ALIAS, alias);
346 // the PendingIntent is used to get calling package name
347 intent.putExtra(EXTRA_SENDER, PendingIntent.getActivity(activity, 0, new Intent(), 0));
Brian Carlstromba1a6672011-05-24 21:54:37 -0700348 activity.startActivity(intent);
349 }
350
Brian Carlstrom93201f52011-06-09 15:05:35 -0700351 private static class AliasResponse extends IKeyChainAliasCallback.Stub {
Brian Carlstrom93201f52011-06-09 15:05:35 -0700352 private final KeyChainAliasCallback keyChainAliasResponse;
Fred Quintanaab8b84a2011-07-13 14:55:39 -0700353 private AliasResponse(KeyChainAliasCallback keyChainAliasResponse) {
Brian Carlstromba1a6672011-05-24 21:54:37 -0700354 this.keyChainAliasResponse = keyChainAliasResponse;
355 }
356 @Override public void alias(String alias) {
Fred Quintanaab8b84a2011-07-13 14:55:39 -0700357 keyChainAliasResponse.alias(alias);
Brian Carlstromba1a6672011-05-24 21:54:37 -0700358 }
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700359 }
360
361 /**
Brian Carlstromba1a6672011-05-24 21:54:37 -0700362 * Returns the {@code PrivateKey} for the requested alias, or null
363 * if no there is no result.
Brian Carlstrom93201f52011-06-09 15:05:35 -0700364 *
Brian Carlstrom93201f52011-06-09 15:05:35 -0700365 * @param alias The alias of the desired private key, typically
366 * returned via {@link KeyChainAliasCallback#alias}.
367 * @throws KeyChainException if the alias was valid but there was some problem accessing it.
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700368 */
Alex Klyubin54bb1592015-05-11 12:30:03 -0700369 @Nullable
370 public static PrivateKey getPrivateKey(@NonNull Context context, @NonNull String alias)
Brian Carlstrom93201f52011-06-09 15:05:35 -0700371 throws KeyChainException, InterruptedException {
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700372 if (alias == null) {
373 throw new NullPointerException("alias == null");
374 }
Brian Carlstromd7524722011-05-17 16:20:36 -0700375 KeyChainConnection keyChainConnection = bind(context);
Brian Carlstrom8e9929c2011-05-17 00:40:28 -0700376 try {
Kenny Root5423e682011-11-14 08:43:13 -0800377 final IKeyChainService keyChainService = keyChainConnection.getService();
378 final String keyId = keyChainService.requestPrivateKey(alias);
379 if (keyId == null) {
380 throw new KeyChainException("keystore had a problem");
381 }
382
383 final OpenSSLEngine engine = OpenSSLEngine.getInstance("keystore");
384 return engine.getPrivateKeyById(keyId);
Brian Carlstrom93201f52011-06-09 15:05:35 -0700385 } catch (RemoteException e) {
386 throw new KeyChainException(e);
387 } catch (RuntimeException e) {
388 // only certain RuntimeExceptions can be propagated across the IKeyChainService call
389 throw new KeyChainException(e);
Kenny Root5423e682011-11-14 08:43:13 -0800390 } catch (InvalidKeyException e) {
391 throw new KeyChainException(e);
Brian Carlstromba1a6672011-05-24 21:54:37 -0700392 } finally {
393 keyChainConnection.close();
394 }
395 }
396
397 /**
398 * Returns the {@code X509Certificate} chain for the requested
399 * alias, or null if no there is no result.
Brian Carlstrom93201f52011-06-09 15:05:35 -0700400 *
Brian Carlstrom93201f52011-06-09 15:05:35 -0700401 * @param alias The alias of the desired certificate chain, typically
402 * returned via {@link KeyChainAliasCallback#alias}.
403 * @throws KeyChainException if the alias was valid but there was some problem accessing it.
Brian Carlstromba1a6672011-05-24 21:54:37 -0700404 */
Alex Klyubin54bb1592015-05-11 12:30:03 -0700405 @Nullable
406 public static X509Certificate[] getCertificateChain(@NonNull Context context,
407 @NonNull String alias) throws KeyChainException, InterruptedException {
Brian Carlstromba1a6672011-05-24 21:54:37 -0700408 if (alias == null) {
409 throw new NullPointerException("alias == null");
410 }
411 KeyChainConnection keyChainConnection = bind(context);
412 try {
Brian Carlstromba1a6672011-05-24 21:54:37 -0700413 IKeyChainService keyChainService = keyChainConnection.getService();
Kenny Root0150e482013-02-13 15:22:50 -0800414
415 final byte[] certificateBytes = keyChainService.getCertificate(alias);
416 if (certificateBytes == null) {
417 return null;
418 }
419
Brian Carlstromdb93b782011-07-01 00:12:17 -0700420 TrustedCertificateStore store = new TrustedCertificateStore();
Kenny Root54e03af2012-08-07 10:04:26 -0700421 List<X509Certificate> chain = store
422 .getCertificateChain(toCertificate(certificateBytes));
Brian Carlstromdb93b782011-07-01 00:12:17 -0700423 return chain.toArray(new X509Certificate[chain.size()]);
Kenny Rootcfba6a02013-05-06 15:00:58 -0700424 } catch (CertificateException e) {
425 throw new KeyChainException(e);
Brian Carlstrom93201f52011-06-09 15:05:35 -0700426 } catch (RemoteException e) {
427 throw new KeyChainException(e);
428 } catch (RuntimeException e) {
429 // only certain RuntimeExceptions can be propagated across the IKeyChainService call
430 throw new KeyChainException(e);
Brian Carlstrom8e9929c2011-05-17 00:40:28 -0700431 } finally {
Brian Carlstromd7524722011-05-17 16:20:36 -0700432 keyChainConnection.close();
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700433 }
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700434 }
435
Kenny Rootbf556ac2013-04-01 15:10:22 -0700436 /**
437 * Returns {@code true} if the current device's {@code KeyChain} supports a
438 * specific {@code PrivateKey} type indicated by {@code algorithm} (e.g.,
439 * "RSA").
440 */
Alex Klyubin4d5443f2015-05-06 15:43:52 -0700441 public static boolean isKeyAlgorithmSupported(
Alex Klyubin622fd932015-05-12 12:53:23 -0700442 @NonNull @KeyStoreKeyProperties.KeyAlgorithmEnum String algorithm) {
Kenny Rootb91773b2013-09-05 13:03:16 -0700443 final String algUpper = algorithm.toUpperCase(Locale.US);
Alex Klyubin622fd932015-05-12 12:53:23 -0700444 return KeyStoreKeyProperties.KEY_ALGORITHM_EC.equals(algUpper)
445 || KeyStoreKeyProperties.KEY_ALGORITHM_RSA.equals(algUpper);
Kenny Rootbf556ac2013-04-01 15:10:22 -0700446 }
447
448 /**
449 * Returns {@code true} if the current device's {@code KeyChain} binds any
450 * {@code PrivateKey} of the given {@code algorithm} to the device once
451 * imported or generated. This can be used to tell if there is special
452 * hardware support that can be used to bind keys to the device in a way
453 * that makes it non-exportable.
454 */
Alex Klyubin4d5443f2015-05-06 15:43:52 -0700455 public static boolean isBoundKeyAlgorithm(
Alex Klyubin622fd932015-05-12 12:53:23 -0700456 @NonNull @KeyStoreKeyProperties.KeyAlgorithmEnum String algorithm) {
Kenny Root5b7e90a2013-04-02 11:23:41 -0700457 if (!isKeyAlgorithmSupported(algorithm)) {
Kenny Rootbf556ac2013-04-01 15:10:22 -0700458 return false;
459 }
460
Kenny Rootb91773b2013-09-05 13:03:16 -0700461 return KeyStore.getInstance().isHardwareBacked(algorithm);
Kenny Rootbf556ac2013-04-01 15:10:22 -0700462 }
463
Zoltan Szatmary-Banf0ae1352014-08-18 10:48:33 +0100464 /** @hide */
Alex Klyubin54bb1592015-05-11 12:30:03 -0700465 @NonNull
466 public static X509Certificate toCertificate(@NonNull byte[] bytes) {
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700467 if (bytes == null) {
Brian Carlstrom8e9929c2011-05-17 00:40:28 -0700468 throw new IllegalArgumentException("bytes == null");
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700469 }
470 try {
471 CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
472 Certificate cert = certFactory.generateCertificate(new ByteArrayInputStream(bytes));
473 return (X509Certificate) cert;
474 } catch (CertificateException e) {
475 throw new AssertionError(e);
476 }
477 }
478
Brian Carlstromd7524722011-05-17 16:20:36 -0700479 /**
480 * @hide for reuse by CertInstaller and Settings.
481 * @see KeyChain#bind
482 */
483 public final static class KeyChainConnection implements Closeable {
484 private final Context context;
485 private final ServiceConnection serviceConnection;
486 private final IKeyChainService service;
487 private KeyChainConnection(Context context,
488 ServiceConnection serviceConnection,
489 IKeyChainService service) {
490 this.context = context;
491 this.serviceConnection = serviceConnection;
492 this.service = service;
493 }
494 @Override public void close() {
495 context.unbindService(serviceConnection);
496 }
497 public IKeyChainService getService() {
498 return service;
499 }
500 }
501
502 /**
503 * @hide for reuse by CertInstaller and Settings.
504 *
505 * Caller should call unbindService on the result when finished.
506 */
Alex Klyubin54bb1592015-05-11 12:30:03 -0700507 public static KeyChainConnection bind(@NonNull Context context) throws InterruptedException {
Robin Lee306fe082014-06-19 14:04:24 +0000508 return bindAsUser(context, Process.myUserHandle());
509 }
510
511 /**
512 * @hide
513 */
Alex Klyubin54bb1592015-05-11 12:30:03 -0700514 public static KeyChainConnection bindAsUser(@NonNull Context context, UserHandle user)
Robin Lee306fe082014-06-19 14:04:24 +0000515 throws InterruptedException {
Brian Carlstromd7524722011-05-17 16:20:36 -0700516 if (context == null) {
517 throw new NullPointerException("context == null");
518 }
519 ensureNotOnMainThread(context);
520 final BlockingQueue<IKeyChainService> q = new LinkedBlockingQueue<IKeyChainService>(1);
521 ServiceConnection keyChainServiceConnection = new ServiceConnection() {
Fred Quintanaab8b84a2011-07-13 14:55:39 -0700522 volatile boolean mConnectedAtLeastOnce = false;
Brian Carlstromd7524722011-05-17 16:20:36 -0700523 @Override public void onServiceConnected(ComponentName name, IBinder service) {
Fred Quintanaab8b84a2011-07-13 14:55:39 -0700524 if (!mConnectedAtLeastOnce) {
525 mConnectedAtLeastOnce = true;
526 try {
527 q.put(IKeyChainService.Stub.asInterface(service));
528 } catch (InterruptedException e) {
529 // will never happen, since the queue starts with one available slot
530 }
Brian Carlstromd7524722011-05-17 16:20:36 -0700531 }
532 }
533 @Override public void onServiceDisconnected(ComponentName name) {}
534 };
Maggie Benthallda51e682013-08-08 22:35:44 -0400535 Intent intent = new Intent(IKeyChainService.class.getName());
536 ComponentName comp = intent.resolveSystemService(context.getPackageManager(), 0);
537 intent.setComponent(comp);
Robin Lee306fe082014-06-19 14:04:24 +0000538 boolean isBound = context.bindServiceAsUser(intent,
539 keyChainServiceConnection,
540 Context.BIND_AUTO_CREATE,
541 user);
Brian Carlstromd7524722011-05-17 16:20:36 -0700542 if (!isBound) {
543 throw new AssertionError("could not bind to KeyChainService");
544 }
545 return new KeyChainConnection(context, keyChainServiceConnection, q.take());
546 }
547
Alex Klyubin54bb1592015-05-11 12:30:03 -0700548 private static void ensureNotOnMainThread(@NonNull Context context) {
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700549 Looper looper = Looper.myLooper();
Brian Carlstrom8e9929c2011-05-17 00:40:28 -0700550 if (looper != null && looper == context.getMainLooper()) {
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700551 throw new IllegalStateException(
552 "calling this from your main thread can lead to deadlock");
553 }
554 }
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700555}