blob: f482bf00ab0a3736306ac502122dd428103ba493 [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 Klyubin4a0ff7c2015-06-09 13:25:20 -070032import android.security.keystore.AndroidKeyStoreProvider;
Alex Klyubin3f8d4d82015-05-13 09:15:00 -070033import android.security.keystore.KeyProperties;
34
Brian Carlstromb9a07c12011-04-11 09:03:51 -070035import java.io.ByteArrayInputStream;
Brian Carlstromd7524722011-05-17 16:20:36 -070036import java.io.Closeable;
Brian Carlstrom93201f52011-06-09 15:05:35 -070037import java.security.Principal;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070038import java.security.PrivateKey;
Alex Klyubin4a0ff7c2015-06-09 13:25:20 -070039import java.security.UnrecoverableKeyException;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070040import java.security.cert.Certificate;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070041import java.security.cert.CertificateException;
42import java.security.cert.CertificateFactory;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070043import java.security.cert.X509Certificate;
Brian Carlstromdb93b782011-07-01 00:12:17 -070044import java.util.List;
Kenny Rootb91773b2013-09-05 13:03:16 -070045import java.util.Locale;
Brian Carlstrom8e9929c2011-05-17 00:40:28 -070046import java.util.concurrent.BlockingQueue;
47import java.util.concurrent.LinkedBlockingQueue;
Kenny Root5423e682011-11-14 08:43:13 -080048
Kenny Root12e75222013-04-23 22:34:24 -070049import 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
Brian Carlstromb9a07c12011-04-11 09:03:51 -070091 /**
92 * @hide Also used by KeyChainService implementation
93 */
94 public static final String ACCOUNT_TYPE = "com.android.keychain";
95
96 /**
Kenny Roota3659062014-03-17 16:21:53 -070097 * Package name for KeyChain chooser.
98 */
99 private static final String KEYCHAIN_PACKAGE = "com.android.keychain";
100
101 /**
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700102 * Action to bring up the KeyChainActivity
103 */
104 private static final String ACTION_CHOOSER = "com.android.keychain.CHOOSER";
105
106 /**
Kenny Root1a88d832014-02-07 09:12:48 -0800107 * Package name for the Certificate Installer.
108 */
109 private static final String CERT_INSTALLER_PACKAGE = "com.android.certinstaller";
110
111 /**
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700112 * Extra for use with {@link #ACTION_CHOOSER}
Brian Carlstromba1a6672011-05-24 21:54:37 -0700113 * @hide Also used by KeyChainActivity implementation
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700114 */
Brian Carlstromba1a6672011-05-24 21:54:37 -0700115 public static final String EXTRA_RESPONSE = "response";
116
117 /**
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700118 * Extra for use with {@link #ACTION_CHOOSER}
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700119 * @hide Also used by KeyChainActivity implementation
120 */
Robin Lee39087b12015-05-05 15:57:17 +0100121 public static final String EXTRA_URI = "uri";
Robin Lee3798ed52015-02-03 17:55:31 +0000122
123 /**
124 * Extra for use with {@link #ACTION_CHOOSER}
125 * @hide Also used by KeyChainActivity implementation
126 */
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700127 public static final String EXTRA_ALIAS = "alias";
128
129 /**
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700130 * Extra for use with {@link #ACTION_CHOOSER}
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700131 * @hide Also used by KeyChainActivity implementation
132 */
133 public static final String EXTRA_SENDER = "sender";
134
135 /**
Selim Gurun93ba4fe2012-02-14 11:48:49 -0800136 * Action to bring up the CertInstaller.
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700137 */
138 private static final String ACTION_INSTALL = "android.credentials.INSTALL";
139
140 /**
141 * Optional extra to specify a {@code String} credential name on
142 * the {@code Intent} returned by {@link #createInstallIntent}.
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700143 */
144 // Compatible with old com.android.certinstaller.CredentialHelper.CERT_NAME_KEY
145 public static final String EXTRA_NAME = "name";
146
147 /**
148 * Optional extra to specify an X.509 certificate to install on
149 * the {@code Intent} returned by {@link #createInstallIntent}.
150 * The extra value should be a PEM or ASN.1 DER encoded {@code
151 * byte[]}. An {@link X509Certificate} can be converted to DER
152 * encoded bytes with {@link X509Certificate#getEncoded}.
153 *
154 * <p>{@link #EXTRA_NAME} may be used to provide a default alias
155 * name for the installed certificate.
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700156 */
157 // Compatible with old android.security.Credentials.CERTIFICATE
158 public static final String EXTRA_CERTIFICATE = "CERT";
159
160 /**
161 * Optional extra for use with the {@code Intent} returned by
162 * {@link #createInstallIntent} to specify a PKCS#12 key store to
163 * install. The extra value should be a {@code byte[]}. The bytes
164 * may come from an external source or be generated with {@link
Brian Carlstromca43c452011-06-29 18:53:17 -0700165 * java.security.KeyStore#store} on a "PKCS12" instance.
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700166 *
167 * <p>The user will be prompted for the password to load the key store.
168 *
169 * <p>The key store will be scanned for {@link
170 * java.security.KeyStore.PrivateKeyEntry} entries and both the
171 * private key and associated certificate chain will be installed.
172 *
173 * <p>{@link #EXTRA_NAME} may be used to provide a default alias
174 * name for the installed credentials.
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700175 */
176 // Compatible with old android.security.Credentials.PKCS12
177 public static final String EXTRA_PKCS12 = "PKCS12";
178
Selim Gurun93ba4fe2012-02-14 11:48:49 -0800179
180 /**
Selim Gurun93ba4fe2012-02-14 11:48:49 -0800181 * Broadcast Action: Indicates the trusted storage has changed. Sent when
182 * one of this happens:
183 *
184 * <ul>
185 * <li>a new CA is added,
186 * <li>an existing CA is removed or disabled,
187 * <li>a disabled CA is enabled,
188 * <li>trusted storage is reset (all user certs are cleared),
189 * <li>when permission to access a private key is changed.
190 * </ul>
191 */
192 public static final String ACTION_STORAGE_CHANGED = "android.security.STORAGE_CHANGED";
193
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700194 /**
195 * Returns an {@code Intent} that can be used for credential
196 * installation. The intent may be used without any extras, in
197 * which case the user will be able to install credentials from
198 * their own source.
199 *
200 * <p>Alternatively, {@link #EXTRA_CERTIFICATE} or {@link
201 * #EXTRA_PKCS12} maybe used to specify the bytes of an X.509
202 * certificate or a PKCS#12 key store for installation. These
Brian Carlstromca43c452011-06-29 18:53:17 -0700203 * extras may be combined with {@link #EXTRA_NAME} to provide a
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700204 * default alias name for credentials being installed.
205 *
206 * <p>When used with {@link Activity#startActivityForResult},
207 * {@link Activity#RESULT_OK} will be returned if a credential was
208 * successfully installed, otherwise {@link
209 * Activity#RESULT_CANCELED} will be returned.
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700210 */
Alex Klyubin54bb1592015-05-11 12:30:03 -0700211 @NonNull
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700212 public static Intent createInstallIntent() {
213 Intent intent = new Intent(ACTION_INSTALL);
Kenny Root1a88d832014-02-07 09:12:48 -0800214 intent.setClassName(CERT_INSTALLER_PACKAGE,
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700215 "com.android.certinstaller.CertInstallerMain");
216 return intent;
217 }
218
219 /**
Brian Carlstromba1a6672011-05-24 21:54:37 -0700220 * Launches an {@code Activity} for the user to select the alias
221 * for a private key and certificate pair for authentication. The
222 * selected alias or null will be returned via the
Brian Carlstrom93201f52011-06-09 15:05:35 -0700223 * KeyChainAliasCallback callback.
224 *
Robin Lee3798ed52015-02-03 17:55:31 +0000225 * <p>The device or profile owner can intercept this before the activity
226 * is shown, to pick a specific private key alias.
227 *
228 * <p>{@code keyTypes} and {@code issuers} may be used to
229 * highlight suggested choices to the user, although to cope with
230 * sometimes erroneous values provided by servers, the user may be
231 * able to override these suggestions.
232 *
233 * <p>{@code host} and {@code port} may be used to give the user
234 * more context about the server requesting the credentials.
235 *
236 * <p>{@code alias} allows the chooser to preselect an existing
237 * alias which will still be subject to user confirmation.
238 *
239 * @param activity The {@link Activity} context to use for
240 * launching the new sub-Activity to prompt the user to select
241 * a private key; used only to call startActivity(); must not
242 * be null.
243 * @param response Callback to invoke when the request completes;
244 * must not be null
245 * @param keyTypes The acceptable types of asymmetric keys such as
246 * "RSA" or "DSA", or a null array.
247 * @param issuers The acceptable certificate issuers for the
248 * certificate matching the private key, or null.
249 * @param host The host name of the server requesting the
250 * certificate, or null if unavailable.
251 * @param port The port number of the server requesting the
252 * certificate, or -1 if unavailable.
253 * @param alias The alias to preselect if available, or null if
254 * unavailable.
255 */
Alex Klyubin54bb1592015-05-11 12:30:03 -0700256 public static void choosePrivateKeyAlias(@NonNull Activity activity,
257 @NonNull KeyChainAliasCallback response,
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700258 @KeyProperties.KeyAlgorithmEnum String[] keyTypes, Principal[] issuers,
Alex Klyubin54bb1592015-05-11 12:30:03 -0700259 @Nullable String host, int port, @Nullable String alias) {
Robin Lee39087b12015-05-05 15:57:17 +0100260 Uri uri = null;
261 if (host != null) {
262 uri = new Uri.Builder()
263 .authority(host + (port != -1 ? ":" + port : ""))
264 .build();
265 }
266 choosePrivateKeyAlias(activity, response, keyTypes, issuers, uri, alias);
Robin Lee3798ed52015-02-03 17:55:31 +0000267 }
268
269 /**
270 * Launches an {@code Activity} for the user to select the alias
271 * for a private key and certificate pair for authentication. The
272 * selected alias or null will be returned via the
273 * KeyChainAliasCallback callback.
274 *
275 * <p>The device or profile owner can intercept this before the activity
276 * is shown, to pick a specific private key alias.</p>
277 *
Brian Carlstrom93201f52011-06-09 15:05:35 -0700278 * <p>{@code keyTypes} and {@code issuers} may be used to
279 * highlight suggested choices to the user, although to cope with
280 * sometimes erroneous values provided by servers, the user may be
281 * able to override these suggestions.
282 *
283 * <p>{@code host} and {@code port} may be used to give the user
284 * more context about the server requesting the credentials.
285 *
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700286 * <p>{@code alias} allows the chooser to preselect an existing
287 * alias which will still be subject to user confirmation.
288 *
Brian Carlstrom93201f52011-06-09 15:05:35 -0700289 * @param activity The {@link Activity} context to use for
290 * launching the new sub-Activity to prompt the user to select
291 * a private key; used only to call startActivity(); must not
292 * be null.
293 * @param response Callback to invoke when the request completes;
294 * must not be null
295 * @param keyTypes The acceptable types of asymmetric keys such as
Alex Klyubincd2329d2015-01-14 16:45:51 -0800296 * "EC" or "RSA", or a null array.
Brian Carlstrom93201f52011-06-09 15:05:35 -0700297 * @param issuers The acceptable certificate issuers for the
298 * certificate matching the private key, or null.
Robin Lee39087b12015-05-05 15:57:17 +0100299 * @param uri The full URI the server is requesting the certificate
Robin Lee3798ed52015-02-03 17:55:31 +0000300 * for, or null if unavailable.
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700301 * @param alias The alias to preselect if available, or null if
302 * unavailable.
Brian Carlstromba1a6672011-05-24 21:54:37 -0700303 */
Alex Klyubin54bb1592015-05-11 12:30:03 -0700304 public static void choosePrivateKeyAlias(@NonNull Activity activity,
305 @NonNull KeyChainAliasCallback response,
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700306 @KeyProperties.KeyAlgorithmEnum String[] keyTypes, Principal[] issuers,
Robin Lee39087b12015-05-05 15:57:17 +0100307 @Nullable Uri uri, @Nullable String alias) {
Brian Carlstrom93201f52011-06-09 15:05:35 -0700308 /*
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700309 * TODO currently keyTypes, issuers are unused. They are meant
310 * to follow the semantics and purpose of X509KeyManager
311 * method arguments.
Brian Carlstrom93201f52011-06-09 15:05:35 -0700312 *
313 * keyTypes would allow the list to be filtered and typically
314 * will be set correctly by the server. In practice today,
Alex Klyubincd2329d2015-01-14 16:45:51 -0800315 * most all users will want only RSA or EC, and usually
Brian Carlstrom93201f52011-06-09 15:05:35 -0700316 * only a small number of certs will be available.
317 *
318 * issuers is typically not useful. Some servers historically
319 * will send the entire list of public CAs known to the
320 * server. Others will send none. If this is used, if there
321 * are no matches after applying the constraint, it should be
322 * ignored.
Brian Carlstrom93201f52011-06-09 15:05:35 -0700323 */
Brian Carlstromba1a6672011-05-24 21:54:37 -0700324 if (activity == null) {
325 throw new NullPointerException("activity == null");
326 }
327 if (response == null) {
328 throw new NullPointerException("response == null");
329 }
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700330 Intent intent = new Intent(ACTION_CHOOSER);
Kenny Roota3659062014-03-17 16:21:53 -0700331 intent.setPackage(KEYCHAIN_PACKAGE);
Fred Quintanaab8b84a2011-07-13 14:55:39 -0700332 intent.putExtra(EXTRA_RESPONSE, new AliasResponse(response));
Robin Lee39087b12015-05-05 15:57:17 +0100333 intent.putExtra(EXTRA_URI, uri);
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700334 intent.putExtra(EXTRA_ALIAS, alias);
335 // the PendingIntent is used to get calling package name
336 intent.putExtra(EXTRA_SENDER, PendingIntent.getActivity(activity, 0, new Intent(), 0));
Brian Carlstromba1a6672011-05-24 21:54:37 -0700337 activity.startActivity(intent);
338 }
339
Brian Carlstrom93201f52011-06-09 15:05:35 -0700340 private static class AliasResponse extends IKeyChainAliasCallback.Stub {
Brian Carlstrom93201f52011-06-09 15:05:35 -0700341 private final KeyChainAliasCallback keyChainAliasResponse;
Fred Quintanaab8b84a2011-07-13 14:55:39 -0700342 private AliasResponse(KeyChainAliasCallback keyChainAliasResponse) {
Brian Carlstromba1a6672011-05-24 21:54:37 -0700343 this.keyChainAliasResponse = keyChainAliasResponse;
344 }
345 @Override public void alias(String alias) {
Fred Quintanaab8b84a2011-07-13 14:55:39 -0700346 keyChainAliasResponse.alias(alias);
Brian Carlstromba1a6672011-05-24 21:54:37 -0700347 }
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700348 }
349
350 /**
Brian Carlstromba1a6672011-05-24 21:54:37 -0700351 * Returns the {@code PrivateKey} for the requested alias, or null
352 * if no there is no result.
Brian Carlstrom93201f52011-06-09 15:05:35 -0700353 *
Brian Carlstrom93201f52011-06-09 15:05:35 -0700354 * @param alias The alias of the desired private key, typically
355 * returned via {@link KeyChainAliasCallback#alias}.
356 * @throws KeyChainException if the alias was valid but there was some problem accessing it.
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700357 */
Alex Klyubin54bb1592015-05-11 12:30:03 -0700358 @Nullable
359 public static PrivateKey getPrivateKey(@NonNull Context context, @NonNull String alias)
Brian Carlstrom93201f52011-06-09 15:05:35 -0700360 throws KeyChainException, InterruptedException {
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700361 if (alias == null) {
362 throw new NullPointerException("alias == null");
363 }
Brian Carlstromd7524722011-05-17 16:20:36 -0700364 KeyChainConnection keyChainConnection = bind(context);
Brian Carlstrom8e9929c2011-05-17 00:40:28 -0700365 try {
Kenny Root5423e682011-11-14 08:43:13 -0800366 final IKeyChainService keyChainService = keyChainConnection.getService();
367 final String keyId = keyChainService.requestPrivateKey(alias);
368 if (keyId == null) {
369 throw new KeyChainException("keystore had a problem");
370 }
Alex Klyubin4a0ff7c2015-06-09 13:25:20 -0700371 return AndroidKeyStoreProvider.loadAndroidKeyStorePrivateKeyFromKeystore(
372 KeyStore.getInstance(), keyId);
Brian Carlstrom93201f52011-06-09 15:05:35 -0700373 } catch (RemoteException e) {
374 throw new KeyChainException(e);
375 } catch (RuntimeException e) {
376 // only certain RuntimeExceptions can be propagated across the IKeyChainService call
377 throw new KeyChainException(e);
Alex Klyubin4a0ff7c2015-06-09 13:25:20 -0700378 } catch (UnrecoverableKeyException e) {
Kenny Root5423e682011-11-14 08:43:13 -0800379 throw new KeyChainException(e);
Brian Carlstromba1a6672011-05-24 21:54:37 -0700380 } finally {
381 keyChainConnection.close();
382 }
383 }
384
385 /**
386 * Returns the {@code X509Certificate} chain for the requested
387 * alias, or null if no there is no result.
Brian Carlstrom93201f52011-06-09 15:05:35 -0700388 *
Brian Carlstrom93201f52011-06-09 15:05:35 -0700389 * @param alias The alias of the desired certificate chain, typically
390 * returned via {@link KeyChainAliasCallback#alias}.
391 * @throws KeyChainException if the alias was valid but there was some problem accessing it.
Brian Carlstromba1a6672011-05-24 21:54:37 -0700392 */
Alex Klyubin54bb1592015-05-11 12:30:03 -0700393 @Nullable
394 public static X509Certificate[] getCertificateChain(@NonNull Context context,
395 @NonNull String alias) throws KeyChainException, InterruptedException {
Brian Carlstromba1a6672011-05-24 21:54:37 -0700396 if (alias == null) {
397 throw new NullPointerException("alias == null");
398 }
399 KeyChainConnection keyChainConnection = bind(context);
400 try {
Brian Carlstromba1a6672011-05-24 21:54:37 -0700401 IKeyChainService keyChainService = keyChainConnection.getService();
Kenny Root0150e482013-02-13 15:22:50 -0800402
403 final byte[] certificateBytes = keyChainService.getCertificate(alias);
404 if (certificateBytes == null) {
405 return null;
406 }
407
Brian Carlstromdb93b782011-07-01 00:12:17 -0700408 TrustedCertificateStore store = new TrustedCertificateStore();
Kenny Root54e03af2012-08-07 10:04:26 -0700409 List<X509Certificate> chain = store
410 .getCertificateChain(toCertificate(certificateBytes));
Brian Carlstromdb93b782011-07-01 00:12:17 -0700411 return chain.toArray(new X509Certificate[chain.size()]);
Kenny Rootcfba6a02013-05-06 15:00:58 -0700412 } catch (CertificateException e) {
413 throw new KeyChainException(e);
Brian Carlstrom93201f52011-06-09 15:05:35 -0700414 } catch (RemoteException e) {
415 throw new KeyChainException(e);
416 } catch (RuntimeException e) {
417 // only certain RuntimeExceptions can be propagated across the IKeyChainService call
418 throw new KeyChainException(e);
Brian Carlstrom8e9929c2011-05-17 00:40:28 -0700419 } finally {
Brian Carlstromd7524722011-05-17 16:20:36 -0700420 keyChainConnection.close();
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700421 }
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700422 }
423
Kenny Rootbf556ac2013-04-01 15:10:22 -0700424 /**
425 * Returns {@code true} if the current device's {@code KeyChain} supports a
426 * specific {@code PrivateKey} type indicated by {@code algorithm} (e.g.,
427 * "RSA").
428 */
Alex Klyubin4d5443f2015-05-06 15:43:52 -0700429 public static boolean isKeyAlgorithmSupported(
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700430 @NonNull @KeyProperties.KeyAlgorithmEnum String algorithm) {
Kenny Rootb91773b2013-09-05 13:03:16 -0700431 final String algUpper = algorithm.toUpperCase(Locale.US);
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700432 return KeyProperties.KEY_ALGORITHM_EC.equals(algUpper)
433 || KeyProperties.KEY_ALGORITHM_RSA.equals(algUpper);
Kenny Rootbf556ac2013-04-01 15:10:22 -0700434 }
435
436 /**
437 * Returns {@code true} if the current device's {@code KeyChain} binds any
438 * {@code PrivateKey} of the given {@code algorithm} to the device once
439 * imported or generated. This can be used to tell if there is special
440 * hardware support that can be used to bind keys to the device in a way
441 * that makes it non-exportable.
Alex Klyubin469cbf52015-06-04 12:36:27 -0700442 *
443 * @deprecated Whether the key is bound to the secure hardware is known only
444 * once the key has been imported. To find out, use:
445 * <pre>{@code
446 * PrivateKey key = ...; // private key from KeyChain
447 *
448 * KeyFactory keyFactory =
449 * KeyFactory.getInstance(key.getAlgorithm(), "AndroidKeyStore");
450 * KeyInfo keyInfo = keyFactory.getKeySpec(key, KeyInfo.class);
451 * if (keyInfo.isInsideSecureHardware()) &#123;
452 * // The key is bound to the secure hardware of this Android
453 * &#125;}</pre>
Kenny Rootbf556ac2013-04-01 15:10:22 -0700454 */
Alex Klyubin469cbf52015-06-04 12:36:27 -0700455 @Deprecated
Alex Klyubin4d5443f2015-05-06 15:43:52 -0700456 public static boolean isBoundKeyAlgorithm(
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700457 @NonNull @KeyProperties.KeyAlgorithmEnum String algorithm) {
Kenny Root5b7e90a2013-04-02 11:23:41 -0700458 if (!isKeyAlgorithmSupported(algorithm)) {
Kenny Rootbf556ac2013-04-01 15:10:22 -0700459 return false;
460 }
461
Kenny Rootb91773b2013-09-05 13:03:16 -0700462 return KeyStore.getInstance().isHardwareBacked(algorithm);
Kenny Rootbf556ac2013-04-01 15:10:22 -0700463 }
464
Zoltan Szatmary-Banf0ae1352014-08-18 10:48:33 +0100465 /** @hide */
Alex Klyubin54bb1592015-05-11 12:30:03 -0700466 @NonNull
467 public static X509Certificate toCertificate(@NonNull byte[] bytes) {
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700468 if (bytes == null) {
Brian Carlstrom8e9929c2011-05-17 00:40:28 -0700469 throw new IllegalArgumentException("bytes == null");
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700470 }
471 try {
472 CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
473 Certificate cert = certFactory.generateCertificate(new ByteArrayInputStream(bytes));
474 return (X509Certificate) cert;
475 } catch (CertificateException e) {
476 throw new AssertionError(e);
477 }
478 }
479
Brian Carlstromd7524722011-05-17 16:20:36 -0700480 /**
481 * @hide for reuse by CertInstaller and Settings.
482 * @see KeyChain#bind
483 */
484 public final static class KeyChainConnection implements Closeable {
485 private final Context context;
486 private final ServiceConnection serviceConnection;
487 private final IKeyChainService service;
488 private KeyChainConnection(Context context,
489 ServiceConnection serviceConnection,
490 IKeyChainService service) {
491 this.context = context;
492 this.serviceConnection = serviceConnection;
493 this.service = service;
494 }
495 @Override public void close() {
496 context.unbindService(serviceConnection);
497 }
498 public IKeyChainService getService() {
499 return service;
500 }
501 }
502
503 /**
504 * @hide for reuse by CertInstaller and Settings.
505 *
506 * Caller should call unbindService on the result when finished.
507 */
Alex Klyubin54bb1592015-05-11 12:30:03 -0700508 public static KeyChainConnection bind(@NonNull Context context) throws InterruptedException {
Robin Lee306fe082014-06-19 14:04:24 +0000509 return bindAsUser(context, Process.myUserHandle());
510 }
511
512 /**
513 * @hide
514 */
Alex Klyubin54bb1592015-05-11 12:30:03 -0700515 public static KeyChainConnection bindAsUser(@NonNull Context context, UserHandle user)
Robin Lee306fe082014-06-19 14:04:24 +0000516 throws InterruptedException {
Brian Carlstromd7524722011-05-17 16:20:36 -0700517 if (context == null) {
518 throw new NullPointerException("context == null");
519 }
520 ensureNotOnMainThread(context);
521 final BlockingQueue<IKeyChainService> q = new LinkedBlockingQueue<IKeyChainService>(1);
522 ServiceConnection keyChainServiceConnection = new ServiceConnection() {
Fred Quintanaab8b84a2011-07-13 14:55:39 -0700523 volatile boolean mConnectedAtLeastOnce = false;
Brian Carlstromd7524722011-05-17 16:20:36 -0700524 @Override public void onServiceConnected(ComponentName name, IBinder service) {
Fred Quintanaab8b84a2011-07-13 14:55:39 -0700525 if (!mConnectedAtLeastOnce) {
526 mConnectedAtLeastOnce = true;
527 try {
528 q.put(IKeyChainService.Stub.asInterface(service));
529 } catch (InterruptedException e) {
530 // will never happen, since the queue starts with one available slot
531 }
Brian Carlstromd7524722011-05-17 16:20:36 -0700532 }
533 }
534 @Override public void onServiceDisconnected(ComponentName name) {}
535 };
Maggie Benthallda51e682013-08-08 22:35:44 -0400536 Intent intent = new Intent(IKeyChainService.class.getName());
537 ComponentName comp = intent.resolveSystemService(context.getPackageManager(), 0);
538 intent.setComponent(comp);
Robin Lee306fe082014-06-19 14:04:24 +0000539 boolean isBound = context.bindServiceAsUser(intent,
540 keyChainServiceConnection,
541 Context.BIND_AUTO_CREATE,
542 user);
Brian Carlstromd7524722011-05-17 16:20:36 -0700543 if (!isBound) {
544 throw new AssertionError("could not bind to KeyChainService");
545 }
546 return new KeyChainConnection(context, keyChainServiceConnection, q.take());
547 }
548
Alex Klyubin54bb1592015-05-11 12:30:03 -0700549 private static void ensureNotOnMainThread(@NonNull Context context) {
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700550 Looper looper = Looper.myLooper();
Brian Carlstrom8e9929c2011-05-17 00:40:28 -0700551 if (looper != null && looper == context.getMainLooper()) {
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700552 throw new IllegalStateException(
553 "calling this from your main thread can lead to deadlock");
554 }
555 }
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700556}