blob: 817b7c953828415fb4f78e08619d34d008112f25 [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;
Robin Lee39087b12015-05-05 15:57:17 +010026import android.net.Uri;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070027import android.os.IBinder;
28import android.os.Looper;
Robin Lee306fe082014-06-19 14:04:24 +000029import android.os.Process;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070030import android.os.RemoteException;
Robin Lee306fe082014-06-19 14:04:24 +000031import android.os.UserHandle;
Alex Klyubin3f8d4d82015-05-13 09:15:00 -070032import android.security.keystore.KeyProperties;
33
Brian Carlstromb9a07c12011-04-11 09:03:51 -070034import java.io.ByteArrayInputStream;
Brian Carlstromd7524722011-05-17 16:20:36 -070035import java.io.Closeable;
Kenny Root5423e682011-11-14 08:43:13 -080036import java.security.InvalidKeyException;
Brian Carlstrom93201f52011-06-09 15:05:35 -070037import java.security.Principal;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070038import java.security.PrivateKey;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070039import java.security.cert.Certificate;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070040import java.security.cert.CertificateException;
41import java.security.cert.CertificateFactory;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070042import java.security.cert.X509Certificate;
Brian Carlstromdb93b782011-07-01 00:12:17 -070043import java.util.List;
Kenny Rootb91773b2013-09-05 13:03:16 -070044import java.util.Locale;
Brian Carlstrom8e9929c2011-05-17 00:40:28 -070045import java.util.concurrent.BlockingQueue;
46import java.util.concurrent.LinkedBlockingQueue;
Kenny Root5423e682011-11-14 08:43:13 -080047
Kenny Root12e75222013-04-23 22:34:24 -070048import com.android.org.conscrypt.OpenSSLEngine;
49import com.android.org.conscrypt.TrustedCertificateStore;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070050
51/**
Brian Carlstrom93201f52011-06-09 15:05:35 -070052 * The {@code KeyChain} class provides access to private keys and
53 * their corresponding certificate chains in credential storage.
54 *
55 * <p>Applications accessing the {@code KeyChain} normally go through
56 * these steps:
57 *
58 * <ol>
59 *
60 * <li>Receive a callback from an {@link javax.net.ssl.X509KeyManager
61 * X509KeyManager} that a private key is requested.
62 *
63 * <li>Call {@link #choosePrivateKeyAlias
64 * choosePrivateKeyAlias} to allow the user to select from a
65 * list of currently available private keys and corresponding
66 * certificate chains. The chosen alias will be returned by the
67 * callback {@link KeyChainAliasCallback#alias}, or null if no private
68 * key is available or the user cancels the request.
69 *
70 * <li>Call {@link #getPrivateKey} and {@link #getCertificateChain} to
71 * retrieve the credentials to return to the corresponding {@link
72 * javax.net.ssl.X509KeyManager} callbacks.
73 *
74 * </ol>
75 *
76 * <p>An application may remember the value of a selected alias to
77 * avoid prompting the user with {@link #choosePrivateKeyAlias
78 * choosePrivateKeyAlias} on subsequent connections. If the alias is
79 * no longer valid, null will be returned on lookups using that value
Brian Carlstromca43c452011-06-29 18:53:17 -070080 *
81 * <p>An application can request the installation of private keys and
82 * certificates via the {@code Intent} provided by {@link
83 * #createInstallIntent}. Private keys installed via this {@code
84 * Intent} will be accessible via {@link #choosePrivateKeyAlias} while
85 * Certificate Authority (CA) certificates will be trusted by all
86 * applications through the default {@code X509TrustManager}.
Brian Carlstromb9a07c12011-04-11 09:03:51 -070087 */
Brian Carlstrom93201f52011-06-09 15:05:35 -070088// TODO reference intent for credential installation when public
Brian Carlstromb9a07c12011-04-11 09:03:51 -070089public final class KeyChain {
90
91 private static final String TAG = "KeyChain";
92
93 /**
94 * @hide Also used by KeyChainService implementation
95 */
96 public static final String ACCOUNT_TYPE = "com.android.keychain";
97
98 /**
Kenny Roota3659062014-03-17 16:21:53 -070099 * Package name for KeyChain chooser.
100 */
101 private static final String KEYCHAIN_PACKAGE = "com.android.keychain";
102
103 /**
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700104 * Action to bring up the KeyChainActivity
105 */
106 private static final String ACTION_CHOOSER = "com.android.keychain.CHOOSER";
107
108 /**
Kenny Root1a88d832014-02-07 09:12:48 -0800109 * Package name for the Certificate Installer.
110 */
111 private static final String CERT_INSTALLER_PACKAGE = "com.android.certinstaller";
112
113 /**
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700114 * Extra for use with {@link #ACTION_CHOOSER}
Brian Carlstromba1a6672011-05-24 21:54:37 -0700115 * @hide Also used by KeyChainActivity implementation
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700116 */
Brian Carlstromba1a6672011-05-24 21:54:37 -0700117 public static final String EXTRA_RESPONSE = "response";
118
119 /**
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700120 * Extra for use with {@link #ACTION_CHOOSER}
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700121 * @hide Also used by KeyChainActivity implementation
122 */
Robin Lee39087b12015-05-05 15:57:17 +0100123 public static final String EXTRA_URI = "uri";
Robin Lee3798ed52015-02-03 17:55:31 +0000124
125 /**
126 * Extra for use with {@link #ACTION_CHOOSER}
127 * @hide Also used by KeyChainActivity implementation
128 */
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700129 public static final String EXTRA_ALIAS = "alias";
130
131 /**
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700132 * Extra for use with {@link #ACTION_CHOOSER}
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700133 * @hide Also used by KeyChainActivity implementation
134 */
135 public static final String EXTRA_SENDER = "sender";
136
137 /**
Selim Gurun93ba4fe2012-02-14 11:48:49 -0800138 * Action to bring up the CertInstaller.
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700139 */
140 private static final String ACTION_INSTALL = "android.credentials.INSTALL";
141
142 /**
143 * Optional extra to specify a {@code String} credential name on
144 * the {@code Intent} returned by {@link #createInstallIntent}.
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700145 */
146 // Compatible with old com.android.certinstaller.CredentialHelper.CERT_NAME_KEY
147 public static final String EXTRA_NAME = "name";
148
149 /**
150 * Optional extra to specify an X.509 certificate to install on
151 * the {@code Intent} returned by {@link #createInstallIntent}.
152 * The extra value should be a PEM or ASN.1 DER encoded {@code
153 * byte[]}. An {@link X509Certificate} can be converted to DER
154 * encoded bytes with {@link X509Certificate#getEncoded}.
155 *
156 * <p>{@link #EXTRA_NAME} may be used to provide a default alias
157 * name for the installed certificate.
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700158 */
159 // Compatible with old android.security.Credentials.CERTIFICATE
160 public static final String EXTRA_CERTIFICATE = "CERT";
161
162 /**
163 * Optional extra for use with the {@code Intent} returned by
164 * {@link #createInstallIntent} to specify a PKCS#12 key store to
165 * install. The extra value should be a {@code byte[]}. The bytes
166 * may come from an external source or be generated with {@link
Brian Carlstromca43c452011-06-29 18:53:17 -0700167 * java.security.KeyStore#store} on a "PKCS12" instance.
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700168 *
169 * <p>The user will be prompted for the password to load the key store.
170 *
171 * <p>The key store will be scanned for {@link
172 * java.security.KeyStore.PrivateKeyEntry} entries and both the
173 * private key and associated certificate chain will be installed.
174 *
175 * <p>{@link #EXTRA_NAME} may be used to provide a default alias
176 * name for the installed credentials.
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700177 */
178 // Compatible with old android.security.Credentials.PKCS12
179 public static final String EXTRA_PKCS12 = "PKCS12";
180
Selim Gurun93ba4fe2012-02-14 11:48:49 -0800181
182 /**
Selim Gurun93ba4fe2012-02-14 11:48:49 -0800183 * Broadcast Action: Indicates the trusted storage has changed. Sent when
184 * one of this happens:
185 *
186 * <ul>
187 * <li>a new CA is added,
188 * <li>an existing CA is removed or disabled,
189 * <li>a disabled CA is enabled,
190 * <li>trusted storage is reset (all user certs are cleared),
191 * <li>when permission to access a private key is changed.
192 * </ul>
193 */
194 public static final String ACTION_STORAGE_CHANGED = "android.security.STORAGE_CHANGED";
195
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700196 /**
197 * Returns an {@code Intent} that can be used for credential
198 * installation. The intent may be used without any extras, in
199 * which case the user will be able to install credentials from
200 * their own source.
201 *
202 * <p>Alternatively, {@link #EXTRA_CERTIFICATE} or {@link
203 * #EXTRA_PKCS12} maybe used to specify the bytes of an X.509
204 * certificate or a PKCS#12 key store for installation. These
Brian Carlstromca43c452011-06-29 18:53:17 -0700205 * extras may be combined with {@link #EXTRA_NAME} to provide a
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700206 * default alias name for credentials being installed.
207 *
208 * <p>When used with {@link Activity#startActivityForResult},
209 * {@link Activity#RESULT_OK} will be returned if a credential was
210 * successfully installed, otherwise {@link
211 * Activity#RESULT_CANCELED} will be returned.
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700212 */
Alex Klyubin54bb1592015-05-11 12:30:03 -0700213 @NonNull
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700214 public static Intent createInstallIntent() {
215 Intent intent = new Intent(ACTION_INSTALL);
Kenny Root1a88d832014-02-07 09:12:48 -0800216 intent.setClassName(CERT_INSTALLER_PACKAGE,
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700217 "com.android.certinstaller.CertInstallerMain");
218 return intent;
219 }
220
221 /**
Brian Carlstromba1a6672011-05-24 21:54:37 -0700222 * Launches an {@code Activity} for the user to select the alias
223 * for a private key and certificate pair for authentication. The
224 * selected alias or null will be returned via the
Brian Carlstrom93201f52011-06-09 15:05:35 -0700225 * KeyChainAliasCallback callback.
226 *
Robin Lee3798ed52015-02-03 17:55:31 +0000227 * <p>The device or profile owner can intercept this before the activity
228 * is shown, to pick a specific private key alias.
229 *
230 * <p>{@code keyTypes} and {@code issuers} may be used to
231 * highlight suggested choices to the user, although to cope with
232 * sometimes erroneous values provided by servers, the user may be
233 * able to override these suggestions.
234 *
235 * <p>{@code host} and {@code port} may be used to give the user
236 * more context about the server requesting the credentials.
237 *
238 * <p>{@code alias} allows the chooser to preselect an existing
239 * alias which will still be subject to user confirmation.
240 *
241 * @param activity The {@link Activity} context to use for
242 * launching the new sub-Activity to prompt the user to select
243 * a private key; used only to call startActivity(); must not
244 * be null.
245 * @param response Callback to invoke when the request completes;
246 * must not be null
247 * @param keyTypes The acceptable types of asymmetric keys such as
248 * "RSA" or "DSA", or a null array.
249 * @param issuers The acceptable certificate issuers for the
250 * certificate matching the private key, or null.
251 * @param host The host name of the server requesting the
252 * certificate, or null if unavailable.
253 * @param port The port number of the server requesting the
254 * certificate, or -1 if unavailable.
255 * @param alias The alias to preselect if available, or null if
256 * unavailable.
257 */
Alex Klyubin54bb1592015-05-11 12:30:03 -0700258 public static void choosePrivateKeyAlias(@NonNull Activity activity,
259 @NonNull KeyChainAliasCallback response,
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700260 @KeyProperties.KeyAlgorithmEnum String[] keyTypes, Principal[] issuers,
Alex Klyubin54bb1592015-05-11 12:30:03 -0700261 @Nullable String host, int port, @Nullable String alias) {
Robin Lee39087b12015-05-05 15:57:17 +0100262 Uri uri = null;
263 if (host != null) {
264 uri = new Uri.Builder()
265 .authority(host + (port != -1 ? ":" + port : ""))
266 .build();
267 }
268 choosePrivateKeyAlias(activity, response, keyTypes, issuers, uri, alias);
Robin Lee3798ed52015-02-03 17:55:31 +0000269 }
270
271 /**
272 * Launches an {@code Activity} for the user to select the alias
273 * for a private key and certificate pair for authentication. The
274 * selected alias or null will be returned via the
275 * KeyChainAliasCallback callback.
276 *
277 * <p>The device or profile owner can intercept this before the activity
278 * is shown, to pick a specific private key alias.</p>
279 *
Brian Carlstrom93201f52011-06-09 15:05:35 -0700280 * <p>{@code keyTypes} and {@code issuers} may be used to
281 * highlight suggested choices to the user, although to cope with
282 * sometimes erroneous values provided by servers, the user may be
283 * able to override these suggestions.
284 *
285 * <p>{@code host} and {@code port} may be used to give the user
286 * more context about the server requesting the credentials.
287 *
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700288 * <p>{@code alias} allows the chooser to preselect an existing
289 * alias which will still be subject to user confirmation.
290 *
Brian Carlstrom93201f52011-06-09 15:05:35 -0700291 * @param activity The {@link Activity} context to use for
292 * launching the new sub-Activity to prompt the user to select
293 * a private key; used only to call startActivity(); must not
294 * be null.
295 * @param response Callback to invoke when the request completes;
296 * must not be null
297 * @param keyTypes The acceptable types of asymmetric keys such as
Alex Klyubincd2329d2015-01-14 16:45:51 -0800298 * "EC" or "RSA", or a null array.
Brian Carlstrom93201f52011-06-09 15:05:35 -0700299 * @param issuers The acceptable certificate issuers for the
300 * certificate matching the private key, or null.
Robin Lee39087b12015-05-05 15:57:17 +0100301 * @param uri The full URI the server is requesting the certificate
Robin Lee3798ed52015-02-03 17:55:31 +0000302 * for, or null if unavailable.
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700303 * @param alias The alias to preselect if available, or null if
304 * unavailable.
Brian Carlstromba1a6672011-05-24 21:54:37 -0700305 */
Alex Klyubin54bb1592015-05-11 12:30:03 -0700306 public static void choosePrivateKeyAlias(@NonNull Activity activity,
307 @NonNull KeyChainAliasCallback response,
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700308 @KeyProperties.KeyAlgorithmEnum String[] keyTypes, Principal[] issuers,
Robin Lee39087b12015-05-05 15:57:17 +0100309 @Nullable Uri uri, @Nullable String alias) {
Brian Carlstrom93201f52011-06-09 15:05:35 -0700310 /*
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700311 * TODO currently keyTypes, issuers are unused. They are meant
312 * to follow the semantics and purpose of X509KeyManager
313 * method arguments.
Brian Carlstrom93201f52011-06-09 15:05:35 -0700314 *
315 * keyTypes would allow the list to be filtered and typically
316 * will be set correctly by the server. In practice today,
Alex Klyubincd2329d2015-01-14 16:45:51 -0800317 * most all users will want only RSA or EC, and usually
Brian Carlstrom93201f52011-06-09 15:05:35 -0700318 * only a small number of certs will be available.
319 *
320 * issuers is typically not useful. Some servers historically
321 * will send the entire list of public CAs known to the
322 * server. Others will send none. If this is used, if there
323 * are no matches after applying the constraint, it should be
324 * ignored.
Brian Carlstrom93201f52011-06-09 15:05:35 -0700325 */
Brian Carlstromba1a6672011-05-24 21:54:37 -0700326 if (activity == null) {
327 throw new NullPointerException("activity == null");
328 }
329 if (response == null) {
330 throw new NullPointerException("response == null");
331 }
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700332 Intent intent = new Intent(ACTION_CHOOSER);
Kenny Roota3659062014-03-17 16:21:53 -0700333 intent.setPackage(KEYCHAIN_PACKAGE);
Fred Quintanaab8b84a2011-07-13 14:55:39 -0700334 intent.putExtra(EXTRA_RESPONSE, new AliasResponse(response));
Robin Lee39087b12015-05-05 15:57:17 +0100335 intent.putExtra(EXTRA_URI, uri);
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700336 intent.putExtra(EXTRA_ALIAS, alias);
337 // the PendingIntent is used to get calling package name
338 intent.putExtra(EXTRA_SENDER, PendingIntent.getActivity(activity, 0, new Intent(), 0));
Brian Carlstromba1a6672011-05-24 21:54:37 -0700339 activity.startActivity(intent);
340 }
341
Brian Carlstrom93201f52011-06-09 15:05:35 -0700342 private static class AliasResponse extends IKeyChainAliasCallback.Stub {
Brian Carlstrom93201f52011-06-09 15:05:35 -0700343 private final KeyChainAliasCallback keyChainAliasResponse;
Fred Quintanaab8b84a2011-07-13 14:55:39 -0700344 private AliasResponse(KeyChainAliasCallback keyChainAliasResponse) {
Brian Carlstromba1a6672011-05-24 21:54:37 -0700345 this.keyChainAliasResponse = keyChainAliasResponse;
346 }
347 @Override public void alias(String alias) {
Fred Quintanaab8b84a2011-07-13 14:55:39 -0700348 keyChainAliasResponse.alias(alias);
Brian Carlstromba1a6672011-05-24 21:54:37 -0700349 }
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700350 }
351
352 /**
Brian Carlstromba1a6672011-05-24 21:54:37 -0700353 * Returns the {@code PrivateKey} for the requested alias, or null
354 * if no there is no result.
Brian Carlstrom93201f52011-06-09 15:05:35 -0700355 *
Brian Carlstrom93201f52011-06-09 15:05:35 -0700356 * @param alias The alias of the desired private key, typically
357 * returned via {@link KeyChainAliasCallback#alias}.
358 * @throws KeyChainException if the alias was valid but there was some problem accessing it.
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700359 */
Alex Klyubin54bb1592015-05-11 12:30:03 -0700360 @Nullable
361 public static PrivateKey getPrivateKey(@NonNull Context context, @NonNull String alias)
Brian Carlstrom93201f52011-06-09 15:05:35 -0700362 throws KeyChainException, InterruptedException {
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700363 if (alias == null) {
364 throw new NullPointerException("alias == null");
365 }
Brian Carlstromd7524722011-05-17 16:20:36 -0700366 KeyChainConnection keyChainConnection = bind(context);
Brian Carlstrom8e9929c2011-05-17 00:40:28 -0700367 try {
Kenny Root5423e682011-11-14 08:43:13 -0800368 final IKeyChainService keyChainService = keyChainConnection.getService();
369 final String keyId = keyChainService.requestPrivateKey(alias);
370 if (keyId == null) {
371 throw new KeyChainException("keystore had a problem");
372 }
373
374 final OpenSSLEngine engine = OpenSSLEngine.getInstance("keystore");
375 return engine.getPrivateKeyById(keyId);
Brian Carlstrom93201f52011-06-09 15:05:35 -0700376 } catch (RemoteException e) {
377 throw new KeyChainException(e);
378 } catch (RuntimeException e) {
379 // only certain RuntimeExceptions can be propagated across the IKeyChainService call
380 throw new KeyChainException(e);
Kenny Root5423e682011-11-14 08:43:13 -0800381 } catch (InvalidKeyException e) {
382 throw new KeyChainException(e);
Brian Carlstromba1a6672011-05-24 21:54:37 -0700383 } finally {
384 keyChainConnection.close();
385 }
386 }
387
388 /**
389 * Returns the {@code X509Certificate} chain for the requested
390 * alias, or null if no there is no result.
Brian Carlstrom93201f52011-06-09 15:05:35 -0700391 *
Brian Carlstrom93201f52011-06-09 15:05:35 -0700392 * @param alias The alias of the desired certificate chain, typically
393 * returned via {@link KeyChainAliasCallback#alias}.
394 * @throws KeyChainException if the alias was valid but there was some problem accessing it.
Brian Carlstromba1a6672011-05-24 21:54:37 -0700395 */
Alex Klyubin54bb1592015-05-11 12:30:03 -0700396 @Nullable
397 public static X509Certificate[] getCertificateChain(@NonNull Context context,
398 @NonNull String alias) throws KeyChainException, InterruptedException {
Brian Carlstromba1a6672011-05-24 21:54:37 -0700399 if (alias == null) {
400 throw new NullPointerException("alias == null");
401 }
402 KeyChainConnection keyChainConnection = bind(context);
403 try {
Brian Carlstromba1a6672011-05-24 21:54:37 -0700404 IKeyChainService keyChainService = keyChainConnection.getService();
Kenny Root0150e482013-02-13 15:22:50 -0800405
406 final byte[] certificateBytes = keyChainService.getCertificate(alias);
407 if (certificateBytes == null) {
408 return null;
409 }
410
Brian Carlstromdb93b782011-07-01 00:12:17 -0700411 TrustedCertificateStore store = new TrustedCertificateStore();
Kenny Root54e03af2012-08-07 10:04:26 -0700412 List<X509Certificate> chain = store
413 .getCertificateChain(toCertificate(certificateBytes));
Brian Carlstromdb93b782011-07-01 00:12:17 -0700414 return chain.toArray(new X509Certificate[chain.size()]);
Kenny Rootcfba6a02013-05-06 15:00:58 -0700415 } catch (CertificateException e) {
416 throw new KeyChainException(e);
Brian Carlstrom93201f52011-06-09 15:05:35 -0700417 } catch (RemoteException e) {
418 throw new KeyChainException(e);
419 } catch (RuntimeException e) {
420 // only certain RuntimeExceptions can be propagated across the IKeyChainService call
421 throw new KeyChainException(e);
Brian Carlstrom8e9929c2011-05-17 00:40:28 -0700422 } finally {
Brian Carlstromd7524722011-05-17 16:20:36 -0700423 keyChainConnection.close();
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700424 }
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700425 }
426
Kenny Rootbf556ac2013-04-01 15:10:22 -0700427 /**
428 * Returns {@code true} if the current device's {@code KeyChain} supports a
429 * specific {@code PrivateKey} type indicated by {@code algorithm} (e.g.,
430 * "RSA").
431 */
Alex Klyubin4d5443f2015-05-06 15:43:52 -0700432 public static boolean isKeyAlgorithmSupported(
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700433 @NonNull @KeyProperties.KeyAlgorithmEnum String algorithm) {
Kenny Rootb91773b2013-09-05 13:03:16 -0700434 final String algUpper = algorithm.toUpperCase(Locale.US);
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700435 return KeyProperties.KEY_ALGORITHM_EC.equals(algUpper)
436 || KeyProperties.KEY_ALGORITHM_RSA.equals(algUpper);
Kenny Rootbf556ac2013-04-01 15:10:22 -0700437 }
438
439 /**
440 * Returns {@code true} if the current device's {@code KeyChain} binds any
441 * {@code PrivateKey} of the given {@code algorithm} to the device once
442 * imported or generated. This can be used to tell if there is special
443 * hardware support that can be used to bind keys to the device in a way
444 * that makes it non-exportable.
445 */
Alex Klyubin4d5443f2015-05-06 15:43:52 -0700446 public static boolean isBoundKeyAlgorithm(
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700447 @NonNull @KeyProperties.KeyAlgorithmEnum String algorithm) {
Kenny Root5b7e90a2013-04-02 11:23:41 -0700448 if (!isKeyAlgorithmSupported(algorithm)) {
Kenny Rootbf556ac2013-04-01 15:10:22 -0700449 return false;
450 }
451
Kenny Rootb91773b2013-09-05 13:03:16 -0700452 return KeyStore.getInstance().isHardwareBacked(algorithm);
Kenny Rootbf556ac2013-04-01 15:10:22 -0700453 }
454
Zoltan Szatmary-Banf0ae1352014-08-18 10:48:33 +0100455 /** @hide */
Alex Klyubin54bb1592015-05-11 12:30:03 -0700456 @NonNull
457 public static X509Certificate toCertificate(@NonNull byte[] bytes) {
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700458 if (bytes == null) {
Brian Carlstrom8e9929c2011-05-17 00:40:28 -0700459 throw new IllegalArgumentException("bytes == null");
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700460 }
461 try {
462 CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
463 Certificate cert = certFactory.generateCertificate(new ByteArrayInputStream(bytes));
464 return (X509Certificate) cert;
465 } catch (CertificateException e) {
466 throw new AssertionError(e);
467 }
468 }
469
Brian Carlstromd7524722011-05-17 16:20:36 -0700470 /**
471 * @hide for reuse by CertInstaller and Settings.
472 * @see KeyChain#bind
473 */
474 public final static class KeyChainConnection implements Closeable {
475 private final Context context;
476 private final ServiceConnection serviceConnection;
477 private final IKeyChainService service;
478 private KeyChainConnection(Context context,
479 ServiceConnection serviceConnection,
480 IKeyChainService service) {
481 this.context = context;
482 this.serviceConnection = serviceConnection;
483 this.service = service;
484 }
485 @Override public void close() {
486 context.unbindService(serviceConnection);
487 }
488 public IKeyChainService getService() {
489 return service;
490 }
491 }
492
493 /**
494 * @hide for reuse by CertInstaller and Settings.
495 *
496 * Caller should call unbindService on the result when finished.
497 */
Alex Klyubin54bb1592015-05-11 12:30:03 -0700498 public static KeyChainConnection bind(@NonNull Context context) throws InterruptedException {
Robin Lee306fe082014-06-19 14:04:24 +0000499 return bindAsUser(context, Process.myUserHandle());
500 }
501
502 /**
503 * @hide
504 */
Alex Klyubin54bb1592015-05-11 12:30:03 -0700505 public static KeyChainConnection bindAsUser(@NonNull Context context, UserHandle user)
Robin Lee306fe082014-06-19 14:04:24 +0000506 throws InterruptedException {
Brian Carlstromd7524722011-05-17 16:20:36 -0700507 if (context == null) {
508 throw new NullPointerException("context == null");
509 }
510 ensureNotOnMainThread(context);
511 final BlockingQueue<IKeyChainService> q = new LinkedBlockingQueue<IKeyChainService>(1);
512 ServiceConnection keyChainServiceConnection = new ServiceConnection() {
Fred Quintanaab8b84a2011-07-13 14:55:39 -0700513 volatile boolean mConnectedAtLeastOnce = false;
Brian Carlstromd7524722011-05-17 16:20:36 -0700514 @Override public void onServiceConnected(ComponentName name, IBinder service) {
Fred Quintanaab8b84a2011-07-13 14:55:39 -0700515 if (!mConnectedAtLeastOnce) {
516 mConnectedAtLeastOnce = true;
517 try {
518 q.put(IKeyChainService.Stub.asInterface(service));
519 } catch (InterruptedException e) {
520 // will never happen, since the queue starts with one available slot
521 }
Brian Carlstromd7524722011-05-17 16:20:36 -0700522 }
523 }
524 @Override public void onServiceDisconnected(ComponentName name) {}
525 };
Maggie Benthallda51e682013-08-08 22:35:44 -0400526 Intent intent = new Intent(IKeyChainService.class.getName());
527 ComponentName comp = intent.resolveSystemService(context.getPackageManager(), 0);
528 intent.setComponent(comp);
Robin Lee306fe082014-06-19 14:04:24 +0000529 boolean isBound = context.bindServiceAsUser(intent,
530 keyChainServiceConnection,
531 Context.BIND_AUTO_CREATE,
532 user);
Brian Carlstromd7524722011-05-17 16:20:36 -0700533 if (!isBound) {
534 throw new AssertionError("could not bind to KeyChainService");
535 }
536 return new KeyChainConnection(context, keyChainServiceConnection, q.take());
537 }
538
Alex Klyubin54bb1592015-05-11 12:30:03 -0700539 private static void ensureNotOnMainThread(@NonNull Context context) {
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700540 Looper looper = Looper.myLooper();
Brian Carlstrom8e9929c2011-05-17 00:40:28 -0700541 if (looper != null && looper == context.getMainLooper()) {
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700542 throw new IllegalStateException(
543 "calling this from your main thread can lead to deadlock");
544 }
545 }
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700546}