blob: c180197d6f8423f5c475a574a2894afefd4f58c7 [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;
Max Bires13f98ce2018-11-02 10:50:40 -070039import android.security.keystore.KeyPermanentlyInvalidatedException;
Alex Klyubin3f8d4d82015-05-13 09:15:00 -070040import android.security.keystore.KeyProperties;
41
Brian Carlstromb9a07c12011-04-11 09:03:51 -070042import java.io.ByteArrayInputStream;
Brian Carlstromd7524722011-05-17 16:20:36 -070043import java.io.Closeable;
Eran Messeri9ccec4d2018-08-24 15:29:05 +010044import java.io.Serializable;
Eran Messeri23c438d2017-11-23 17:20:52 +000045import java.security.KeyPair;
Brian Carlstrom93201f52011-06-09 15:05:35 -070046import java.security.Principal;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070047import java.security.PrivateKey;
Alex Klyubin4a0ff7c2015-06-09 13:25:20 -070048import java.security.UnrecoverableKeyException;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070049import java.security.cert.Certificate;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070050import java.security.cert.CertificateException;
51import java.security.cert.CertificateFactory;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070052import java.security.cert.X509Certificate;
Rubin Xub4365912016-03-23 12:13:22 +000053import java.util.ArrayList;
54import java.util.Collection;
Brian Carlstromdb93b782011-07-01 00:12:17 -070055import java.util.List;
Kenny Rootb91773b2013-09-05 13:03:16 -070056import java.util.Locale;
Brian Carlstrom8e9929c2011-05-17 00:40:28 -070057import java.util.concurrent.BlockingQueue;
58import java.util.concurrent.LinkedBlockingQueue;
Kenny Root5423e682011-11-14 08:43:13 -080059
Eran Messeri9ccec4d2018-08-24 15:29:05 +010060import javax.security.auth.x500.X500Principal;
61
Kenny Root12e75222013-04-23 22:34:24 -070062import com.android.org.conscrypt.TrustedCertificateStore;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070063
64/**
Brian Carlstrom93201f52011-06-09 15:05:35 -070065 * The {@code KeyChain} class provides access to private keys and
66 * their corresponding certificate chains in credential storage.
67 *
68 * <p>Applications accessing the {@code KeyChain} normally go through
69 * these steps:
70 *
71 * <ol>
72 *
73 * <li>Receive a callback from an {@link javax.net.ssl.X509KeyManager
74 * X509KeyManager} that a private key is requested.
75 *
76 * <li>Call {@link #choosePrivateKeyAlias
77 * choosePrivateKeyAlias} to allow the user to select from a
78 * list of currently available private keys and corresponding
79 * certificate chains. The chosen alias will be returned by the
80 * callback {@link KeyChainAliasCallback#alias}, or null if no private
81 * key is available or the user cancels the request.
82 *
83 * <li>Call {@link #getPrivateKey} and {@link #getCertificateChain} to
84 * retrieve the credentials to return to the corresponding {@link
85 * javax.net.ssl.X509KeyManager} callbacks.
86 *
87 * </ol>
88 *
89 * <p>An application may remember the value of a selected alias to
90 * avoid prompting the user with {@link #choosePrivateKeyAlias
91 * choosePrivateKeyAlias} on subsequent connections. If the alias is
92 * no longer valid, null will be returned on lookups using that value
Brian Carlstromca43c452011-06-29 18:53:17 -070093 *
94 * <p>An application can request the installation of private keys and
95 * certificates via the {@code Intent} provided by {@link
96 * #createInstallIntent}. Private keys installed via this {@code
97 * Intent} will be accessible via {@link #choosePrivateKeyAlias} while
98 * Certificate Authority (CA) certificates will be trusted by all
99 * applications through the default {@code X509TrustManager}.
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700100 */
Brian Carlstrom93201f52011-06-09 15:05:35 -0700101// TODO reference intent for credential installation when public
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700102public final class KeyChain {
103
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700104 /**
105 * @hide Also used by KeyChainService implementation
106 */
107 public static final String ACCOUNT_TYPE = "com.android.keychain";
108
109 /**
Kenny Roota3659062014-03-17 16:21:53 -0700110 * Package name for KeyChain chooser.
111 */
112 private static final String KEYCHAIN_PACKAGE = "com.android.keychain";
113
114 /**
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700115 * Action to bring up the KeyChainActivity
116 */
117 private static final String ACTION_CHOOSER = "com.android.keychain.CHOOSER";
118
119 /**
Kenny Root1a88d832014-02-07 09:12:48 -0800120 * Package name for the Certificate Installer.
121 */
122 private static final String CERT_INSTALLER_PACKAGE = "com.android.certinstaller";
123
124 /**
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700125 * Extra for use with {@link #ACTION_CHOOSER}
Brian Carlstromba1a6672011-05-24 21:54:37 -0700126 * @hide Also used by KeyChainActivity implementation
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700127 */
Brian Carlstromba1a6672011-05-24 21:54:37 -0700128 public static final String EXTRA_RESPONSE = "response";
129
130 /**
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700131 * Extra for use with {@link #ACTION_CHOOSER}
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700132 * @hide Also used by KeyChainActivity implementation
133 */
Robin Lee39087b12015-05-05 15:57:17 +0100134 public static final String EXTRA_URI = "uri";
Robin Lee3798ed52015-02-03 17:55:31 +0000135
136 /**
137 * Extra for use with {@link #ACTION_CHOOSER}
138 * @hide Also used by KeyChainActivity implementation
139 */
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700140 public static final String EXTRA_ALIAS = "alias";
141
142 /**
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700143 * Extra for use with {@link #ACTION_CHOOSER}
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700144 * @hide Also used by KeyChainActivity implementation
145 */
146 public static final String EXTRA_SENDER = "sender";
147
148 /**
Eran Messeri9ccec4d2018-08-24 15:29:05 +0100149 * Extra for use with {@link #ACTION_CHOOSER}
150 * @hide Also used by KeyChainActivity implementation
151 */
152 public static final String EXTRA_KEY_TYPES = "key_types";
153
154 /**
155 * Extra for use with {@link #ACTION_CHOOSER}
156 * @hide Also used by KeyChainActivity implementation
157 */
158 public static final String EXTRA_ISSUERS = "issuers";
159
160 /**
Selim Gurun93ba4fe2012-02-14 11:48:49 -0800161 * Action to bring up the CertInstaller.
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700162 */
163 private static final String ACTION_INSTALL = "android.credentials.INSTALL";
164
165 /**
166 * Optional extra to specify a {@code String} credential name on
167 * the {@code Intent} returned by {@link #createInstallIntent}.
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700168 */
169 // Compatible with old com.android.certinstaller.CredentialHelper.CERT_NAME_KEY
170 public static final String EXTRA_NAME = "name";
171
172 /**
173 * Optional extra to specify an X.509 certificate to install on
174 * the {@code Intent} returned by {@link #createInstallIntent}.
175 * The extra value should be a PEM or ASN.1 DER encoded {@code
176 * byte[]}. An {@link X509Certificate} can be converted to DER
177 * encoded bytes with {@link X509Certificate#getEncoded}.
178 *
179 * <p>{@link #EXTRA_NAME} may be used to provide a default alias
180 * name for the installed certificate.
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700181 */
182 // Compatible with old android.security.Credentials.CERTIFICATE
183 public static final String EXTRA_CERTIFICATE = "CERT";
184
185 /**
186 * Optional extra for use with the {@code Intent} returned by
187 * {@link #createInstallIntent} to specify a PKCS#12 key store to
188 * install. The extra value should be a {@code byte[]}. The bytes
189 * may come from an external source or be generated with {@link
Brian Carlstromca43c452011-06-29 18:53:17 -0700190 * java.security.KeyStore#store} on a "PKCS12" instance.
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700191 *
192 * <p>The user will be prompted for the password to load the key store.
193 *
194 * <p>The key store will be scanned for {@link
195 * java.security.KeyStore.PrivateKeyEntry} entries and both the
196 * private key and associated certificate chain will be installed.
197 *
198 * <p>{@link #EXTRA_NAME} may be used to provide a default alias
199 * name for the installed credentials.
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700200 */
201 // Compatible with old android.security.Credentials.PKCS12
202 public static final String EXTRA_PKCS12 = "PKCS12";
203
Selim Gurun93ba4fe2012-02-14 11:48:49 -0800204 /**
Selim Gurun93ba4fe2012-02-14 11:48:49 -0800205 * Broadcast Action: Indicates the trusted storage has changed. Sent when
206 * one of this happens:
207 *
208 * <ul>
209 * <li>a new CA is added,
210 * <li>an existing CA is removed or disabled,
211 * <li>a disabled CA is enabled,
212 * <li>trusted storage is reset (all user certs are cleared),
213 * <li>when permission to access a private key is changed.
214 * </ul>
Chad Brubaker4de59ef2016-05-02 13:17:31 -0700215 *
Chad Brubakerdbf01c12016-07-25 14:54:39 -0700216 * @deprecated Use {@link #ACTION_KEYCHAIN_CHANGED}, {@link #ACTION_TRUST_STORE_CHANGED} or
Chad Brubaker721afae2016-07-08 11:06:09 -0700217 * {@link #ACTION_KEY_ACCESS_CHANGED}. Apps that target a version higher than
Chad Brubaker8b651bf2017-03-23 09:26:09 -0700218 * {@link Build.VERSION_CODES#N_MR1} will only receive this broadcast if they register for it
219 * at runtime.
Selim Gurun93ba4fe2012-02-14 11:48:49 -0800220 */
Jeff Sharkey0f3f60b2017-04-24 18:06:20 -0600221 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Selim Gurun93ba4fe2012-02-14 11:48:49 -0800222 public static final String ACTION_STORAGE_CHANGED = "android.security.STORAGE_CHANGED";
223
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700224 /**
Chad Brubaker4de59ef2016-05-02 13:17:31 -0700225 * Broadcast Action: Indicates the contents of the keychain has changed. Sent when a KeyChain
226 * entry is added, modified or removed.
227 */
Jeff Sharkey0f3f60b2017-04-24 18:06:20 -0600228 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Chad Brubaker4de59ef2016-05-02 13:17:31 -0700229 public static final String ACTION_KEYCHAIN_CHANGED = "android.security.action.KEYCHAIN_CHANGED";
230
231 /**
232 * Broadcast Action: Indicates the contents of the trusted certificate store has changed. Sent
233 * when one the following occurs:
234 *
235 * <ul>
236 * <li>A pre-installed CA is disabled or re-enabled</li>
237 * <li>A CA is added or removed from the trust store</li>
238 * </ul>
239 */
Jeff Sharkey0f3f60b2017-04-24 18:06:20 -0600240 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Chad Brubaker4de59ef2016-05-02 13:17:31 -0700241 public static final String ACTION_TRUST_STORE_CHANGED =
242 "android.security.action.TRUST_STORE_CHANGED";
243
244 /**
245 * Broadcast Action: Indicates that the access permissions for a private key have changed.
246 *
247 */
Jeff Sharkey0f3f60b2017-04-24 18:06:20 -0600248 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Chad Brubaker4de59ef2016-05-02 13:17:31 -0700249 public static final String ACTION_KEY_ACCESS_CHANGED =
250 "android.security.action.KEY_ACCESS_CHANGED";
251
252 /**
253 * Used as a String extra field in {@link #ACTION_KEY_ACCESS_CHANGED} to supply the alias of
254 * the key.
255 */
256 public static final String EXTRA_KEY_ALIAS = "android.security.extra.KEY_ALIAS";
257
258 /**
259 * Used as a boolean extra field in {@link #ACTION_KEY_ACCESS_CHANGED} to supply if the key is
260 * accessible to the application.
261 */
262 public static final String EXTRA_KEY_ACCESSIBLE = "android.security.extra.KEY_ACCESSIBLE";
263
264 /**
Eran Messeri61692392018-03-26 16:43:14 +0100265 * Indicates that a call to {@link #generateKeyPair} was successful.
266 * @hide
267 */
268 public static final int KEY_GEN_SUCCESS = 0;
269
270 /**
271 * An alias was missing from the key specifications when calling {@link #generateKeyPair}.
272 * @hide
273 */
274 public static final int KEY_GEN_MISSING_ALIAS = 1;
275
276 /**
277 * A key attestation challenge was provided to {@link #generateKeyPair}, but it shouldn't
278 * have been provided.
279 * @hide
280 */
281 public static final int KEY_GEN_SUPERFLUOUS_ATTESTATION_CHALLENGE = 2;
282
283 /**
284 * Algorithm not supported by {@link #generateKeyPair}
285 * @hide
286 */
287 public static final int KEY_GEN_NO_SUCH_ALGORITHM = 3;
288
289 /**
290 * Invalid algorithm parameters when calling {@link #generateKeyPair}
291 * @hide
292 */
293 public static final int KEY_GEN_INVALID_ALGORITHM_PARAMETERS = 4;
294
295 /**
296 * Keystore is not available when calling {@link #generateKeyPair}
297 * @hide
298 */
299 public static final int KEY_GEN_NO_KEYSTORE_PROVIDER = 5;
300
301 /**
Eran Messeri607a9952018-07-09 17:58:26 +0100302 * StrongBox unavailable when calling {@link #generateKeyPair}
303 * @hide
304 */
305 public static final int KEY_GEN_STRONGBOX_UNAVAILABLE = 6;
306
307 /**
Eran Messeri61692392018-03-26 16:43:14 +0100308 * General failure while calling {@link #generateKeyPair}
309 * @hide
310 */
Eran Messeri607a9952018-07-09 17:58:26 +0100311 public static final int KEY_GEN_FAILURE = 7;
Eran Messeri61692392018-03-26 16:43:14 +0100312
313 /**
314 * Successful call to {@link #attestKey}
315 * @hide
316 */
317 public static final int KEY_ATTESTATION_SUCCESS = 0;
318
319 /**
320 * Attestation challenge missing when calling {@link #attestKey}
321 * @hide
322 */
323 public static final int KEY_ATTESTATION_MISSING_CHALLENGE = 1;
324
325 /**
326 * The caller requested Device ID attestation when calling {@link #attestKey}, but has no
327 * permissions to get device identifiers.
328 * @hide
329 */
330 public static final int KEY_ATTESTATION_CANNOT_COLLECT_DATA = 2;
331
332 /**
333 * The underlying hardware does not support Device ID attestation or cannot attest to the
334 * identifiers that are stored on the device. This indicates permanent inability
335 * to get attestation records on the device.
336 * @hide
337 */
338 public static final int KEY_ATTESTATION_CANNOT_ATTEST_IDS = 3;
339
340 /**
341 * General failure when calling {@link #attestKey}
342 * @hide
343 */
344 public static final int KEY_ATTESTATION_FAILURE = 4;
345
346 /**
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700347 * Returns an {@code Intent} that can be used for credential
348 * installation. The intent may be used without any extras, in
349 * which case the user will be able to install credentials from
350 * their own source.
351 *
352 * <p>Alternatively, {@link #EXTRA_CERTIFICATE} or {@link
353 * #EXTRA_PKCS12} maybe used to specify the bytes of an X.509
354 * certificate or a PKCS#12 key store for installation. These
Brian Carlstromca43c452011-06-29 18:53:17 -0700355 * extras may be combined with {@link #EXTRA_NAME} to provide a
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700356 * default alias name for credentials being installed.
357 *
358 * <p>When used with {@link Activity#startActivityForResult},
359 * {@link Activity#RESULT_OK} will be returned if a credential was
360 * successfully installed, otherwise {@link
361 * Activity#RESULT_CANCELED} will be returned.
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700362 */
Alex Klyubin54bb1592015-05-11 12:30:03 -0700363 @NonNull
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700364 public static Intent createInstallIntent() {
365 Intent intent = new Intent(ACTION_INSTALL);
Kenny Root1a88d832014-02-07 09:12:48 -0800366 intent.setClassName(CERT_INSTALLER_PACKAGE,
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700367 "com.android.certinstaller.CertInstallerMain");
368 return intent;
369 }
370
371 /**
Brian Carlstromba1a6672011-05-24 21:54:37 -0700372 * Launches an {@code Activity} for the user to select the alias
373 * for a private key and certificate pair for authentication. The
374 * selected alias or null will be returned via the
Brian Carlstrom93201f52011-06-09 15:05:35 -0700375 * KeyChainAliasCallback callback.
376 *
Eran Messeri0bc50f92018-06-01 16:03:39 +0100377 * <p>A device policy controller (as a device or profile owner) can
378 * intercept the request before the activity is shown, to pick a
379 * specific private key alias by implementing
380 * {@link android.app.admin.DeviceAdminReceiver#onChoosePrivateKeyAlias
381 * onChoosePrivateKeyAlias}.
Robin Lee3798ed52015-02-03 17:55:31 +0000382 *
383 * <p>{@code keyTypes} and {@code issuers} may be used to
Eran Messeri9ccec4d2018-08-24 15:29:05 +0100384 * narrow down suggested choices to the user. If either {@code keyTypes}
385 * or {@code issuers} is specified and non-empty, and there are no
386 * matching certificates in the KeyChain, then the certificate
387 * selection prompt would be suppressed entirely.
Robin Lee3798ed52015-02-03 17:55:31 +0000388 *
389 * <p>{@code host} and {@code port} may be used to give the user
390 * more context about the server requesting the credentials.
391 *
Eran Messeri0bc50f92018-06-01 16:03:39 +0100392 * <p>{@code alias} allows the caller to preselect an existing
Robin Lee3798ed52015-02-03 17:55:31 +0000393 * alias which will still be subject to user confirmation.
394 *
395 * @param activity The {@link Activity} context to use for
396 * launching the new sub-Activity to prompt the user to select
397 * a private key; used only to call startActivity(); must not
398 * be null.
399 * @param response Callback to invoke when the request completes;
Mike Harriscd0eb712018-04-26 15:20:10 -0700400 * must not be null.
Robin Lee3798ed52015-02-03 17:55:31 +0000401 * @param keyTypes The acceptable types of asymmetric keys such as
Eran Messeri9ccec4d2018-08-24 15:29:05 +0100402 * "RSA", "EC" or null.
Robin Lee3798ed52015-02-03 17:55:31 +0000403 * @param issuers The acceptable certificate issuers for the
404 * certificate matching the private key, or null.
405 * @param host The host name of the server requesting the
406 * certificate, or null if unavailable.
407 * @param port The port number of the server requesting the
408 * certificate, or -1 if unavailable.
409 * @param alias The alias to preselect if available, or null if
410 * unavailable.
411 */
Alex Klyubin54bb1592015-05-11 12:30:03 -0700412 public static void choosePrivateKeyAlias(@NonNull Activity activity,
413 @NonNull KeyChainAliasCallback response,
Mike Harriscd0eb712018-04-26 15:20:10 -0700414 @Nullable @KeyProperties.KeyAlgorithmEnum String[] keyTypes,
415 @Nullable Principal[] issuers,
Alex Klyubin54bb1592015-05-11 12:30:03 -0700416 @Nullable String host, int port, @Nullable String alias) {
Robin Lee39087b12015-05-05 15:57:17 +0100417 Uri uri = null;
418 if (host != null) {
419 uri = new Uri.Builder()
420 .authority(host + (port != -1 ? ":" + port : ""))
421 .build();
422 }
423 choosePrivateKeyAlias(activity, response, keyTypes, issuers, uri, alias);
Robin Lee3798ed52015-02-03 17:55:31 +0000424 }
425
426 /**
427 * Launches an {@code Activity} for the user to select the alias
428 * for a private key and certificate pair for authentication. The
429 * selected alias or null will be returned via the
430 * KeyChainAliasCallback callback.
431 *
Eran Messeri0bc50f92018-06-01 16:03:39 +0100432 * <p>A device policy controller (as a device or profile owner) can
433 * intercept the request before the activity is shown, to pick a
434 * specific private key alias by implementing
435 * {@link android.app.admin.DeviceAdminReceiver#onChoosePrivateKeyAlias
436 * onChoosePrivateKeyAlias}.
Robin Lee3798ed52015-02-03 17:55:31 +0000437 *
Brian Carlstrom93201f52011-06-09 15:05:35 -0700438 * <p>{@code keyTypes} and {@code issuers} may be used to
Eran Messeri9ccec4d2018-08-24 15:29:05 +0100439 * narrow down suggested choices to the user. If either {@code keyTypes}
440 * or {@code issuers} is specified and non-empty, and there are no
441 * matching certificates in the KeyChain, then the certificate
442 * selection prompt would be suppressed entirely.
Brian Carlstrom93201f52011-06-09 15:05:35 -0700443 *
Eran Messeri0bc50f92018-06-01 16:03:39 +0100444 * <p>{@code uri} may be used to give the user more context about
445 * the server requesting the credentials.
Brian Carlstrom93201f52011-06-09 15:05:35 -0700446 *
Eran Messeri0bc50f92018-06-01 16:03:39 +0100447 * <p>{@code alias} allows the caller to preselect an existing
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700448 * alias which will still be subject to user confirmation.
449 *
Brian Carlstrom93201f52011-06-09 15:05:35 -0700450 * @param activity The {@link Activity} context to use for
451 * launching the new sub-Activity to prompt the user to select
452 * a private key; used only to call startActivity(); must not
453 * be null.
454 * @param response Callback to invoke when the request completes;
Mike Harriscd0eb712018-04-26 15:20:10 -0700455 * must not be null.
Brian Carlstrom93201f52011-06-09 15:05:35 -0700456 * @param keyTypes The acceptable types of asymmetric keys such as
Eran Messeri9ccec4d2018-08-24 15:29:05 +0100457 * "RSA", "EC" or null.
Brian Carlstrom93201f52011-06-09 15:05:35 -0700458 * @param issuers The acceptable certificate issuers for the
459 * certificate matching the private key, or null.
Robin Lee39087b12015-05-05 15:57:17 +0100460 * @param uri The full URI the server is requesting the certificate
Robin Lee3798ed52015-02-03 17:55:31 +0000461 * for, or null if unavailable.
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700462 * @param alias The alias to preselect if available, or null if
463 * unavailable.
Eran Messeri9ccec4d2018-08-24 15:29:05 +0100464 * @throws IllegalArgumentException if the specified issuers are not
465 * of type {@code X500Principal}.
Brian Carlstromba1a6672011-05-24 21:54:37 -0700466 */
Alex Klyubin54bb1592015-05-11 12:30:03 -0700467 public static void choosePrivateKeyAlias(@NonNull Activity activity,
468 @NonNull KeyChainAliasCallback response,
Mike Harriscd0eb712018-04-26 15:20:10 -0700469 @Nullable @KeyProperties.KeyAlgorithmEnum String[] keyTypes,
470 @Nullable Principal[] issuers,
Robin Lee39087b12015-05-05 15:57:17 +0100471 @Nullable Uri uri, @Nullable String alias) {
Brian Carlstrom93201f52011-06-09 15:05:35 -0700472 /*
Eran Messeri9ccec4d2018-08-24 15:29:05 +0100473 * Specifying keyTypes excludes certificates with different key types
474 * from the list of certificates presented to the user.
475 * In practice today, most servers would require RSA or EC
476 * certificates.
Brian Carlstrom93201f52011-06-09 15:05:35 -0700477 *
Eran Messeri9ccec4d2018-08-24 15:29:05 +0100478 * Specifying issuers narrows down the list by filtering out
479 * certificates with issuers which are not matching the provided ones.
480 * This has been reported to Chrome several times (crbug.com/731769).
481 * There's no concrete description on what to do when the client has no
482 * certificates that match the provided issuers.
483 * To be conservative, Android will not present the user with any
484 * certificates to choose from.
485 * If the list of issuers is empty then the client may send any
486 * certificate, see:
487 * https://tools.ietf.org/html/rfc5246#section-7.4.4
Brian Carlstrom93201f52011-06-09 15:05:35 -0700488 */
Brian Carlstromba1a6672011-05-24 21:54:37 -0700489 if (activity == null) {
490 throw new NullPointerException("activity == null");
491 }
492 if (response == null) {
493 throw new NullPointerException("response == null");
494 }
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700495 Intent intent = new Intent(ACTION_CHOOSER);
Kenny Roota3659062014-03-17 16:21:53 -0700496 intent.setPackage(KEYCHAIN_PACKAGE);
Fred Quintanaab8b84a2011-07-13 14:55:39 -0700497 intent.putExtra(EXTRA_RESPONSE, new AliasResponse(response));
Robin Lee39087b12015-05-05 15:57:17 +0100498 intent.putExtra(EXTRA_URI, uri);
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700499 intent.putExtra(EXTRA_ALIAS, alias);
Eran Messeri9ccec4d2018-08-24 15:29:05 +0100500 intent.putExtra(EXTRA_KEY_TYPES, keyTypes);
501 ArrayList<byte[]> issuersList = new ArrayList();
502 if (issuers != null) {
503 for (Principal issuer: issuers) {
504 // In a TLS client context (like Chrome), issuers would only
505 // be specified as X500Principals. No other use cases for
506 // specifying principals have been brought up. Under these
507 // circumstances, only allow issuers specified as
508 // X500Principals.
509 if (!(issuer instanceof X500Principal)) {
510 throw new IllegalArgumentException(String.format(
511 "Issuer %s is of type %s, not X500Principal",
512 issuer.toString(), issuer.getClass()));
513 }
514 // Pass the DER-encoded issuer as that's the most accurate
515 // representation and what is sent over the wire.
516 issuersList.add(((X500Principal) issuer).getEncoded());
517 }
518 }
519 intent.putExtra(EXTRA_ISSUERS, (Serializable) issuersList);
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700520 // the PendingIntent is used to get calling package name
521 intent.putExtra(EXTRA_SENDER, PendingIntent.getActivity(activity, 0, new Intent(), 0));
Brian Carlstromba1a6672011-05-24 21:54:37 -0700522 activity.startActivity(intent);
523 }
524
Brian Carlstrom93201f52011-06-09 15:05:35 -0700525 private static class AliasResponse extends IKeyChainAliasCallback.Stub {
Brian Carlstrom93201f52011-06-09 15:05:35 -0700526 private final KeyChainAliasCallback keyChainAliasResponse;
Fred Quintanaab8b84a2011-07-13 14:55:39 -0700527 private AliasResponse(KeyChainAliasCallback keyChainAliasResponse) {
Brian Carlstromba1a6672011-05-24 21:54:37 -0700528 this.keyChainAliasResponse = keyChainAliasResponse;
529 }
530 @Override public void alias(String alias) {
Fred Quintanaab8b84a2011-07-13 14:55:39 -0700531 keyChainAliasResponse.alias(alias);
Brian Carlstromba1a6672011-05-24 21:54:37 -0700532 }
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700533 }
534
535 /**
Brian Carlstromba1a6672011-05-24 21:54:37 -0700536 * Returns the {@code PrivateKey} for the requested alias, or null
Robin Lee3a435f02015-12-21 12:06:04 +0000537 * if there is no result.
Brian Carlstrom93201f52011-06-09 15:05:35 -0700538 *
Robin Lee59e3baa2015-06-30 10:48:06 -0700539 * <p> This method may block while waiting for a connection to another process, and must never
540 * be called from the main thread.
Robin Leeda236182016-08-12 12:46:28 +0100541 * <p> As {@link Activity} and {@link Service} contexts are short-lived and can be destroyed
542 * at any time from the main thread, it is safer to rely on a long-lived context such as one
543 * returned from {@link Context#getApplicationContext()}.
Robin Lee59e3baa2015-06-30 10:48:06 -0700544 *
545 * @param alias The alias of the desired private key, typically returned via
546 * {@link KeyChainAliasCallback#alias}.
Brian Carlstrom93201f52011-06-09 15:05:35 -0700547 * @throws KeyChainException if the alias was valid but there was some problem accessing it.
Robin Lee59e3baa2015-06-30 10:48:06 -0700548 * @throws IllegalStateException if called from the main thread.
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700549 */
Robin Lee59e3baa2015-06-30 10:48:06 -0700550 @Nullable @WorkerThread
Alex Klyubin54bb1592015-05-11 12:30:03 -0700551 public static PrivateKey getPrivateKey(@NonNull Context context, @NonNull String alias)
Brian Carlstrom93201f52011-06-09 15:05:35 -0700552 throws KeyChainException, InterruptedException {
Eran Messeri23c438d2017-11-23 17:20:52 +0000553 KeyPair keyPair = getKeyPair(context, alias);
554 if (keyPair != null) {
555 return keyPair.getPrivate();
556 }
557
558 return null;
559 }
560
561 /** @hide */
562 @Nullable @WorkerThread
563 public static KeyPair getKeyPair(@NonNull Context context, @NonNull String alias)
564 throws KeyChainException, InterruptedException {
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700565 if (alias == null) {
566 throw new NullPointerException("alias == null");
567 }
Shawn Willdendea66142016-11-16 06:01:06 -0700568 if (context == null) {
569 throw new NullPointerException("context == null");
570 }
Robin Lee28d68b12016-07-22 16:32:32 +0100571
572 final String keyId;
573 try (KeyChainConnection keyChainConnection = bind(context.getApplicationContext())) {
574 keyId = keyChainConnection.getService().requestPrivateKey(alias);
Brian Carlstrom93201f52011-06-09 15:05:35 -0700575 } catch (RemoteException e) {
576 throw new KeyChainException(e);
577 } catch (RuntimeException e) {
578 // only certain RuntimeExceptions can be propagated across the IKeyChainService call
579 throw new KeyChainException(e);
Robin Lee28d68b12016-07-22 16:32:32 +0100580 }
581
582 if (keyId == null) {
583 return null;
584 } else {
585 try {
Eran Messeri23c438d2017-11-23 17:20:52 +0000586 return AndroidKeyStoreProvider.loadAndroidKeyStoreKeyPairFromKeystore(
Robin Lee28d68b12016-07-22 16:32:32 +0100587 KeyStore.getInstance(), keyId, KeyStore.UID_SELF);
Max Bires13f98ce2018-11-02 10:50:40 -0700588 } catch (RuntimeException | UnrecoverableKeyException | KeyPermanentlyInvalidatedException e) {
Robin Lee28d68b12016-07-22 16:32:32 +0100589 throw new KeyChainException(e);
590 }
Brian Carlstromba1a6672011-05-24 21:54:37 -0700591 }
592 }
593
594 /**
595 * Returns the {@code X509Certificate} chain for the requested
Rubin Xub4365912016-03-23 12:13:22 +0000596 * alias, or null if there is no result.
597 * <p>
598 * <strong>Note:</strong> If a certificate chain was explicitly specified when the alias was
599 * installed, this method will return that chain. If only the client certificate was specified
600 * at the installation time, this method will try to build a certificate chain using all
601 * available trust anchors (preinstalled and user-added).
Brian Carlstrom93201f52011-06-09 15:05:35 -0700602 *
Robin Lee59e3baa2015-06-30 10:48:06 -0700603 * <p> This method may block while waiting for a connection to another process, and must never
604 * be called from the main thread.
Robin Leeda236182016-08-12 12:46:28 +0100605 * <p> As {@link Activity} and {@link Service} contexts are short-lived and can be destroyed
606 * at any time from the main thread, it is safer to rely on a long-lived context such as one
607 * returned from {@link Context#getApplicationContext()}.
Robin Lee59e3baa2015-06-30 10:48:06 -0700608 *
Brian Carlstrom93201f52011-06-09 15:05:35 -0700609 * @param alias The alias of the desired certificate chain, typically
610 * returned via {@link KeyChainAliasCallback#alias}.
611 * @throws KeyChainException if the alias was valid but there was some problem accessing it.
Robin Lee59e3baa2015-06-30 10:48:06 -0700612 * @throws IllegalStateException if called from the main thread.
Brian Carlstromba1a6672011-05-24 21:54:37 -0700613 */
Robin Lee59e3baa2015-06-30 10:48:06 -0700614 @Nullable @WorkerThread
Alex Klyubin54bb1592015-05-11 12:30:03 -0700615 public static X509Certificate[] getCertificateChain(@NonNull Context context,
616 @NonNull String alias) throws KeyChainException, InterruptedException {
Brian Carlstromba1a6672011-05-24 21:54:37 -0700617 if (alias == null) {
618 throw new NullPointerException("alias == null");
619 }
Kenny Root0150e482013-02-13 15:22:50 -0800620
Robin Lee28d68b12016-07-22 16:32:32 +0100621 final byte[] certificateBytes;
622 final byte[] certChainBytes;
623 try (KeyChainConnection keyChainConnection = bind(context.getApplicationContext())) {
624 IKeyChainService keyChainService = keyChainConnection.getService();
625 certificateBytes = keyChainService.getCertificate(alias);
Kenny Root0150e482013-02-13 15:22:50 -0800626 if (certificateBytes == null) {
627 return null;
628 }
Robin Lee28d68b12016-07-22 16:32:32 +0100629 certChainBytes = keyChainService.getCaCertificates(alias);
630 } catch (RemoteException e) {
631 throw new KeyChainException(e);
632 } catch (RuntimeException e) {
633 // only certain RuntimeExceptions can be propagated across the IKeyChainService call
634 throw new KeyChainException(e);
635 }
636
637 try {
Rubin Xub4365912016-03-23 12:13:22 +0000638 X509Certificate leafCert = toCertificate(certificateBytes);
Rubin Xub4365912016-03-23 12:13:22 +0000639 // If the keypair is installed with a certificate chain by either
640 // DevicePolicyManager.installKeyPair or CertInstaller, return that chain.
641 if (certChainBytes != null && certChainBytes.length != 0) {
642 Collection<X509Certificate> chain = toCertificates(certChainBytes);
643 ArrayList<X509Certificate> fullChain = new ArrayList<>(chain.size() + 1);
644 fullChain.add(leafCert);
645 fullChain.addAll(chain);
646 return fullChain.toArray(new X509Certificate[fullChain.size()]);
647 } else {
648 // If there isn't a certificate chain, either due to a pre-existing keypair
649 // installed before N, or no chain is explicitly installed under the new logic,
650 // fall back to old behavior of constructing the chain from trusted credentials.
651 //
652 // This logic exists to maintain old behaviour for already installed keypair, at
653 // the cost of potentially returning extra certificate chain for new clients who
654 // explicitly installed only the client certificate without a chain. The latter
655 // case is actually no different from pre-N behaviour of getCertificateChain(),
656 // in that sense this change introduces no regression. Besides the returned chain
657 // is still valid so the consumer of the chain should have no problem verifying it.
658 TrustedCertificateStore store = new TrustedCertificateStore();
659 List<X509Certificate> chain = store.getCertificateChain(leafCert);
660 return chain.toArray(new X509Certificate[chain.size()]);
661 }
Robin Lee28d68b12016-07-22 16:32:32 +0100662 } catch (CertificateException | RuntimeException e) {
Kenny Rootcfba6a02013-05-06 15:00:58 -0700663 throw new KeyChainException(e);
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700664 }
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700665 }
666
Kenny Rootbf556ac2013-04-01 15:10:22 -0700667 /**
668 * Returns {@code true} if the current device's {@code KeyChain} supports a
669 * specific {@code PrivateKey} type indicated by {@code algorithm} (e.g.,
670 * "RSA").
671 */
Alex Klyubin4d5443f2015-05-06 15:43:52 -0700672 public static boolean isKeyAlgorithmSupported(
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700673 @NonNull @KeyProperties.KeyAlgorithmEnum String algorithm) {
Kenny Rootb91773b2013-09-05 13:03:16 -0700674 final String algUpper = algorithm.toUpperCase(Locale.US);
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700675 return KeyProperties.KEY_ALGORITHM_EC.equals(algUpper)
676 || KeyProperties.KEY_ALGORITHM_RSA.equals(algUpper);
Kenny Rootbf556ac2013-04-01 15:10:22 -0700677 }
678
679 /**
680 * Returns {@code true} if the current device's {@code KeyChain} binds any
681 * {@code PrivateKey} of the given {@code algorithm} to the device once
682 * imported or generated. This can be used to tell if there is special
683 * hardware support that can be used to bind keys to the device in a way
684 * that makes it non-exportable.
Alex Klyubin469cbf52015-06-04 12:36:27 -0700685 *
686 * @deprecated Whether the key is bound to the secure hardware is known only
687 * once the key has been imported. To find out, use:
688 * <pre>{@code
689 * PrivateKey key = ...; // private key from KeyChain
690 *
691 * KeyFactory keyFactory =
692 * KeyFactory.getInstance(key.getAlgorithm(), "AndroidKeyStore");
693 * KeyInfo keyInfo = keyFactory.getKeySpec(key, KeyInfo.class);
Neil Fuller71fbb812015-11-30 09:51:33 +0000694 * if (keyInfo.isInsideSecureHardware()) {
Alex Klyubin469cbf52015-06-04 12:36:27 -0700695 * // The key is bound to the secure hardware of this Android
Neil Fuller71fbb812015-11-30 09:51:33 +0000696 * }}</pre>
Kenny Rootbf556ac2013-04-01 15:10:22 -0700697 */
Alex Klyubin469cbf52015-06-04 12:36:27 -0700698 @Deprecated
Alex Klyubin4d5443f2015-05-06 15:43:52 -0700699 public static boolean isBoundKeyAlgorithm(
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700700 @NonNull @KeyProperties.KeyAlgorithmEnum String algorithm) {
Kenny Root5b7e90a2013-04-02 11:23:41 -0700701 if (!isKeyAlgorithmSupported(algorithm)) {
Kenny Rootbf556ac2013-04-01 15:10:22 -0700702 return false;
703 }
704
Kenny Rootb91773b2013-09-05 13:03:16 -0700705 return KeyStore.getInstance().isHardwareBacked(algorithm);
Kenny Rootbf556ac2013-04-01 15:10:22 -0700706 }
707
Zoltan Szatmary-Banf0ae1352014-08-18 10:48:33 +0100708 /** @hide */
Alex Klyubin54bb1592015-05-11 12:30:03 -0700709 @NonNull
710 public static X509Certificate toCertificate(@NonNull byte[] bytes) {
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700711 if (bytes == null) {
Brian Carlstrom8e9929c2011-05-17 00:40:28 -0700712 throw new IllegalArgumentException("bytes == null");
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700713 }
714 try {
715 CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
716 Certificate cert = certFactory.generateCertificate(new ByteArrayInputStream(bytes));
717 return (X509Certificate) cert;
718 } catch (CertificateException e) {
719 throw new AssertionError(e);
720 }
721 }
722
Rubin Xub4365912016-03-23 12:13:22 +0000723 /** @hide */
724 @NonNull
725 public static Collection<X509Certificate> toCertificates(@NonNull byte[] bytes) {
726 if (bytes == null) {
727 throw new IllegalArgumentException("bytes == null");
728 }
729 try {
730 CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
731 return (Collection<X509Certificate>) certFactory.generateCertificates(
732 new ByteArrayInputStream(bytes));
733 } catch (CertificateException e) {
734 throw new AssertionError(e);
735 }
736 }
737
Brian Carlstromd7524722011-05-17 16:20:36 -0700738 /**
739 * @hide for reuse by CertInstaller and Settings.
740 * @see KeyChain#bind
741 */
Robin Lee7f5c91c2017-02-08 21:27:02 +0000742 public static class KeyChainConnection implements Closeable {
Brian Carlstromd7524722011-05-17 16:20:36 -0700743 private final Context context;
744 private final ServiceConnection serviceConnection;
745 private final IKeyChainService service;
phweisse375fc42017-04-19 20:15:06 +0200746 protected KeyChainConnection(Context context,
747 ServiceConnection serviceConnection,
748 IKeyChainService service) {
Brian Carlstromd7524722011-05-17 16:20:36 -0700749 this.context = context;
750 this.serviceConnection = serviceConnection;
751 this.service = service;
752 }
753 @Override public void close() {
754 context.unbindService(serviceConnection);
755 }
756 public IKeyChainService getService() {
757 return service;
758 }
759 }
760
761 /**
762 * @hide for reuse by CertInstaller and Settings.
763 *
764 * Caller should call unbindService on the result when finished.
765 */
Robin Lee59e3baa2015-06-30 10:48:06 -0700766 @WorkerThread
Alex Klyubin54bb1592015-05-11 12:30:03 -0700767 public static KeyChainConnection bind(@NonNull Context context) throws InterruptedException {
Robin Lee306fe082014-06-19 14:04:24 +0000768 return bindAsUser(context, Process.myUserHandle());
769 }
770
771 /**
772 * @hide
773 */
Robin Lee59e3baa2015-06-30 10:48:06 -0700774 @WorkerThread
Alex Klyubin54bb1592015-05-11 12:30:03 -0700775 public static KeyChainConnection bindAsUser(@NonNull Context context, UserHandle user)
Robin Lee306fe082014-06-19 14:04:24 +0000776 throws InterruptedException {
Brian Carlstromd7524722011-05-17 16:20:36 -0700777 if (context == null) {
778 throw new NullPointerException("context == null");
779 }
780 ensureNotOnMainThread(context);
781 final BlockingQueue<IKeyChainService> q = new LinkedBlockingQueue<IKeyChainService>(1);
782 ServiceConnection keyChainServiceConnection = new ServiceConnection() {
Fred Quintanaab8b84a2011-07-13 14:55:39 -0700783 volatile boolean mConnectedAtLeastOnce = false;
Brian Carlstromd7524722011-05-17 16:20:36 -0700784 @Override public void onServiceConnected(ComponentName name, IBinder service) {
Fred Quintanaab8b84a2011-07-13 14:55:39 -0700785 if (!mConnectedAtLeastOnce) {
786 mConnectedAtLeastOnce = true;
787 try {
Jeff Sharkey0a17db12016-11-04 11:23:46 -0600788 q.put(IKeyChainService.Stub.asInterface(Binder.allowBlocking(service)));
Fred Quintanaab8b84a2011-07-13 14:55:39 -0700789 } catch (InterruptedException e) {
790 // will never happen, since the queue starts with one available slot
791 }
Brian Carlstromd7524722011-05-17 16:20:36 -0700792 }
793 }
794 @Override public void onServiceDisconnected(ComponentName name) {}
795 };
Maggie Benthallda51e682013-08-08 22:35:44 -0400796 Intent intent = new Intent(IKeyChainService.class.getName());
797 ComponentName comp = intent.resolveSystemService(context.getPackageManager(), 0);
798 intent.setComponent(comp);
Robin Lee21bcbc52016-02-29 18:55:35 +0000799 if (comp == null || !context.bindServiceAsUser(
800 intent, keyChainServiceConnection, Context.BIND_AUTO_CREATE, user)) {
Brian Carlstromd7524722011-05-17 16:20:36 -0700801 throw new AssertionError("could not bind to KeyChainService");
802 }
803 return new KeyChainConnection(context, keyChainServiceConnection, q.take());
804 }
805
Alex Klyubin54bb1592015-05-11 12:30:03 -0700806 private static void ensureNotOnMainThread(@NonNull Context context) {
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700807 Looper looper = Looper.myLooper();
Brian Carlstrom8e9929c2011-05-17 00:40:28 -0700808 if (looper != null && looper == context.getMainLooper()) {
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700809 throw new IllegalStateException(
810 "calling this from your main thread can lead to deadlock");
811 }
812 }
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700813}