blob: 78dbb6ae0df3a886abe9ce0cdd72bdbffb19c114 [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;
Jeff Sharkey0f3f60b2017-04-24 18:06:20 -060020import android.annotation.SdkConstant;
Robin Lee59e3baa2015-06-30 10:48:06 -070021import android.annotation.WorkerThread;
Jeff Sharkey0f3f60b2017-04-24 18:06:20 -060022import android.annotation.SdkConstant.SdkConstantType;
Brian Carlstromba1a6672011-05-24 21:54:37 -070023import android.app.Activity;
Brian Carlstrom67c30df2011-06-24 02:13:23 -070024import android.app.PendingIntent;
Robin Leeda236182016-08-12 12:46:28 +010025import android.app.Service;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070026import android.content.ComponentName;
27import android.content.Context;
28import android.content.Intent;
29import android.content.ServiceConnection;
Robin Lee39087b12015-05-05 15:57:17 +010030import android.net.Uri;
Jeff Sharkey0a17db12016-11-04 11:23:46 -060031import android.os.Binder;
Chad Brubaker721afae2016-07-08 11:06:09 -070032import android.os.Build;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070033import android.os.IBinder;
34import android.os.Looper;
Robin Lee306fe082014-06-19 14:04:24 +000035import android.os.Process;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070036import android.os.RemoteException;
Robin Lee306fe082014-06-19 14:04:24 +000037import android.os.UserHandle;
Alex Klyubin4a0ff7c2015-06-09 13:25:20 -070038import android.security.keystore.AndroidKeyStoreProvider;
Alex Klyubin3f8d4d82015-05-13 09:15:00 -070039import android.security.keystore.KeyProperties;
40
Brian Carlstromb9a07c12011-04-11 09:03:51 -070041import java.io.ByteArrayInputStream;
Brian Carlstromd7524722011-05-17 16:20:36 -070042import java.io.Closeable;
Eran Messeri23c438d2017-11-23 17:20:52 +000043import java.security.KeyPair;
Brian Carlstrom93201f52011-06-09 15:05:35 -070044import java.security.Principal;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070045import java.security.PrivateKey;
Alex Klyubin4a0ff7c2015-06-09 13:25:20 -070046import java.security.UnrecoverableKeyException;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070047import java.security.cert.Certificate;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070048import java.security.cert.CertificateException;
49import java.security.cert.CertificateFactory;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070050import java.security.cert.X509Certificate;
Rubin Xub4365912016-03-23 12:13:22 +000051import java.util.ArrayList;
52import java.util.Collection;
Brian Carlstromdb93b782011-07-01 00:12:17 -070053import java.util.List;
Kenny Rootb91773b2013-09-05 13:03:16 -070054import java.util.Locale;
Brian Carlstrom8e9929c2011-05-17 00:40:28 -070055import java.util.concurrent.BlockingQueue;
56import java.util.concurrent.LinkedBlockingQueue;
Kenny Root5423e682011-11-14 08:43:13 -080057
Kenny Root12e75222013-04-23 22:34:24 -070058import com.android.org.conscrypt.TrustedCertificateStore;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070059
60/**
Brian Carlstrom93201f52011-06-09 15:05:35 -070061 * The {@code KeyChain} class provides access to private keys and
62 * their corresponding certificate chains in credential storage.
63 *
64 * <p>Applications accessing the {@code KeyChain} normally go through
65 * these steps:
66 *
67 * <ol>
68 *
69 * <li>Receive a callback from an {@link javax.net.ssl.X509KeyManager
70 * X509KeyManager} that a private key is requested.
71 *
72 * <li>Call {@link #choosePrivateKeyAlias
73 * choosePrivateKeyAlias} to allow the user to select from a
74 * list of currently available private keys and corresponding
75 * certificate chains. The chosen alias will be returned by the
76 * callback {@link KeyChainAliasCallback#alias}, or null if no private
77 * key is available or the user cancels the request.
78 *
79 * <li>Call {@link #getPrivateKey} and {@link #getCertificateChain} to
80 * retrieve the credentials to return to the corresponding {@link
81 * javax.net.ssl.X509KeyManager} callbacks.
82 *
83 * </ol>
84 *
85 * <p>An application may remember the value of a selected alias to
86 * avoid prompting the user with {@link #choosePrivateKeyAlias
87 * choosePrivateKeyAlias} on subsequent connections. If the alias is
88 * no longer valid, null will be returned on lookups using that value
Brian Carlstromca43c452011-06-29 18:53:17 -070089 *
90 * <p>An application can request the installation of private keys and
91 * certificates via the {@code Intent} provided by {@link
92 * #createInstallIntent}. Private keys installed via this {@code
93 * Intent} will be accessible via {@link #choosePrivateKeyAlias} while
94 * Certificate Authority (CA) certificates will be trusted by all
95 * applications through the default {@code X509TrustManager}.
Brian Carlstromb9a07c12011-04-11 09:03:51 -070096 */
Brian Carlstrom93201f52011-06-09 15:05:35 -070097// TODO reference intent for credential installation when public
Brian Carlstromb9a07c12011-04-11 09:03:51 -070098public final class KeyChain {
99
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700100 /**
101 * @hide Also used by KeyChainService implementation
102 */
103 public static final String ACCOUNT_TYPE = "com.android.keychain";
104
105 /**
Kenny Roota3659062014-03-17 16:21:53 -0700106 * Package name for KeyChain chooser.
107 */
108 private static final String KEYCHAIN_PACKAGE = "com.android.keychain";
109
110 /**
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700111 * Action to bring up the KeyChainActivity
112 */
113 private static final String ACTION_CHOOSER = "com.android.keychain.CHOOSER";
114
115 /**
Kenny Root1a88d832014-02-07 09:12:48 -0800116 * Package name for the Certificate Installer.
117 */
118 private static final String CERT_INSTALLER_PACKAGE = "com.android.certinstaller";
119
120 /**
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700121 * Extra for use with {@link #ACTION_CHOOSER}
Brian Carlstromba1a6672011-05-24 21:54:37 -0700122 * @hide Also used by KeyChainActivity implementation
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700123 */
Brian Carlstromba1a6672011-05-24 21:54:37 -0700124 public static final String EXTRA_RESPONSE = "response";
125
126 /**
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700127 * Extra for use with {@link #ACTION_CHOOSER}
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700128 * @hide Also used by KeyChainActivity implementation
129 */
Robin Lee39087b12015-05-05 15:57:17 +0100130 public static final String EXTRA_URI = "uri";
Robin Lee3798ed52015-02-03 17:55:31 +0000131
132 /**
133 * Extra for use with {@link #ACTION_CHOOSER}
134 * @hide Also used by KeyChainActivity implementation
135 */
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700136 public static final String EXTRA_ALIAS = "alias";
137
138 /**
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700139 * Extra for use with {@link #ACTION_CHOOSER}
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700140 * @hide Also used by KeyChainActivity implementation
141 */
142 public static final String EXTRA_SENDER = "sender";
143
144 /**
Selim Gurun93ba4fe2012-02-14 11:48:49 -0800145 * Action to bring up the CertInstaller.
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700146 */
147 private static final String ACTION_INSTALL = "android.credentials.INSTALL";
148
149 /**
150 * Optional extra to specify a {@code String} credential name on
151 * the {@code Intent} returned by {@link #createInstallIntent}.
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700152 */
153 // Compatible with old com.android.certinstaller.CredentialHelper.CERT_NAME_KEY
154 public static final String EXTRA_NAME = "name";
155
156 /**
157 * Optional extra to specify an X.509 certificate to install on
158 * the {@code Intent} returned by {@link #createInstallIntent}.
159 * The extra value should be a PEM or ASN.1 DER encoded {@code
160 * byte[]}. An {@link X509Certificate} can be converted to DER
161 * encoded bytes with {@link X509Certificate#getEncoded}.
162 *
163 * <p>{@link #EXTRA_NAME} may be used to provide a default alias
164 * name for the installed certificate.
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700165 */
166 // Compatible with old android.security.Credentials.CERTIFICATE
167 public static final String EXTRA_CERTIFICATE = "CERT";
168
169 /**
170 * Optional extra for use with the {@code Intent} returned by
171 * {@link #createInstallIntent} to specify a PKCS#12 key store to
172 * install. The extra value should be a {@code byte[]}. The bytes
173 * may come from an external source or be generated with {@link
Brian Carlstromca43c452011-06-29 18:53:17 -0700174 * java.security.KeyStore#store} on a "PKCS12" instance.
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700175 *
176 * <p>The user will be prompted for the password to load the key store.
177 *
178 * <p>The key store will be scanned for {@link
179 * java.security.KeyStore.PrivateKeyEntry} entries and both the
180 * private key and associated certificate chain will be installed.
181 *
182 * <p>{@link #EXTRA_NAME} may be used to provide a default alias
183 * name for the installed credentials.
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700184 */
185 // Compatible with old android.security.Credentials.PKCS12
186 public static final String EXTRA_PKCS12 = "PKCS12";
187
Selim Gurun93ba4fe2012-02-14 11:48:49 -0800188 /**
Selim Gurun93ba4fe2012-02-14 11:48:49 -0800189 * Broadcast Action: Indicates the trusted storage has changed. Sent when
190 * one of this happens:
191 *
192 * <ul>
193 * <li>a new CA is added,
194 * <li>an existing CA is removed or disabled,
195 * <li>a disabled CA is enabled,
196 * <li>trusted storage is reset (all user certs are cleared),
197 * <li>when permission to access a private key is changed.
198 * </ul>
Chad Brubaker4de59ef2016-05-02 13:17:31 -0700199 *
Chad Brubakerdbf01c12016-07-25 14:54:39 -0700200 * @deprecated Use {@link #ACTION_KEYCHAIN_CHANGED}, {@link #ACTION_TRUST_STORE_CHANGED} or
Chad Brubaker721afae2016-07-08 11:06:09 -0700201 * {@link #ACTION_KEY_ACCESS_CHANGED}. Apps that target a version higher than
Chad Brubaker8b651bf2017-03-23 09:26:09 -0700202 * {@link Build.VERSION_CODES#N_MR1} will only receive this broadcast if they register for it
203 * at runtime.
Selim Gurun93ba4fe2012-02-14 11:48:49 -0800204 */
Jeff Sharkey0f3f60b2017-04-24 18:06:20 -0600205 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Selim Gurun93ba4fe2012-02-14 11:48:49 -0800206 public static final String ACTION_STORAGE_CHANGED = "android.security.STORAGE_CHANGED";
207
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700208 /**
Chad Brubaker4de59ef2016-05-02 13:17:31 -0700209 * Broadcast Action: Indicates the contents of the keychain has changed. Sent when a KeyChain
210 * entry is added, modified or removed.
211 */
Jeff Sharkey0f3f60b2017-04-24 18:06:20 -0600212 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Chad Brubaker4de59ef2016-05-02 13:17:31 -0700213 public static final String ACTION_KEYCHAIN_CHANGED = "android.security.action.KEYCHAIN_CHANGED";
214
215 /**
216 * Broadcast Action: Indicates the contents of the trusted certificate store has changed. Sent
217 * when one the following occurs:
218 *
219 * <ul>
220 * <li>A pre-installed CA is disabled or re-enabled</li>
221 * <li>A CA is added or removed from the trust store</li>
222 * </ul>
223 */
Jeff Sharkey0f3f60b2017-04-24 18:06:20 -0600224 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Chad Brubaker4de59ef2016-05-02 13:17:31 -0700225 public static final String ACTION_TRUST_STORE_CHANGED =
226 "android.security.action.TRUST_STORE_CHANGED";
227
228 /**
229 * Broadcast Action: Indicates that the access permissions for a private key have changed.
230 *
231 */
Jeff Sharkey0f3f60b2017-04-24 18:06:20 -0600232 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Chad Brubaker4de59ef2016-05-02 13:17:31 -0700233 public static final String ACTION_KEY_ACCESS_CHANGED =
234 "android.security.action.KEY_ACCESS_CHANGED";
235
236 /**
237 * Used as a String extra field in {@link #ACTION_KEY_ACCESS_CHANGED} to supply the alias of
238 * the key.
239 */
240 public static final String EXTRA_KEY_ALIAS = "android.security.extra.KEY_ALIAS";
241
242 /**
243 * Used as a boolean extra field in {@link #ACTION_KEY_ACCESS_CHANGED} to supply if the key is
244 * accessible to the application.
245 */
246 public static final String EXTRA_KEY_ACCESSIBLE = "android.security.extra.KEY_ACCESSIBLE";
247
248 /**
Eran Messeri61692392018-03-26 16:43:14 +0100249 * Indicates that a call to {@link #generateKeyPair} was successful.
250 * @hide
251 */
252 public static final int KEY_GEN_SUCCESS = 0;
253
254 /**
255 * An alias was missing from the key specifications when calling {@link #generateKeyPair}.
256 * @hide
257 */
258 public static final int KEY_GEN_MISSING_ALIAS = 1;
259
260 /**
261 * A key attestation challenge was provided to {@link #generateKeyPair}, but it shouldn't
262 * have been provided.
263 * @hide
264 */
265 public static final int KEY_GEN_SUPERFLUOUS_ATTESTATION_CHALLENGE = 2;
266
267 /**
268 * Algorithm not supported by {@link #generateKeyPair}
269 * @hide
270 */
271 public static final int KEY_GEN_NO_SUCH_ALGORITHM = 3;
272
273 /**
274 * Invalid algorithm parameters when calling {@link #generateKeyPair}
275 * @hide
276 */
277 public static final int KEY_GEN_INVALID_ALGORITHM_PARAMETERS = 4;
278
279 /**
280 * Keystore is not available when calling {@link #generateKeyPair}
281 * @hide
282 */
283 public static final int KEY_GEN_NO_KEYSTORE_PROVIDER = 5;
284
285 /**
Eran Messeri607a9952018-07-09 17:58:26 +0100286 * StrongBox unavailable when calling {@link #generateKeyPair}
287 * @hide
288 */
289 public static final int KEY_GEN_STRONGBOX_UNAVAILABLE = 6;
290
291 /**
Eran Messeri61692392018-03-26 16:43:14 +0100292 * General failure while calling {@link #generateKeyPair}
293 * @hide
294 */
Eran Messeri607a9952018-07-09 17:58:26 +0100295 public static final int KEY_GEN_FAILURE = 7;
Eran Messeri61692392018-03-26 16:43:14 +0100296
297 /**
298 * Successful call to {@link #attestKey}
299 * @hide
300 */
301 public static final int KEY_ATTESTATION_SUCCESS = 0;
302
303 /**
304 * Attestation challenge missing when calling {@link #attestKey}
305 * @hide
306 */
307 public static final int KEY_ATTESTATION_MISSING_CHALLENGE = 1;
308
309 /**
310 * The caller requested Device ID attestation when calling {@link #attestKey}, but has no
311 * permissions to get device identifiers.
312 * @hide
313 */
314 public static final int KEY_ATTESTATION_CANNOT_COLLECT_DATA = 2;
315
316 /**
317 * The underlying hardware does not support Device ID attestation or cannot attest to the
318 * identifiers that are stored on the device. This indicates permanent inability
319 * to get attestation records on the device.
320 * @hide
321 */
322 public static final int KEY_ATTESTATION_CANNOT_ATTEST_IDS = 3;
323
324 /**
325 * General failure when calling {@link #attestKey}
326 * @hide
327 */
328 public static final int KEY_ATTESTATION_FAILURE = 4;
329
330 /**
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700331 * Returns an {@code Intent} that can be used for credential
332 * installation. The intent may be used without any extras, in
333 * which case the user will be able to install credentials from
334 * their own source.
335 *
336 * <p>Alternatively, {@link #EXTRA_CERTIFICATE} or {@link
337 * #EXTRA_PKCS12} maybe used to specify the bytes of an X.509
338 * certificate or a PKCS#12 key store for installation. These
Brian Carlstromca43c452011-06-29 18:53:17 -0700339 * extras may be combined with {@link #EXTRA_NAME} to provide a
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700340 * default alias name for credentials being installed.
341 *
342 * <p>When used with {@link Activity#startActivityForResult},
343 * {@link Activity#RESULT_OK} will be returned if a credential was
344 * successfully installed, otherwise {@link
345 * Activity#RESULT_CANCELED} will be returned.
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700346 */
Alex Klyubin54bb1592015-05-11 12:30:03 -0700347 @NonNull
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700348 public static Intent createInstallIntent() {
349 Intent intent = new Intent(ACTION_INSTALL);
Kenny Root1a88d832014-02-07 09:12:48 -0800350 intent.setClassName(CERT_INSTALLER_PACKAGE,
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700351 "com.android.certinstaller.CertInstallerMain");
352 return intent;
353 }
354
355 /**
Brian Carlstromba1a6672011-05-24 21:54:37 -0700356 * Launches an {@code Activity} for the user to select the alias
357 * for a private key and certificate pair for authentication. The
358 * selected alias or null will be returned via the
Brian Carlstrom93201f52011-06-09 15:05:35 -0700359 * KeyChainAliasCallback callback.
360 *
Eran Messeri0bc50f92018-06-01 16:03:39 +0100361 * <p>A device policy controller (as a device or profile owner) can
362 * intercept the request before the activity is shown, to pick a
363 * specific private key alias by implementing
364 * {@link android.app.admin.DeviceAdminReceiver#onChoosePrivateKeyAlias
365 * onChoosePrivateKeyAlias}.
Robin Lee3798ed52015-02-03 17:55:31 +0000366 *
367 * <p>{@code keyTypes} and {@code issuers} may be used to
368 * highlight suggested choices to the user, although to cope with
369 * sometimes erroneous values provided by servers, the user may be
370 * able to override these suggestions.
371 *
372 * <p>{@code host} and {@code port} may be used to give the user
373 * more context about the server requesting the credentials.
374 *
Eran Messeri0bc50f92018-06-01 16:03:39 +0100375 * <p>{@code alias} allows the caller to preselect an existing
Robin Lee3798ed52015-02-03 17:55:31 +0000376 * alias which will still be subject to user confirmation.
377 *
378 * @param activity The {@link Activity} context to use for
379 * launching the new sub-Activity to prompt the user to select
380 * a private key; used only to call startActivity(); must not
381 * be null.
382 * @param response Callback to invoke when the request completes;
Mike Harriscd0eb712018-04-26 15:20:10 -0700383 * must not be null.
Robin Lee3798ed52015-02-03 17:55:31 +0000384 * @param keyTypes The acceptable types of asymmetric keys such as
Mike Harriscd0eb712018-04-26 15:20:10 -0700385 * "RSA" or "DSA", or null.
Robin Lee3798ed52015-02-03 17:55:31 +0000386 * @param issuers The acceptable certificate issuers for the
387 * certificate matching the private key, or null.
388 * @param host The host name of the server requesting the
389 * certificate, or null if unavailable.
390 * @param port The port number of the server requesting the
391 * certificate, or -1 if unavailable.
392 * @param alias The alias to preselect if available, or null if
393 * unavailable.
394 */
Alex Klyubin54bb1592015-05-11 12:30:03 -0700395 public static void choosePrivateKeyAlias(@NonNull Activity activity,
396 @NonNull KeyChainAliasCallback response,
Mike Harriscd0eb712018-04-26 15:20:10 -0700397 @Nullable @KeyProperties.KeyAlgorithmEnum String[] keyTypes,
398 @Nullable Principal[] issuers,
Alex Klyubin54bb1592015-05-11 12:30:03 -0700399 @Nullable String host, int port, @Nullable String alias) {
Robin Lee39087b12015-05-05 15:57:17 +0100400 Uri uri = null;
401 if (host != null) {
402 uri = new Uri.Builder()
403 .authority(host + (port != -1 ? ":" + port : ""))
404 .build();
405 }
406 choosePrivateKeyAlias(activity, response, keyTypes, issuers, uri, alias);
Robin Lee3798ed52015-02-03 17:55:31 +0000407 }
408
409 /**
410 * Launches an {@code Activity} for the user to select the alias
411 * for a private key and certificate pair for authentication. The
412 * selected alias or null will be returned via the
413 * KeyChainAliasCallback callback.
414 *
Eran Messeri0bc50f92018-06-01 16:03:39 +0100415 * <p>A device policy controller (as a device or profile owner) can
416 * intercept the request before the activity is shown, to pick a
417 * specific private key alias by implementing
418 * {@link android.app.admin.DeviceAdminReceiver#onChoosePrivateKeyAlias
419 * onChoosePrivateKeyAlias}.
Robin Lee3798ed52015-02-03 17:55:31 +0000420 *
Brian Carlstrom93201f52011-06-09 15:05:35 -0700421 * <p>{@code keyTypes} and {@code issuers} may be used to
422 * highlight suggested choices to the user, although to cope with
423 * sometimes erroneous values provided by servers, the user may be
424 * able to override these suggestions.
425 *
Eran Messeri0bc50f92018-06-01 16:03:39 +0100426 * <p>{@code uri} may be used to give the user more context about
427 * the server requesting the credentials.
Brian Carlstrom93201f52011-06-09 15:05:35 -0700428 *
Eran Messeri0bc50f92018-06-01 16:03:39 +0100429 * <p>{@code alias} allows the caller to preselect an existing
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700430 * alias which will still be subject to user confirmation.
431 *
Brian Carlstrom93201f52011-06-09 15:05:35 -0700432 * @param activity The {@link Activity} context to use for
433 * launching the new sub-Activity to prompt the user to select
434 * a private key; used only to call startActivity(); must not
435 * be null.
436 * @param response Callback to invoke when the request completes;
Mike Harriscd0eb712018-04-26 15:20:10 -0700437 * must not be null.
Brian Carlstrom93201f52011-06-09 15:05:35 -0700438 * @param keyTypes The acceptable types of asymmetric keys such as
Mike Harriscd0eb712018-04-26 15:20:10 -0700439 * "EC" or "RSA", or null.
Brian Carlstrom93201f52011-06-09 15:05:35 -0700440 * @param issuers The acceptable certificate issuers for the
441 * certificate matching the private key, or null.
Robin Lee39087b12015-05-05 15:57:17 +0100442 * @param uri The full URI the server is requesting the certificate
Robin Lee3798ed52015-02-03 17:55:31 +0000443 * for, or null if unavailable.
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700444 * @param alias The alias to preselect if available, or null if
445 * unavailable.
Brian Carlstromba1a6672011-05-24 21:54:37 -0700446 */
Alex Klyubin54bb1592015-05-11 12:30:03 -0700447 public static void choosePrivateKeyAlias(@NonNull Activity activity,
448 @NonNull KeyChainAliasCallback response,
Mike Harriscd0eb712018-04-26 15:20:10 -0700449 @Nullable @KeyProperties.KeyAlgorithmEnum String[] keyTypes,
450 @Nullable Principal[] issuers,
Robin Lee39087b12015-05-05 15:57:17 +0100451 @Nullable Uri uri, @Nullable String alias) {
Brian Carlstrom93201f52011-06-09 15:05:35 -0700452 /*
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700453 * TODO currently keyTypes, issuers are unused. They are meant
454 * to follow the semantics and purpose of X509KeyManager
455 * method arguments.
Brian Carlstrom93201f52011-06-09 15:05:35 -0700456 *
457 * keyTypes would allow the list to be filtered and typically
458 * will be set correctly by the server. In practice today,
Alex Klyubincd2329d2015-01-14 16:45:51 -0800459 * most all users will want only RSA or EC, and usually
Brian Carlstrom93201f52011-06-09 15:05:35 -0700460 * only a small number of certs will be available.
461 *
462 * issuers is typically not useful. Some servers historically
463 * will send the entire list of public CAs known to the
464 * server. Others will send none. If this is used, if there
465 * are no matches after applying the constraint, it should be
466 * ignored.
Brian Carlstrom93201f52011-06-09 15:05:35 -0700467 */
Brian Carlstromba1a6672011-05-24 21:54:37 -0700468 if (activity == null) {
469 throw new NullPointerException("activity == null");
470 }
471 if (response == null) {
472 throw new NullPointerException("response == null");
473 }
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700474 Intent intent = new Intent(ACTION_CHOOSER);
Kenny Roota3659062014-03-17 16:21:53 -0700475 intent.setPackage(KEYCHAIN_PACKAGE);
Fred Quintanaab8b84a2011-07-13 14:55:39 -0700476 intent.putExtra(EXTRA_RESPONSE, new AliasResponse(response));
Robin Lee39087b12015-05-05 15:57:17 +0100477 intent.putExtra(EXTRA_URI, uri);
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700478 intent.putExtra(EXTRA_ALIAS, alias);
479 // the PendingIntent is used to get calling package name
480 intent.putExtra(EXTRA_SENDER, PendingIntent.getActivity(activity, 0, new Intent(), 0));
Brian Carlstromba1a6672011-05-24 21:54:37 -0700481 activity.startActivity(intent);
482 }
483
Brian Carlstrom93201f52011-06-09 15:05:35 -0700484 private static class AliasResponse extends IKeyChainAliasCallback.Stub {
Brian Carlstrom93201f52011-06-09 15:05:35 -0700485 private final KeyChainAliasCallback keyChainAliasResponse;
Fred Quintanaab8b84a2011-07-13 14:55:39 -0700486 private AliasResponse(KeyChainAliasCallback keyChainAliasResponse) {
Brian Carlstromba1a6672011-05-24 21:54:37 -0700487 this.keyChainAliasResponse = keyChainAliasResponse;
488 }
489 @Override public void alias(String alias) {
Fred Quintanaab8b84a2011-07-13 14:55:39 -0700490 keyChainAliasResponse.alias(alias);
Brian Carlstromba1a6672011-05-24 21:54:37 -0700491 }
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700492 }
493
494 /**
Brian Carlstromba1a6672011-05-24 21:54:37 -0700495 * Returns the {@code PrivateKey} for the requested alias, or null
Robin Lee3a435f02015-12-21 12:06:04 +0000496 * if there is no result.
Brian Carlstrom93201f52011-06-09 15:05:35 -0700497 *
Robin Lee59e3baa2015-06-30 10:48:06 -0700498 * <p> This method may block while waiting for a connection to another process, and must never
499 * be called from the main thread.
Robin Leeda236182016-08-12 12:46:28 +0100500 * <p> As {@link Activity} and {@link Service} contexts are short-lived and can be destroyed
501 * at any time from the main thread, it is safer to rely on a long-lived context such as one
502 * returned from {@link Context#getApplicationContext()}.
Robin Lee59e3baa2015-06-30 10:48:06 -0700503 *
504 * @param alias The alias of the desired private key, typically returned via
505 * {@link KeyChainAliasCallback#alias}.
Brian Carlstrom93201f52011-06-09 15:05:35 -0700506 * @throws KeyChainException if the alias was valid but there was some problem accessing it.
Robin Lee59e3baa2015-06-30 10:48:06 -0700507 * @throws IllegalStateException if called from the main thread.
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700508 */
Robin Lee59e3baa2015-06-30 10:48:06 -0700509 @Nullable @WorkerThread
Alex Klyubin54bb1592015-05-11 12:30:03 -0700510 public static PrivateKey getPrivateKey(@NonNull Context context, @NonNull String alias)
Brian Carlstrom93201f52011-06-09 15:05:35 -0700511 throws KeyChainException, InterruptedException {
Eran Messeri23c438d2017-11-23 17:20:52 +0000512 KeyPair keyPair = getKeyPair(context, alias);
513 if (keyPair != null) {
514 return keyPair.getPrivate();
515 }
516
517 return null;
518 }
519
520 /** @hide */
521 @Nullable @WorkerThread
522 public static KeyPair getKeyPair(@NonNull Context context, @NonNull String alias)
523 throws KeyChainException, InterruptedException {
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700524 if (alias == null) {
525 throw new NullPointerException("alias == null");
526 }
Shawn Willdendea66142016-11-16 06:01:06 -0700527 if (context == null) {
528 throw new NullPointerException("context == null");
529 }
Robin Lee28d68b12016-07-22 16:32:32 +0100530
531 final String keyId;
532 try (KeyChainConnection keyChainConnection = bind(context.getApplicationContext())) {
533 keyId = keyChainConnection.getService().requestPrivateKey(alias);
Brian Carlstrom93201f52011-06-09 15:05:35 -0700534 } catch (RemoteException e) {
535 throw new KeyChainException(e);
536 } catch (RuntimeException e) {
537 // only certain RuntimeExceptions can be propagated across the IKeyChainService call
538 throw new KeyChainException(e);
Robin Lee28d68b12016-07-22 16:32:32 +0100539 }
540
541 if (keyId == null) {
542 return null;
543 } else {
544 try {
Eran Messeri23c438d2017-11-23 17:20:52 +0000545 return AndroidKeyStoreProvider.loadAndroidKeyStoreKeyPairFromKeystore(
Robin Lee28d68b12016-07-22 16:32:32 +0100546 KeyStore.getInstance(), keyId, KeyStore.UID_SELF);
547 } catch (RuntimeException | UnrecoverableKeyException e) {
548 throw new KeyChainException(e);
549 }
Brian Carlstromba1a6672011-05-24 21:54:37 -0700550 }
551 }
552
553 /**
554 * Returns the {@code X509Certificate} chain for the requested
Rubin Xub4365912016-03-23 12:13:22 +0000555 * alias, or null if there is no result.
556 * <p>
557 * <strong>Note:</strong> If a certificate chain was explicitly specified when the alias was
558 * installed, this method will return that chain. If only the client certificate was specified
559 * at the installation time, this method will try to build a certificate chain using all
560 * available trust anchors (preinstalled and user-added).
Brian Carlstrom93201f52011-06-09 15:05:35 -0700561 *
Robin Lee59e3baa2015-06-30 10:48:06 -0700562 * <p> This method may block while waiting for a connection to another process, and must never
563 * be called from the main thread.
Robin Leeda236182016-08-12 12:46:28 +0100564 * <p> As {@link Activity} and {@link Service} contexts are short-lived and can be destroyed
565 * at any time from the main thread, it is safer to rely on a long-lived context such as one
566 * returned from {@link Context#getApplicationContext()}.
Robin Lee59e3baa2015-06-30 10:48:06 -0700567 *
Brian Carlstrom93201f52011-06-09 15:05:35 -0700568 * @param alias The alias of the desired certificate chain, typically
569 * returned via {@link KeyChainAliasCallback#alias}.
570 * @throws KeyChainException if the alias was valid but there was some problem accessing it.
Robin Lee59e3baa2015-06-30 10:48:06 -0700571 * @throws IllegalStateException if called from the main thread.
Brian Carlstromba1a6672011-05-24 21:54:37 -0700572 */
Robin Lee59e3baa2015-06-30 10:48:06 -0700573 @Nullable @WorkerThread
Alex Klyubin54bb1592015-05-11 12:30:03 -0700574 public static X509Certificate[] getCertificateChain(@NonNull Context context,
575 @NonNull String alias) throws KeyChainException, InterruptedException {
Brian Carlstromba1a6672011-05-24 21:54:37 -0700576 if (alias == null) {
577 throw new NullPointerException("alias == null");
578 }
Kenny Root0150e482013-02-13 15:22:50 -0800579
Robin Lee28d68b12016-07-22 16:32:32 +0100580 final byte[] certificateBytes;
581 final byte[] certChainBytes;
582 try (KeyChainConnection keyChainConnection = bind(context.getApplicationContext())) {
583 IKeyChainService keyChainService = keyChainConnection.getService();
584 certificateBytes = keyChainService.getCertificate(alias);
Kenny Root0150e482013-02-13 15:22:50 -0800585 if (certificateBytes == null) {
586 return null;
587 }
Robin Lee28d68b12016-07-22 16:32:32 +0100588 certChainBytes = keyChainService.getCaCertificates(alias);
589 } catch (RemoteException e) {
590 throw new KeyChainException(e);
591 } catch (RuntimeException e) {
592 // only certain RuntimeExceptions can be propagated across the IKeyChainService call
593 throw new KeyChainException(e);
594 }
595
596 try {
Rubin Xub4365912016-03-23 12:13:22 +0000597 X509Certificate leafCert = toCertificate(certificateBytes);
Rubin Xub4365912016-03-23 12:13:22 +0000598 // If the keypair is installed with a certificate chain by either
599 // DevicePolicyManager.installKeyPair or CertInstaller, return that chain.
600 if (certChainBytes != null && certChainBytes.length != 0) {
601 Collection<X509Certificate> chain = toCertificates(certChainBytes);
602 ArrayList<X509Certificate> fullChain = new ArrayList<>(chain.size() + 1);
603 fullChain.add(leafCert);
604 fullChain.addAll(chain);
605 return fullChain.toArray(new X509Certificate[fullChain.size()]);
606 } else {
607 // If there isn't a certificate chain, either due to a pre-existing keypair
608 // installed before N, or no chain is explicitly installed under the new logic,
609 // fall back to old behavior of constructing the chain from trusted credentials.
610 //
611 // This logic exists to maintain old behaviour for already installed keypair, at
612 // the cost of potentially returning extra certificate chain for new clients who
613 // explicitly installed only the client certificate without a chain. The latter
614 // case is actually no different from pre-N behaviour of getCertificateChain(),
615 // in that sense this change introduces no regression. Besides the returned chain
616 // is still valid so the consumer of the chain should have no problem verifying it.
617 TrustedCertificateStore store = new TrustedCertificateStore();
618 List<X509Certificate> chain = store.getCertificateChain(leafCert);
619 return chain.toArray(new X509Certificate[chain.size()]);
620 }
Robin Lee28d68b12016-07-22 16:32:32 +0100621 } catch (CertificateException | RuntimeException e) {
Kenny Rootcfba6a02013-05-06 15:00:58 -0700622 throw new KeyChainException(e);
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700623 }
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700624 }
625
Kenny Rootbf556ac2013-04-01 15:10:22 -0700626 /**
627 * Returns {@code true} if the current device's {@code KeyChain} supports a
628 * specific {@code PrivateKey} type indicated by {@code algorithm} (e.g.,
629 * "RSA").
630 */
Alex Klyubin4d5443f2015-05-06 15:43:52 -0700631 public static boolean isKeyAlgorithmSupported(
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700632 @NonNull @KeyProperties.KeyAlgorithmEnum String algorithm) {
Kenny Rootb91773b2013-09-05 13:03:16 -0700633 final String algUpper = algorithm.toUpperCase(Locale.US);
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700634 return KeyProperties.KEY_ALGORITHM_EC.equals(algUpper)
635 || KeyProperties.KEY_ALGORITHM_RSA.equals(algUpper);
Kenny Rootbf556ac2013-04-01 15:10:22 -0700636 }
637
638 /**
639 * Returns {@code true} if the current device's {@code KeyChain} binds any
640 * {@code PrivateKey} of the given {@code algorithm} to the device once
641 * imported or generated. This can be used to tell if there is special
642 * hardware support that can be used to bind keys to the device in a way
643 * that makes it non-exportable.
Alex Klyubin469cbf52015-06-04 12:36:27 -0700644 *
645 * @deprecated Whether the key is bound to the secure hardware is known only
646 * once the key has been imported. To find out, use:
647 * <pre>{@code
648 * PrivateKey key = ...; // private key from KeyChain
649 *
650 * KeyFactory keyFactory =
651 * KeyFactory.getInstance(key.getAlgorithm(), "AndroidKeyStore");
652 * KeyInfo keyInfo = keyFactory.getKeySpec(key, KeyInfo.class);
Neil Fuller71fbb812015-11-30 09:51:33 +0000653 * if (keyInfo.isInsideSecureHardware()) {
Alex Klyubin469cbf52015-06-04 12:36:27 -0700654 * // The key is bound to the secure hardware of this Android
Neil Fuller71fbb812015-11-30 09:51:33 +0000655 * }}</pre>
Kenny Rootbf556ac2013-04-01 15:10:22 -0700656 */
Alex Klyubin469cbf52015-06-04 12:36:27 -0700657 @Deprecated
Alex Klyubin4d5443f2015-05-06 15:43:52 -0700658 public static boolean isBoundKeyAlgorithm(
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700659 @NonNull @KeyProperties.KeyAlgorithmEnum String algorithm) {
Kenny Root5b7e90a2013-04-02 11:23:41 -0700660 if (!isKeyAlgorithmSupported(algorithm)) {
Kenny Rootbf556ac2013-04-01 15:10:22 -0700661 return false;
662 }
663
Kenny Rootb91773b2013-09-05 13:03:16 -0700664 return KeyStore.getInstance().isHardwareBacked(algorithm);
Kenny Rootbf556ac2013-04-01 15:10:22 -0700665 }
666
Zoltan Szatmary-Banf0ae1352014-08-18 10:48:33 +0100667 /** @hide */
Alex Klyubin54bb1592015-05-11 12:30:03 -0700668 @NonNull
669 public static X509Certificate toCertificate(@NonNull byte[] bytes) {
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700670 if (bytes == null) {
Brian Carlstrom8e9929c2011-05-17 00:40:28 -0700671 throw new IllegalArgumentException("bytes == null");
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700672 }
673 try {
674 CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
675 Certificate cert = certFactory.generateCertificate(new ByteArrayInputStream(bytes));
676 return (X509Certificate) cert;
677 } catch (CertificateException e) {
678 throw new AssertionError(e);
679 }
680 }
681
Rubin Xub4365912016-03-23 12:13:22 +0000682 /** @hide */
683 @NonNull
684 public static Collection<X509Certificate> toCertificates(@NonNull byte[] bytes) {
685 if (bytes == null) {
686 throw new IllegalArgumentException("bytes == null");
687 }
688 try {
689 CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
690 return (Collection<X509Certificate>) certFactory.generateCertificates(
691 new ByteArrayInputStream(bytes));
692 } catch (CertificateException e) {
693 throw new AssertionError(e);
694 }
695 }
696
Brian Carlstromd7524722011-05-17 16:20:36 -0700697 /**
698 * @hide for reuse by CertInstaller and Settings.
699 * @see KeyChain#bind
700 */
Robin Lee7f5c91c2017-02-08 21:27:02 +0000701 public static class KeyChainConnection implements Closeable {
Brian Carlstromd7524722011-05-17 16:20:36 -0700702 private final Context context;
703 private final ServiceConnection serviceConnection;
704 private final IKeyChainService service;
phweisse375fc42017-04-19 20:15:06 +0200705 protected KeyChainConnection(Context context,
706 ServiceConnection serviceConnection,
707 IKeyChainService service) {
Brian Carlstromd7524722011-05-17 16:20:36 -0700708 this.context = context;
709 this.serviceConnection = serviceConnection;
710 this.service = service;
711 }
712 @Override public void close() {
713 context.unbindService(serviceConnection);
714 }
715 public IKeyChainService getService() {
716 return service;
717 }
718 }
719
720 /**
721 * @hide for reuse by CertInstaller and Settings.
722 *
723 * Caller should call unbindService on the result when finished.
724 */
Robin Lee59e3baa2015-06-30 10:48:06 -0700725 @WorkerThread
Alex Klyubin54bb1592015-05-11 12:30:03 -0700726 public static KeyChainConnection bind(@NonNull Context context) throws InterruptedException {
Robin Lee306fe082014-06-19 14:04:24 +0000727 return bindAsUser(context, Process.myUserHandle());
728 }
729
730 /**
731 * @hide
732 */
Robin Lee59e3baa2015-06-30 10:48:06 -0700733 @WorkerThread
Alex Klyubin54bb1592015-05-11 12:30:03 -0700734 public static KeyChainConnection bindAsUser(@NonNull Context context, UserHandle user)
Robin Lee306fe082014-06-19 14:04:24 +0000735 throws InterruptedException {
Brian Carlstromd7524722011-05-17 16:20:36 -0700736 if (context == null) {
737 throw new NullPointerException("context == null");
738 }
739 ensureNotOnMainThread(context);
740 final BlockingQueue<IKeyChainService> q = new LinkedBlockingQueue<IKeyChainService>(1);
741 ServiceConnection keyChainServiceConnection = new ServiceConnection() {
Fred Quintanaab8b84a2011-07-13 14:55:39 -0700742 volatile boolean mConnectedAtLeastOnce = false;
Brian Carlstromd7524722011-05-17 16:20:36 -0700743 @Override public void onServiceConnected(ComponentName name, IBinder service) {
Fred Quintanaab8b84a2011-07-13 14:55:39 -0700744 if (!mConnectedAtLeastOnce) {
745 mConnectedAtLeastOnce = true;
746 try {
Jeff Sharkey0a17db12016-11-04 11:23:46 -0600747 q.put(IKeyChainService.Stub.asInterface(Binder.allowBlocking(service)));
Fred Quintanaab8b84a2011-07-13 14:55:39 -0700748 } catch (InterruptedException e) {
749 // will never happen, since the queue starts with one available slot
750 }
Brian Carlstromd7524722011-05-17 16:20:36 -0700751 }
752 }
753 @Override public void onServiceDisconnected(ComponentName name) {}
754 };
Maggie Benthallda51e682013-08-08 22:35:44 -0400755 Intent intent = new Intent(IKeyChainService.class.getName());
756 ComponentName comp = intent.resolveSystemService(context.getPackageManager(), 0);
757 intent.setComponent(comp);
Robin Lee21bcbc52016-02-29 18:55:35 +0000758 if (comp == null || !context.bindServiceAsUser(
759 intent, keyChainServiceConnection, Context.BIND_AUTO_CREATE, user)) {
Brian Carlstromd7524722011-05-17 16:20:36 -0700760 throw new AssertionError("could not bind to KeyChainService");
761 }
762 return new KeyChainConnection(context, keyChainServiceConnection, q.take());
763 }
764
Alex Klyubin54bb1592015-05-11 12:30:03 -0700765 private static void ensureNotOnMainThread(@NonNull Context context) {
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700766 Looper looper = Looper.myLooper();
Brian Carlstrom8e9929c2011-05-17 00:40:28 -0700767 if (looper != null && looper == context.getMainLooper()) {
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700768 throw new IllegalStateException(
769 "calling this from your main thread can lead to deadlock");
770 }
771 }
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700772}