blob: 19b62a653e5ba2eaef44e3061614e12f1f861663 [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;
Alex Klyubin3f8d4d82015-05-13 09:15:00 -070031import android.security.keystore.KeyProperties;
32
Brian Carlstromb9a07c12011-04-11 09:03:51 -070033import java.io.ByteArrayInputStream;
Brian Carlstromd7524722011-05-17 16:20:36 -070034import java.io.Closeable;
Kenny Root5423e682011-11-14 08:43:13 -080035import java.security.InvalidKeyException;
Brian Carlstrom93201f52011-06-09 15:05:35 -070036import java.security.Principal;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070037import java.security.PrivateKey;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070038import java.security.cert.Certificate;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070039import java.security.cert.CertificateException;
40import java.security.cert.CertificateFactory;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070041import java.security.cert.X509Certificate;
Brian Carlstromdb93b782011-07-01 00:12:17 -070042import java.util.List;
Kenny Rootb91773b2013-09-05 13:03:16 -070043import java.util.Locale;
Brian Carlstrom8e9929c2011-05-17 00:40:28 -070044import java.util.concurrent.BlockingQueue;
45import java.util.concurrent.LinkedBlockingQueue;
Kenny Root5423e682011-11-14 08:43:13 -080046
Kenny Root12e75222013-04-23 22:34:24 -070047import com.android.org.conscrypt.OpenSSLEngine;
48import com.android.org.conscrypt.TrustedCertificateStore;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070049
50/**
Brian Carlstrom93201f52011-06-09 15:05:35 -070051 * The {@code KeyChain} class provides access to private keys and
52 * their corresponding certificate chains in credential storage.
53 *
54 * <p>Applications accessing the {@code KeyChain} normally go through
55 * these steps:
56 *
57 * <ol>
58 *
59 * <li>Receive a callback from an {@link javax.net.ssl.X509KeyManager
60 * X509KeyManager} that a private key is requested.
61 *
62 * <li>Call {@link #choosePrivateKeyAlias
63 * choosePrivateKeyAlias} to allow the user to select from a
64 * list of currently available private keys and corresponding
65 * certificate chains. The chosen alias will be returned by the
66 * callback {@link KeyChainAliasCallback#alias}, or null if no private
67 * key is available or the user cancels the request.
68 *
69 * <li>Call {@link #getPrivateKey} and {@link #getCertificateChain} to
70 * retrieve the credentials to return to the corresponding {@link
71 * javax.net.ssl.X509KeyManager} callbacks.
72 *
73 * </ol>
74 *
75 * <p>An application may remember the value of a selected alias to
76 * avoid prompting the user with {@link #choosePrivateKeyAlias
77 * choosePrivateKeyAlias} on subsequent connections. If the alias is
78 * no longer valid, null will be returned on lookups using that value
Brian Carlstromca43c452011-06-29 18:53:17 -070079 *
80 * <p>An application can request the installation of private keys and
81 * certificates via the {@code Intent} provided by {@link
82 * #createInstallIntent}. Private keys installed via this {@code
83 * Intent} will be accessible via {@link #choosePrivateKeyAlias} while
84 * Certificate Authority (CA) certificates will be trusted by all
85 * applications through the default {@code X509TrustManager}.
Brian Carlstromb9a07c12011-04-11 09:03:51 -070086 */
Brian Carlstrom93201f52011-06-09 15:05:35 -070087// TODO reference intent for credential installation when public
Brian Carlstromb9a07c12011-04-11 09:03:51 -070088public final class KeyChain {
89
90 private static final String TAG = "KeyChain";
91
92 /**
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 */
122 public static final String EXTRA_HOST = "host";
123
124 /**
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700125 * Extra for use with {@link #ACTION_CHOOSER}
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700126 * @hide Also used by KeyChainActivity implementation
127 */
128 public static final String EXTRA_PORT = "port";
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 */
Robin Lee3798ed52015-02-03 17:55:31 +0000134 public static final String EXTRA_URL = "url";
135
136 /**
137 * Extra for use with {@link #ACTION_CHOOSER}
138 * @hide Also used by KeyChainActivity implementation
139 */
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700140 public static final String EXTRA_ALIAS = "alias";
141
142 /**
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700143 * Extra for use with {@link #ACTION_CHOOSER}
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700144 * @hide Also used by KeyChainActivity implementation
145 */
146 public static final String EXTRA_SENDER = "sender";
147
148 /**
Selim Gurun93ba4fe2012-02-14 11:48:49 -0800149 * Action to bring up the CertInstaller.
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700150 */
151 private static final String ACTION_INSTALL = "android.credentials.INSTALL";
152
153 /**
154 * Optional extra to specify a {@code String} credential name on
155 * the {@code Intent} returned by {@link #createInstallIntent}.
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700156 */
157 // Compatible with old com.android.certinstaller.CredentialHelper.CERT_NAME_KEY
158 public static final String EXTRA_NAME = "name";
159
160 /**
161 * Optional extra to specify an X.509 certificate to install on
162 * the {@code Intent} returned by {@link #createInstallIntent}.
163 * The extra value should be a PEM or ASN.1 DER encoded {@code
164 * byte[]}. An {@link X509Certificate} can be converted to DER
165 * encoded bytes with {@link X509Certificate#getEncoded}.
166 *
167 * <p>{@link #EXTRA_NAME} may be used to provide a default alias
168 * name for the installed certificate.
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700169 */
170 // Compatible with old android.security.Credentials.CERTIFICATE
171 public static final String EXTRA_CERTIFICATE = "CERT";
172
173 /**
174 * Optional extra for use with the {@code Intent} returned by
175 * {@link #createInstallIntent} to specify a PKCS#12 key store to
176 * install. The extra value should be a {@code byte[]}. The bytes
177 * may come from an external source or be generated with {@link
Brian Carlstromca43c452011-06-29 18:53:17 -0700178 * java.security.KeyStore#store} on a "PKCS12" instance.
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700179 *
180 * <p>The user will be prompted for the password to load the key store.
181 *
182 * <p>The key store will be scanned for {@link
183 * java.security.KeyStore.PrivateKeyEntry} entries and both the
184 * private key and associated certificate chain will be installed.
185 *
186 * <p>{@link #EXTRA_NAME} may be used to provide a default alias
187 * name for the installed credentials.
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700188 */
189 // Compatible with old android.security.Credentials.PKCS12
190 public static final String EXTRA_PKCS12 = "PKCS12";
191
Selim Gurun93ba4fe2012-02-14 11:48:49 -0800192
193 /**
Selim Gurun93ba4fe2012-02-14 11:48:49 -0800194 * Broadcast Action: Indicates the trusted storage has changed. Sent when
195 * one of this happens:
196 *
197 * <ul>
198 * <li>a new CA is added,
199 * <li>an existing CA is removed or disabled,
200 * <li>a disabled CA is enabled,
201 * <li>trusted storage is reset (all user certs are cleared),
202 * <li>when permission to access a private key is changed.
203 * </ul>
204 */
205 public static final String ACTION_STORAGE_CHANGED = "android.security.STORAGE_CHANGED";
206
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700207 /**
208 * Returns an {@code Intent} that can be used for credential
209 * installation. The intent may be used without any extras, in
210 * which case the user will be able to install credentials from
211 * their own source.
212 *
213 * <p>Alternatively, {@link #EXTRA_CERTIFICATE} or {@link
214 * #EXTRA_PKCS12} maybe used to specify the bytes of an X.509
215 * certificate or a PKCS#12 key store for installation. These
Brian Carlstromca43c452011-06-29 18:53:17 -0700216 * extras may be combined with {@link #EXTRA_NAME} to provide a
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700217 * default alias name for credentials being installed.
218 *
219 * <p>When used with {@link Activity#startActivityForResult},
220 * {@link Activity#RESULT_OK} will be returned if a credential was
221 * successfully installed, otherwise {@link
222 * Activity#RESULT_CANCELED} will be returned.
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700223 */
Alex Klyubin54bb1592015-05-11 12:30:03 -0700224 @NonNull
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700225 public static Intent createInstallIntent() {
226 Intent intent = new Intent(ACTION_INSTALL);
Kenny Root1a88d832014-02-07 09:12:48 -0800227 intent.setClassName(CERT_INSTALLER_PACKAGE,
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700228 "com.android.certinstaller.CertInstallerMain");
229 return intent;
230 }
231
232 /**
Brian Carlstromba1a6672011-05-24 21:54:37 -0700233 * Launches an {@code Activity} for the user to select the alias
234 * for a private key and certificate pair for authentication. The
235 * selected alias or null will be returned via the
Brian Carlstrom93201f52011-06-09 15:05:35 -0700236 * KeyChainAliasCallback callback.
237 *
Robin Lee3798ed52015-02-03 17:55:31 +0000238 * <p>The device or profile owner can intercept this before the activity
239 * is shown, to pick a specific private key alias.
240 *
241 * <p>{@code keyTypes} and {@code issuers} may be used to
242 * highlight suggested choices to the user, although to cope with
243 * sometimes erroneous values provided by servers, the user may be
244 * able to override these suggestions.
245 *
246 * <p>{@code host} and {@code port} may be used to give the user
247 * more context about the server requesting the credentials.
248 *
249 * <p>{@code alias} allows the chooser to preselect an existing
250 * alias which will still be subject to user confirmation.
251 *
252 * @param activity The {@link Activity} context to use for
253 * launching the new sub-Activity to prompt the user to select
254 * a private key; used only to call startActivity(); must not
255 * be null.
256 * @param response Callback to invoke when the request completes;
257 * must not be null
258 * @param keyTypes The acceptable types of asymmetric keys such as
259 * "RSA" or "DSA", or a null array.
260 * @param issuers The acceptable certificate issuers for the
261 * certificate matching the private key, or null.
262 * @param host The host name of the server requesting the
263 * certificate, or null if unavailable.
264 * @param port The port number of the server requesting the
265 * certificate, or -1 if unavailable.
266 * @param alias The alias to preselect if available, or null if
267 * unavailable.
268 */
Alex Klyubin54bb1592015-05-11 12:30:03 -0700269 public static void choosePrivateKeyAlias(@NonNull Activity activity,
270 @NonNull KeyChainAliasCallback response,
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700271 @KeyProperties.KeyAlgorithmEnum String[] keyTypes, Principal[] issuers,
Alex Klyubin54bb1592015-05-11 12:30:03 -0700272 @Nullable String host, int port, @Nullable String alias) {
Robin Lee3798ed52015-02-03 17:55:31 +0000273 choosePrivateKeyAlias(activity, response, keyTypes, issuers, host, port, null, alias);
274 }
275
276 /**
277 * Launches an {@code Activity} for the user to select the alias
278 * for a private key and certificate pair for authentication. The
279 * selected alias or null will be returned via the
280 * KeyChainAliasCallback callback.
281 *
282 * <p>The device or profile owner can intercept this before the activity
283 * is shown, to pick a specific private key alias.</p>
284 *
Brian Carlstrom93201f52011-06-09 15:05:35 -0700285 * <p>{@code keyTypes} and {@code issuers} may be used to
286 * highlight suggested choices to the user, although to cope with
287 * sometimes erroneous values provided by servers, the user may be
288 * able to override these suggestions.
289 *
290 * <p>{@code host} and {@code port} may be used to give the user
291 * more context about the server requesting the credentials.
292 *
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700293 * <p>{@code alias} allows the chooser to preselect an existing
294 * alias which will still be subject to user confirmation.
295 *
Brian Carlstrom93201f52011-06-09 15:05:35 -0700296 * @param activity The {@link Activity} context to use for
297 * launching the new sub-Activity to prompt the user to select
298 * a private key; used only to call startActivity(); must not
299 * be null.
300 * @param response Callback to invoke when the request completes;
301 * must not be null
302 * @param keyTypes The acceptable types of asymmetric keys such as
Alex Klyubincd2329d2015-01-14 16:45:51 -0800303 * "EC" or "RSA", or a null array.
Brian Carlstrom93201f52011-06-09 15:05:35 -0700304 * @param issuers The acceptable certificate issuers for the
305 * certificate matching the private key, or null.
306 * @param host The host name of the server requesting the
307 * certificate, or null if unavailable.
308 * @param port The port number of the server requesting the
309 * certificate, or -1 if unavailable.
Robin Lee3798ed52015-02-03 17:55:31 +0000310 * @param url The full url the server is requesting the certificate
311 * for, or null if unavailable.
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700312 * @param alias The alias to preselect if available, or null if
313 * unavailable.
Brian Carlstromba1a6672011-05-24 21:54:37 -0700314 */
Alex Klyubin54bb1592015-05-11 12:30:03 -0700315 public static void choosePrivateKeyAlias(@NonNull Activity activity,
316 @NonNull KeyChainAliasCallback response,
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700317 @KeyProperties.KeyAlgorithmEnum String[] keyTypes, Principal[] issuers,
Alex Klyubin54bb1592015-05-11 12:30:03 -0700318 @Nullable String host, int port, @Nullable String url, @Nullable String alias) {
Brian Carlstrom93201f52011-06-09 15:05:35 -0700319 /*
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700320 * TODO currently keyTypes, issuers are unused. They are meant
321 * to follow the semantics and purpose of X509KeyManager
322 * method arguments.
Brian Carlstrom93201f52011-06-09 15:05:35 -0700323 *
324 * keyTypes would allow the list to be filtered and typically
325 * will be set correctly by the server. In practice today,
Alex Klyubincd2329d2015-01-14 16:45:51 -0800326 * most all users will want only RSA or EC, and usually
Brian Carlstrom93201f52011-06-09 15:05:35 -0700327 * only a small number of certs will be available.
328 *
329 * issuers is typically not useful. Some servers historically
330 * will send the entire list of public CAs known to the
331 * server. Others will send none. If this is used, if there
332 * are no matches after applying the constraint, it should be
333 * ignored.
Brian Carlstrom93201f52011-06-09 15:05:35 -0700334 */
Brian Carlstromba1a6672011-05-24 21:54:37 -0700335 if (activity == null) {
336 throw new NullPointerException("activity == null");
337 }
338 if (response == null) {
339 throw new NullPointerException("response == null");
340 }
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700341 Intent intent = new Intent(ACTION_CHOOSER);
Kenny Roota3659062014-03-17 16:21:53 -0700342 intent.setPackage(KEYCHAIN_PACKAGE);
Fred Quintanaab8b84a2011-07-13 14:55:39 -0700343 intent.putExtra(EXTRA_RESPONSE, new AliasResponse(response));
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700344 intent.putExtra(EXTRA_HOST, host);
345 intent.putExtra(EXTRA_PORT, port);
Robin Lee3798ed52015-02-03 17:55:31 +0000346 intent.putExtra(EXTRA_URL, url);
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700347 intent.putExtra(EXTRA_ALIAS, alias);
348 // the PendingIntent is used to get calling package name
349 intent.putExtra(EXTRA_SENDER, PendingIntent.getActivity(activity, 0, new Intent(), 0));
Brian Carlstromba1a6672011-05-24 21:54:37 -0700350 activity.startActivity(intent);
351 }
352
Brian Carlstrom93201f52011-06-09 15:05:35 -0700353 private static class AliasResponse extends IKeyChainAliasCallback.Stub {
Brian Carlstrom93201f52011-06-09 15:05:35 -0700354 private final KeyChainAliasCallback keyChainAliasResponse;
Fred Quintanaab8b84a2011-07-13 14:55:39 -0700355 private AliasResponse(KeyChainAliasCallback keyChainAliasResponse) {
Brian Carlstromba1a6672011-05-24 21:54:37 -0700356 this.keyChainAliasResponse = keyChainAliasResponse;
357 }
358 @Override public void alias(String alias) {
Fred Quintanaab8b84a2011-07-13 14:55:39 -0700359 keyChainAliasResponse.alias(alias);
Brian Carlstromba1a6672011-05-24 21:54:37 -0700360 }
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700361 }
362
363 /**
Brian Carlstromba1a6672011-05-24 21:54:37 -0700364 * Returns the {@code PrivateKey} for the requested alias, or null
365 * if no there is no result.
Brian Carlstrom93201f52011-06-09 15:05:35 -0700366 *
Brian Carlstrom93201f52011-06-09 15:05:35 -0700367 * @param alias The alias of the desired private key, typically
368 * returned via {@link KeyChainAliasCallback#alias}.
369 * @throws KeyChainException if the alias was valid but there was some problem accessing it.
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700370 */
Alex Klyubin54bb1592015-05-11 12:30:03 -0700371 @Nullable
372 public static PrivateKey getPrivateKey(@NonNull Context context, @NonNull String alias)
Brian Carlstrom93201f52011-06-09 15:05:35 -0700373 throws KeyChainException, InterruptedException {
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700374 if (alias == null) {
375 throw new NullPointerException("alias == null");
376 }
Brian Carlstromd7524722011-05-17 16:20:36 -0700377 KeyChainConnection keyChainConnection = bind(context);
Brian Carlstrom8e9929c2011-05-17 00:40:28 -0700378 try {
Kenny Root5423e682011-11-14 08:43:13 -0800379 final IKeyChainService keyChainService = keyChainConnection.getService();
380 final String keyId = keyChainService.requestPrivateKey(alias);
381 if (keyId == null) {
382 throw new KeyChainException("keystore had a problem");
383 }
384
385 final OpenSSLEngine engine = OpenSSLEngine.getInstance("keystore");
386 return engine.getPrivateKeyById(keyId);
Brian Carlstrom93201f52011-06-09 15:05:35 -0700387 } catch (RemoteException e) {
388 throw new KeyChainException(e);
389 } catch (RuntimeException e) {
390 // only certain RuntimeExceptions can be propagated across the IKeyChainService call
391 throw new KeyChainException(e);
Kenny Root5423e682011-11-14 08:43:13 -0800392 } catch (InvalidKeyException e) {
393 throw new KeyChainException(e);
Brian Carlstromba1a6672011-05-24 21:54:37 -0700394 } finally {
395 keyChainConnection.close();
396 }
397 }
398
399 /**
400 * Returns the {@code X509Certificate} chain for the requested
401 * alias, or null if no there is no result.
Brian Carlstrom93201f52011-06-09 15:05:35 -0700402 *
Brian Carlstrom93201f52011-06-09 15:05:35 -0700403 * @param alias The alias of the desired certificate chain, typically
404 * returned via {@link KeyChainAliasCallback#alias}.
405 * @throws KeyChainException if the alias was valid but there was some problem accessing it.
Brian Carlstromba1a6672011-05-24 21:54:37 -0700406 */
Alex Klyubin54bb1592015-05-11 12:30:03 -0700407 @Nullable
408 public static X509Certificate[] getCertificateChain(@NonNull Context context,
409 @NonNull String alias) throws KeyChainException, InterruptedException {
Brian Carlstromba1a6672011-05-24 21:54:37 -0700410 if (alias == null) {
411 throw new NullPointerException("alias == null");
412 }
413 KeyChainConnection keyChainConnection = bind(context);
414 try {
Brian Carlstromba1a6672011-05-24 21:54:37 -0700415 IKeyChainService keyChainService = keyChainConnection.getService();
Kenny Root0150e482013-02-13 15:22:50 -0800416
417 final byte[] certificateBytes = keyChainService.getCertificate(alias);
418 if (certificateBytes == null) {
419 return null;
420 }
421
Brian Carlstromdb93b782011-07-01 00:12:17 -0700422 TrustedCertificateStore store = new TrustedCertificateStore();
Kenny Root54e03af2012-08-07 10:04:26 -0700423 List<X509Certificate> chain = store
424 .getCertificateChain(toCertificate(certificateBytes));
Brian Carlstromdb93b782011-07-01 00:12:17 -0700425 return chain.toArray(new X509Certificate[chain.size()]);
Kenny Rootcfba6a02013-05-06 15:00:58 -0700426 } catch (CertificateException e) {
427 throw new KeyChainException(e);
Brian Carlstrom93201f52011-06-09 15:05:35 -0700428 } catch (RemoteException e) {
429 throw new KeyChainException(e);
430 } catch (RuntimeException e) {
431 // only certain RuntimeExceptions can be propagated across the IKeyChainService call
432 throw new KeyChainException(e);
Brian Carlstrom8e9929c2011-05-17 00:40:28 -0700433 } finally {
Brian Carlstromd7524722011-05-17 16:20:36 -0700434 keyChainConnection.close();
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700435 }
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700436 }
437
Kenny Rootbf556ac2013-04-01 15:10:22 -0700438 /**
439 * Returns {@code true} if the current device's {@code KeyChain} supports a
440 * specific {@code PrivateKey} type indicated by {@code algorithm} (e.g.,
441 * "RSA").
442 */
Alex Klyubin4d5443f2015-05-06 15:43:52 -0700443 public static boolean isKeyAlgorithmSupported(
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700444 @NonNull @KeyProperties.KeyAlgorithmEnum String algorithm) {
Kenny Rootb91773b2013-09-05 13:03:16 -0700445 final String algUpper = algorithm.toUpperCase(Locale.US);
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700446 return KeyProperties.KEY_ALGORITHM_EC.equals(algUpper)
447 || KeyProperties.KEY_ALGORITHM_RSA.equals(algUpper);
Kenny Rootbf556ac2013-04-01 15:10:22 -0700448 }
449
450 /**
451 * Returns {@code true} if the current device's {@code KeyChain} binds any
452 * {@code PrivateKey} of the given {@code algorithm} to the device once
453 * imported or generated. This can be used to tell if there is special
454 * hardware support that can be used to bind keys to the device in a way
455 * that makes it non-exportable.
456 */
Alex Klyubin4d5443f2015-05-06 15:43:52 -0700457 public static boolean isBoundKeyAlgorithm(
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700458 @NonNull @KeyProperties.KeyAlgorithmEnum String algorithm) {
Kenny Root5b7e90a2013-04-02 11:23:41 -0700459 if (!isKeyAlgorithmSupported(algorithm)) {
Kenny Rootbf556ac2013-04-01 15:10:22 -0700460 return false;
461 }
462
Kenny Rootb91773b2013-09-05 13:03:16 -0700463 return KeyStore.getInstance().isHardwareBacked(algorithm);
Kenny Rootbf556ac2013-04-01 15:10:22 -0700464 }
465
Zoltan Szatmary-Banf0ae1352014-08-18 10:48:33 +0100466 /** @hide */
Alex Klyubin54bb1592015-05-11 12:30:03 -0700467 @NonNull
468 public static X509Certificate toCertificate(@NonNull byte[] bytes) {
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700469 if (bytes == null) {
Brian Carlstrom8e9929c2011-05-17 00:40:28 -0700470 throw new IllegalArgumentException("bytes == null");
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700471 }
472 try {
473 CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
474 Certificate cert = certFactory.generateCertificate(new ByteArrayInputStream(bytes));
475 return (X509Certificate) cert;
476 } catch (CertificateException e) {
477 throw new AssertionError(e);
478 }
479 }
480
Brian Carlstromd7524722011-05-17 16:20:36 -0700481 /**
482 * @hide for reuse by CertInstaller and Settings.
483 * @see KeyChain#bind
484 */
485 public final static class KeyChainConnection implements Closeable {
486 private final Context context;
487 private final ServiceConnection serviceConnection;
488 private final IKeyChainService service;
489 private KeyChainConnection(Context context,
490 ServiceConnection serviceConnection,
491 IKeyChainService service) {
492 this.context = context;
493 this.serviceConnection = serviceConnection;
494 this.service = service;
495 }
496 @Override public void close() {
497 context.unbindService(serviceConnection);
498 }
499 public IKeyChainService getService() {
500 return service;
501 }
502 }
503
504 /**
505 * @hide for reuse by CertInstaller and Settings.
506 *
507 * Caller should call unbindService on the result when finished.
508 */
Alex Klyubin54bb1592015-05-11 12:30:03 -0700509 public static KeyChainConnection bind(@NonNull Context context) throws InterruptedException {
Robin Lee306fe082014-06-19 14:04:24 +0000510 return bindAsUser(context, Process.myUserHandle());
511 }
512
513 /**
514 * @hide
515 */
Alex Klyubin54bb1592015-05-11 12:30:03 -0700516 public static KeyChainConnection bindAsUser(@NonNull Context context, UserHandle user)
Robin Lee306fe082014-06-19 14:04:24 +0000517 throws InterruptedException {
Brian Carlstromd7524722011-05-17 16:20:36 -0700518 if (context == null) {
519 throw new NullPointerException("context == null");
520 }
521 ensureNotOnMainThread(context);
522 final BlockingQueue<IKeyChainService> q = new LinkedBlockingQueue<IKeyChainService>(1);
523 ServiceConnection keyChainServiceConnection = new ServiceConnection() {
Fred Quintanaab8b84a2011-07-13 14:55:39 -0700524 volatile boolean mConnectedAtLeastOnce = false;
Brian Carlstromd7524722011-05-17 16:20:36 -0700525 @Override public void onServiceConnected(ComponentName name, IBinder service) {
Fred Quintanaab8b84a2011-07-13 14:55:39 -0700526 if (!mConnectedAtLeastOnce) {
527 mConnectedAtLeastOnce = true;
528 try {
529 q.put(IKeyChainService.Stub.asInterface(service));
530 } catch (InterruptedException e) {
531 // will never happen, since the queue starts with one available slot
532 }
Brian Carlstromd7524722011-05-17 16:20:36 -0700533 }
534 }
535 @Override public void onServiceDisconnected(ComponentName name) {}
536 };
Maggie Benthallda51e682013-08-08 22:35:44 -0400537 Intent intent = new Intent(IKeyChainService.class.getName());
538 ComponentName comp = intent.resolveSystemService(context.getPackageManager(), 0);
539 intent.setComponent(comp);
Robin Lee306fe082014-06-19 14:04:24 +0000540 boolean isBound = context.bindServiceAsUser(intent,
541 keyChainServiceConnection,
542 Context.BIND_AUTO_CREATE,
543 user);
Brian Carlstromd7524722011-05-17 16:20:36 -0700544 if (!isBound) {
545 throw new AssertionError("could not bind to KeyChainService");
546 }
547 return new KeyChainConnection(context, keyChainServiceConnection, q.take());
548 }
549
Alex Klyubin54bb1592015-05-11 12:30:03 -0700550 private static void ensureNotOnMainThread(@NonNull Context context) {
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700551 Looper looper = Looper.myLooper();
Brian Carlstrom8e9929c2011-05-17 00:40:28 -0700552 if (looper != null && looper == context.getMainLooper()) {
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700553 throw new IllegalStateException(
554 "calling this from your main thread can lead to deadlock");
555 }
556 }
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700557}