• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
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  */
16 package android.security;
17 
18 import android.annotation.NonNull;
19 import android.annotation.Nullable;
20 import android.annotation.SdkConstant;
21 import android.annotation.SdkConstant.SdkConstantType;
22 import android.annotation.WorkerThread;
23 import android.app.Activity;
24 import android.app.PendingIntent;
25 import android.app.Service;
26 import android.content.ComponentName;
27 import android.content.Context;
28 import android.content.Intent;
29 import android.content.ServiceConnection;
30 import android.net.Uri;
31 import android.os.Binder;
32 import android.os.IBinder;
33 import android.os.Looper;
34 import android.os.Process;
35 import android.os.RemoteException;
36 import android.os.UserHandle;
37 import android.os.UserManager;
38 import android.security.keystore.AndroidKeyStoreProvider;
39 import android.security.keystore.KeyPermanentlyInvalidatedException;
40 import android.security.keystore.KeyProperties;
41 
42 import com.android.org.conscrypt.TrustedCertificateStore;
43 
44 import java.io.ByteArrayInputStream;
45 import java.io.Closeable;
46 import java.io.Serializable;
47 import java.security.KeyPair;
48 import java.security.Principal;
49 import java.security.PrivateKey;
50 import java.security.UnrecoverableKeyException;
51 import java.security.cert.Certificate;
52 import java.security.cert.CertificateException;
53 import java.security.cert.CertificateFactory;
54 import java.security.cert.X509Certificate;
55 import java.util.ArrayList;
56 import java.util.Collection;
57 import java.util.List;
58 import java.util.Locale;
59 import java.util.concurrent.CountDownLatch;
60 import java.util.concurrent.atomic.AtomicReference;
61 
62 import javax.security.auth.x500.X500Principal;
63 
64 /**
65  * 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
93  *
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}.
100  */
101 // TODO reference intent for credential installation when public
102 public final class KeyChain {
103 
104     /**
105      * @hide Also used by KeyChainService implementation
106      */
107     public static final String ACCOUNT_TYPE = "com.android.keychain";
108 
109     /**
110      * Package name for KeyChain chooser.
111      */
112     private static final String KEYCHAIN_PACKAGE = "com.android.keychain";
113 
114     /**
115      * Action to bring up the KeyChainActivity
116      */
117     private static final String ACTION_CHOOSER = "com.android.keychain.CHOOSER";
118 
119     /**
120      * Package name for the Certificate Installer.
121      */
122     private static final String CERT_INSTALLER_PACKAGE = "com.android.certinstaller";
123 
124     /**
125      * Extra for use with {@link #ACTION_CHOOSER}
126      * @hide Also used by KeyChainActivity implementation
127      */
128     public static final String EXTRA_RESPONSE = "response";
129 
130     /**
131      * Extra for use with {@link #ACTION_CHOOSER}
132      * @hide Also used by KeyChainActivity implementation
133      */
134     public static final String EXTRA_URI = "uri";
135 
136     /**
137      * Extra for use with {@link #ACTION_CHOOSER}
138      * @hide Also used by KeyChainActivity implementation
139      */
140     public static final String EXTRA_ALIAS = "alias";
141 
142     /**
143      * Extra for use with {@link #ACTION_CHOOSER}
144      * @hide Also used by KeyChainActivity implementation
145      */
146     public static final String EXTRA_SENDER = "sender";
147 
148     /**
149      * 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     /**
161      * Action to bring up the CertInstaller.
162      */
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}.
168      */
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.
181      */
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
190      * java.security.KeyStore#store} on a "PKCS12" instance.
191      *
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.
200      */
201     // Compatible with old android.security.Credentials.PKCS12
202     public static final String EXTRA_PKCS12 = "PKCS12";
203 
204     /**
205      * 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>
215      *
216      * @deprecated Use {@link #ACTION_KEYCHAIN_CHANGED}, {@link #ACTION_TRUST_STORE_CHANGED} or
217      * {@link #ACTION_KEY_ACCESS_CHANGED}. Apps that target a version higher than
218      * {@link android.os.Build.VERSION_CODES#N_MR1} will only receive this broadcast if they
219      * register for it at runtime.
220      */
221     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
222     public static final String ACTION_STORAGE_CHANGED = "android.security.STORAGE_CHANGED";
223 
224     /**
225      * Broadcast Action: Indicates the contents of the keychain has changed. Sent when a KeyChain
226      * entry is added, modified or removed.
227      */
228     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
229     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      */
240     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
241     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      */
248     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
249     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     /**
265      * 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     /**
302      * StrongBox unavailable when calling {@link #generateKeyPair}
303      * @hide
304      */
305     public static final int KEY_GEN_STRONGBOX_UNAVAILABLE = 6;
306 
307     /**
308      * General failure while calling {@link #generateKeyPair}
309      * @hide
310      */
311     public static final int KEY_GEN_FAILURE = 7;
312 
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     /**
347      * Used by DPC or delegated app in
348      * {@link android.app.admin.DeviceAdminReceiver#onChoosePrivateKeyAlias} or
349      * {@link android.app.admin.DelegatedAdminReceiver#onChoosePrivateKeyAlias} to identify that
350      * the requesting app is not granted access to any key, and nor will the user be able to grant
351      * access manually.
352      */
353     public static final String KEY_ALIAS_SELECTION_DENIED =
354             "android:alias-selection-denied";
355 
356     /**
357      * Returns an {@code Intent} that can be used for credential
358      * installation. The intent may be used without any extras, in
359      * which case the user will be able to install credentials from
360      * their own source.
361      *
362      * <p>Alternatively, {@link #EXTRA_CERTIFICATE} or {@link
363      * #EXTRA_PKCS12} maybe used to specify the bytes of an X.509
364      * certificate or a PKCS#12 key store for installation. These
365      * extras may be combined with {@link #EXTRA_NAME} to provide a
366      * default alias name for credentials being installed.
367      *
368      * <p>When used with {@link Activity#startActivityForResult},
369      * {@link Activity#RESULT_OK} will be returned if a credential was
370      * successfully installed, otherwise {@link
371      * Activity#RESULT_CANCELED} will be returned.
372      *
373      * <p>Starting from {@link android.os.Build.VERSION_CODES#R}, the intent returned by this
374      * method cannot be used for installing CA certificates. Since CA certificates can only be
375      * installed via Settings, the app should provide the user with a file containing the
376      * CA certificate. One way to do this would be to use the {@link android.provider.MediaStore}
377      * API to write the certificate to the {@link android.provider.MediaStore.Downloads}
378      * collection.
379      */
380     @NonNull
createInstallIntent()381     public static Intent createInstallIntent() {
382         Intent intent = new Intent(ACTION_INSTALL);
383         intent.setClassName(CERT_INSTALLER_PACKAGE,
384                             "com.android.certinstaller.CertInstallerMain");
385         return intent;
386     }
387 
388     /**
389      * Launches an {@code Activity} for the user to select the alias
390      * for a private key and certificate pair for authentication. The
391      * selected alias or null will be returned via the
392      * KeyChainAliasCallback callback.
393      *
394      * <p>A device policy controller (as a device or profile owner) can
395      * intercept the request before the activity is shown, to pick a
396      * specific private key alias by implementing
397      * {@link android.app.admin.DeviceAdminReceiver#onChoosePrivateKeyAlias
398      * onChoosePrivateKeyAlias}.
399      *
400      * <p>{@code keyTypes} and {@code issuers} may be used to
401      * narrow down suggested choices to the user. If either {@code keyTypes}
402      * or {@code issuers} is specified and non-empty, and there are no
403      * matching certificates in the KeyChain, then the certificate
404      * selection prompt would be suppressed entirely.
405      *
406      * <p>{@code host} and {@code port} may be used to give the user
407      * more context about the server requesting the credentials.
408      *
409      * <p>{@code alias} allows the caller to preselect an existing
410      * alias which will still be subject to user confirmation.
411      *
412      * @param activity The {@link Activity} context to use for
413      *     launching the new sub-Activity to prompt the user to select
414      *     a private key; used only to call startActivity(); must not
415      *     be null.
416      * @param response Callback to invoke when the request completes;
417      *     must not be null.
418      * @param keyTypes The acceptable types of asymmetric keys such as
419      *     "RSA", "EC" or null.
420      * @param issuers The acceptable certificate issuers for the
421      *     certificate matching the private key, or null.
422      * @param host The host name of the server requesting the
423      *     certificate, or null if unavailable.
424      * @param port The port number of the server requesting the
425      *     certificate, or -1 if unavailable.
426      * @param alias The alias to preselect if available, or null if
427      *     unavailable.
428      */
choosePrivateKeyAlias(@onNull Activity activity, @NonNull KeyChainAliasCallback response, @Nullable @KeyProperties.KeyAlgorithmEnum String[] keyTypes, @Nullable Principal[] issuers, @Nullable String host, int port, @Nullable String alias)429     public static void choosePrivateKeyAlias(@NonNull Activity activity,
430             @NonNull KeyChainAliasCallback response,
431             @Nullable @KeyProperties.KeyAlgorithmEnum String[] keyTypes,
432             @Nullable Principal[] issuers,
433             @Nullable String host, int port, @Nullable String alias) {
434         Uri uri = null;
435         if (host != null) {
436             uri = new Uri.Builder()
437                     .authority(host + (port != -1 ? ":" + port : ""))
438                     .build();
439         }
440         choosePrivateKeyAlias(activity, response, keyTypes, issuers, uri, alias);
441     }
442 
443     /**
444      * Launches an {@code Activity} for the user to select the alias
445      * for a private key and certificate pair for authentication. The
446      * selected alias or null will be returned via the
447      * KeyChainAliasCallback callback.
448      *
449      * <p>A device policy controller (as a device or profile owner) can
450      * intercept the request before the activity is shown, to pick a
451      * specific private key alias by implementing
452      * {@link android.app.admin.DeviceAdminReceiver#onChoosePrivateKeyAlias
453      * onChoosePrivateKeyAlias}.
454      *
455      * <p>{@code keyTypes} and {@code issuers} may be used to
456      * narrow down suggested choices to the user. If either {@code keyTypes}
457      * or {@code issuers} is specified and non-empty, and there are no
458      * matching certificates in the KeyChain, then the certificate
459      * selection prompt would be suppressed entirely.
460      *
461      * <p>{@code uri} may be used to give the user more context about
462      * the server requesting the credentials.
463      *
464      * <p>{@code alias} allows the caller to preselect an existing
465      * alias which will still be subject to user confirmation.
466      *
467      * @param activity The {@link Activity} context to use for
468      *     launching the new sub-Activity to prompt the user to select
469      *     a private key; used only to call startActivity(); must not
470      *     be null.
471      * @param response Callback to invoke when the request completes;
472      *     must not be null.
473      * @param keyTypes The acceptable types of asymmetric keys such as
474      *     "RSA", "EC" or null.
475      * @param issuers The acceptable certificate issuers for the
476      *     certificate matching the private key, or null.
477      * @param uri The full URI the server is requesting the certificate
478      *     for, or null if unavailable.
479      * @param alias The alias to preselect if available, or null if
480      *     unavailable.
481      * @throws IllegalArgumentException if the specified issuers are not
482      *     of type {@code X500Principal}.
483      */
choosePrivateKeyAlias(@onNull Activity activity, @NonNull KeyChainAliasCallback response, @Nullable @KeyProperties.KeyAlgorithmEnum String[] keyTypes, @Nullable Principal[] issuers, @Nullable Uri uri, @Nullable String alias)484     public static void choosePrivateKeyAlias(@NonNull Activity activity,
485             @NonNull KeyChainAliasCallback response,
486             @Nullable @KeyProperties.KeyAlgorithmEnum String[] keyTypes,
487             @Nullable Principal[] issuers,
488             @Nullable Uri uri, @Nullable String alias) {
489         /*
490          * Specifying keyTypes excludes certificates with different key types
491          * from the list of certificates presented to the user.
492          * In practice today, most servers would require RSA or EC
493          * certificates.
494          *
495          * Specifying issuers narrows down the list by filtering out
496          * certificates with issuers which are not matching the provided ones.
497          * This has been reported to Chrome several times (crbug.com/731769).
498          * There's no concrete description on what to do when the client has no
499          * certificates that match the provided issuers.
500          * To be conservative, Android will not present the user with any
501          * certificates to choose from.
502          * If the list of issuers is empty then the client may send any
503          * certificate, see:
504          * https://tools.ietf.org/html/rfc5246#section-7.4.4
505          */
506         if (activity == null) {
507             throw new NullPointerException("activity == null");
508         }
509         if (response == null) {
510             throw new NullPointerException("response == null");
511         }
512         Intent intent = new Intent(ACTION_CHOOSER);
513         intent.setPackage(KEYCHAIN_PACKAGE);
514         intent.putExtra(EXTRA_RESPONSE, new AliasResponse(response));
515         intent.putExtra(EXTRA_URI, uri);
516         intent.putExtra(EXTRA_ALIAS, alias);
517         intent.putExtra(EXTRA_KEY_TYPES, keyTypes);
518         ArrayList<byte[]> issuersList = new ArrayList();
519         if (issuers != null) {
520             for (Principal issuer: issuers) {
521                 // In a TLS client context (like Chrome), issuers would only
522                 // be specified as X500Principals. No other use cases for
523                 // specifying principals have been brought up. Under these
524                 // circumstances, only allow issuers specified as
525                 // X500Principals.
526                 if (!(issuer instanceof X500Principal)) {
527                     throw new IllegalArgumentException(String.format(
528                             "Issuer %s is of type %s, not X500Principal",
529                             issuer.toString(), issuer.getClass()));
530                 }
531                 // Pass the DER-encoded issuer as that's the most accurate
532                 // representation and what is sent over the wire.
533                 issuersList.add(((X500Principal) issuer).getEncoded());
534             }
535         }
536         intent.putExtra(EXTRA_ISSUERS, (Serializable) issuersList);
537         // the PendingIntent is used to get calling package name
538         intent.putExtra(EXTRA_SENDER, PendingIntent.getActivity(activity, 0, new Intent(), 0));
539         activity.startActivity(intent);
540     }
541 
542     private static class AliasResponse extends IKeyChainAliasCallback.Stub {
543         private final KeyChainAliasCallback keyChainAliasResponse;
AliasResponse(KeyChainAliasCallback keyChainAliasResponse)544         private AliasResponse(KeyChainAliasCallback keyChainAliasResponse) {
545             this.keyChainAliasResponse = keyChainAliasResponse;
546         }
alias(String alias)547         @Override public void alias(String alias) {
548             keyChainAliasResponse.alias(alias);
549         }
550     }
551 
552     /**
553      * Returns the {@code PrivateKey} for the requested alias, or null if the alias does not exist
554      * or the caller has no permission to access it (see note on exceptions below).
555      *
556      * <p> This method may block while waiting for a connection to another process, and must never
557      * be called from the main thread.
558      * <p> As {@link Activity} and {@link Service} contexts are short-lived and can be destroyed
559      * at any time from the main thread, it is safer to rely on a long-lived context such as one
560      * returned from {@link Context#getApplicationContext()}.
561      *
562      * <p> If the caller provides a valid alias to which it was not granted access, then the
563      * caller must invoke {@link #choosePrivateKeyAlias} again to get another valid alias
564      * or a grant to access the same alias.
565      * <p>On Android versions prior to Q, when a key associated with the specified alias is
566      * unavailable, the method will throw a {@code KeyChainException} rather than return null.
567      * If the exception's cause (as obtained by calling {@code KeyChainException.getCause()})
568      * is a throwable of type {@code IllegalStateException} then the caller lacks a grant
569      * to access the key and certificates associated with this alias.
570      *
571      * @param alias The alias of the desired private key, typically returned via
572      *              {@link KeyChainAliasCallback#alias}.
573      * @throws KeyChainException if the alias was valid but there was some problem accessing it.
574      * @throws IllegalStateException if called from the main thread.
575      */
576     @Nullable @WorkerThread
getPrivateKey(@onNull Context context, @NonNull String alias)577     public static PrivateKey getPrivateKey(@NonNull Context context, @NonNull String alias)
578             throws KeyChainException, InterruptedException {
579         KeyPair keyPair = getKeyPair(context, alias);
580         if (keyPair != null) {
581             return keyPair.getPrivate();
582         }
583 
584         return null;
585     }
586 
587     /** @hide */
588     @Nullable @WorkerThread
getKeyPair(@onNull Context context, @NonNull String alias)589     public static KeyPair getKeyPair(@NonNull Context context, @NonNull String alias)
590             throws KeyChainException, InterruptedException {
591         if (alias == null) {
592             throw new NullPointerException("alias == null");
593         }
594         if (context == null) {
595             throw new NullPointerException("context == null");
596         }
597 
598         final String keyId;
599         try (KeyChainConnection keyChainConnection = bind(context.getApplicationContext())) {
600             keyId = keyChainConnection.getService().requestPrivateKey(alias);
601         } catch (RemoteException e) {
602             throw new KeyChainException(e);
603         } catch (RuntimeException e) {
604             // only certain RuntimeExceptions can be propagated across the IKeyChainService call
605             throw new KeyChainException(e);
606         }
607 
608         if (keyId == null) {
609             return null;
610         } else {
611             try {
612                 return AndroidKeyStoreProvider.loadAndroidKeyStoreKeyPairFromKeystore(
613                         KeyStore.getInstance(), keyId, KeyStore.UID_SELF);
614             } catch (RuntimeException | UnrecoverableKeyException | KeyPermanentlyInvalidatedException e) {
615                 throw new KeyChainException(e);
616             }
617         }
618     }
619 
620     /**
621      * Returns the {@code X509Certificate} chain for the requested alias, or null if the alias
622      * does not exist or the caller has no permission to access it (see note on exceptions
623      * in {@link #getPrivateKey}).
624      *
625      * <p>
626      * <strong>Note:</strong> If a certificate chain was explicitly specified when the alias was
627      * installed, this method will return that chain. If only the client certificate was specified
628      * at the installation time, this method will try to build a certificate chain using all
629      * available trust anchors (preinstalled and user-added).
630      *
631      * <p> This method may block while waiting for a connection to another process, and must never
632      * be called from the main thread.
633      * <p> As {@link Activity} and {@link Service} contexts are short-lived and can be destroyed
634      * at any time from the main thread, it is safer to rely on a long-lived context such as one
635      * returned from {@link Context#getApplicationContext()}.
636      * <p> In case the caller specifies an alias for which it lacks a grant, it must call
637      * {@link #choosePrivateKeyAlias} again. See {@link #getPrivateKey} for more details on
638      * coping with this scenario.
639      *
640      * @param alias The alias of the desired certificate chain, typically
641      * returned via {@link KeyChainAliasCallback#alias}.
642      * @throws KeyChainException if the alias was valid but there was some problem accessing it.
643      * @throws IllegalStateException if called from the main thread.
644      */
645     @Nullable @WorkerThread
getCertificateChain(@onNull Context context, @NonNull String alias)646     public static X509Certificate[] getCertificateChain(@NonNull Context context,
647             @NonNull String alias) throws KeyChainException, InterruptedException {
648         if (alias == null) {
649             throw new NullPointerException("alias == null");
650         }
651 
652         final byte[] certificateBytes;
653         final byte[] certChainBytes;
654         try (KeyChainConnection keyChainConnection = bind(context.getApplicationContext())) {
655             IKeyChainService keyChainService = keyChainConnection.getService();
656             certificateBytes = keyChainService.getCertificate(alias);
657             if (certificateBytes == null) {
658                 return null;
659             }
660             certChainBytes = keyChainService.getCaCertificates(alias);
661         } catch (RemoteException e) {
662             throw new KeyChainException(e);
663         } catch (RuntimeException e) {
664             // only certain RuntimeExceptions can be propagated across the IKeyChainService call
665             throw new KeyChainException(e);
666         }
667 
668         try {
669             X509Certificate leafCert = toCertificate(certificateBytes);
670             // If the keypair is installed with a certificate chain by either
671             // DevicePolicyManager.installKeyPair or CertInstaller, return that chain.
672             if (certChainBytes != null && certChainBytes.length != 0) {
673                 Collection<X509Certificate> chain = toCertificates(certChainBytes);
674                 ArrayList<X509Certificate> fullChain = new ArrayList<>(chain.size() + 1);
675                 fullChain.add(leafCert);
676                 fullChain.addAll(chain);
677                 return fullChain.toArray(new X509Certificate[fullChain.size()]);
678             } else {
679                 // If there isn't a certificate chain, either due to a pre-existing keypair
680                 // installed before N, or no chain is explicitly installed under the new logic,
681                 // fall back to old behavior of constructing the chain from trusted credentials.
682                 //
683                 // This logic exists to maintain old behaviour for already installed keypair, at
684                 // the cost of potentially returning extra certificate chain for new clients who
685                 // explicitly installed only the client certificate without a chain. The latter
686                 // case is actually no different from pre-N behaviour of getCertificateChain(),
687                 // in that sense this change introduces no regression. Besides the returned chain
688                 // is still valid so the consumer of the chain should have no problem verifying it.
689                 TrustedCertificateStore store = new TrustedCertificateStore();
690                 List<X509Certificate> chain = store.getCertificateChain(leafCert);
691                 return chain.toArray(new X509Certificate[chain.size()]);
692             }
693         } catch (CertificateException | RuntimeException e) {
694             throw new KeyChainException(e);
695         }
696     }
697 
698     /**
699      * Returns {@code true} if the current device's {@code KeyChain} supports a
700      * specific {@code PrivateKey} type indicated by {@code algorithm} (e.g.,
701      * "RSA").
702      */
isKeyAlgorithmSupported( @onNull @eyProperties.KeyAlgorithmEnum String algorithm)703     public static boolean isKeyAlgorithmSupported(
704             @NonNull @KeyProperties.KeyAlgorithmEnum String algorithm) {
705         final String algUpper = algorithm.toUpperCase(Locale.US);
706         return KeyProperties.KEY_ALGORITHM_EC.equals(algUpper)
707                 || KeyProperties.KEY_ALGORITHM_RSA.equals(algUpper);
708     }
709 
710     /**
711      * Returns {@code true} if the current device's {@code KeyChain} binds any
712      * {@code PrivateKey} of the given {@code algorithm} to the device once
713      * imported or generated. This can be used to tell if there is special
714      * hardware support that can be used to bind keys to the device in a way
715      * that makes it non-exportable.
716      *
717      * @deprecated Whether the key is bound to the secure hardware is known only
718      * once the key has been imported. To find out, use:
719      * <pre>{@code
720      * PrivateKey key = ...; // private key from KeyChain
721      *
722      * KeyFactory keyFactory =
723      *     KeyFactory.getInstance(key.getAlgorithm(), "AndroidKeyStore");
724      * KeyInfo keyInfo = keyFactory.getKeySpec(key, KeyInfo.class);
725      * if (keyInfo.isInsideSecureHardware()) {
726      *     // The key is bound to the secure hardware of this Android
727      * }}</pre>
728      */
729     @Deprecated
isBoundKeyAlgorithm( @onNull @eyProperties.KeyAlgorithmEnum String algorithm)730     public static boolean isBoundKeyAlgorithm(
731             @NonNull @KeyProperties.KeyAlgorithmEnum String algorithm) {
732         if (!isKeyAlgorithmSupported(algorithm)) {
733             return false;
734         }
735 
736         return KeyStore.getInstance().isHardwareBacked(algorithm);
737     }
738 
739     /** @hide */
740     @NonNull
toCertificate(@onNull byte[] bytes)741     public static X509Certificate toCertificate(@NonNull byte[] bytes) {
742         if (bytes == null) {
743             throw new IllegalArgumentException("bytes == null");
744         }
745         try {
746             CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
747             Certificate cert = certFactory.generateCertificate(new ByteArrayInputStream(bytes));
748             return (X509Certificate) cert;
749         } catch (CertificateException e) {
750             throw new AssertionError(e);
751         }
752     }
753 
754     /** @hide */
755     @NonNull
toCertificates(@onNull byte[] bytes)756     public static Collection<X509Certificate> toCertificates(@NonNull byte[] bytes) {
757         if (bytes == null) {
758             throw new IllegalArgumentException("bytes == null");
759         }
760         try {
761             CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
762             return (Collection<X509Certificate>) certFactory.generateCertificates(
763                     new ByteArrayInputStream(bytes));
764         } catch (CertificateException e) {
765             throw new AssertionError(e);
766         }
767     }
768 
769     /**
770      * @hide for reuse by CertInstaller and Settings.
771      * @see KeyChain#bind
772      */
773     public static class KeyChainConnection implements Closeable {
774         private final Context mContext;
775         private final ServiceConnection mServiceConnection;
776         private final IKeyChainService mService;
KeyChainConnection(Context context, ServiceConnection serviceConnection, IKeyChainService service)777         protected KeyChainConnection(Context context,
778                                      ServiceConnection serviceConnection,
779                                      IKeyChainService service) {
780             this.mContext = context;
781             this.mServiceConnection = serviceConnection;
782             this.mService = service;
783         }
close()784         @Override public void close() {
785             mContext.unbindService(mServiceConnection);
786         }
787 
788         /** returns the service binder. */
getService()789         public IKeyChainService getService() {
790             return mService;
791         }
792     }
793 
794     /**
795      * Bind to KeyChainService in the current user.
796      * Caller should call unbindService on the result when finished.
797      *
798      *@throws InterruptedException if interrupted during binding.
799      *@throws AssertionError if unable to bind to KeyChainService.
800      * @hide for reuse by CertInstaller and Settings.
801      */
802     @WorkerThread
bind(@onNull Context context)803     public static KeyChainConnection bind(@NonNull Context context) throws InterruptedException {
804         return bindAsUser(context, Process.myUserHandle());
805     }
806 
807     /**
808      * Bind to KeyChainService in the target user.
809      * Caller should call unbindService on the result when finished.
810      *
811      * @throws InterruptedException if interrupted during binding.
812      * @throws AssertionError if unable to bind to KeyChainService.
813      * @hide
814      */
815     @WorkerThread
bindAsUser(@onNull Context context, UserHandle user)816     public static KeyChainConnection bindAsUser(@NonNull Context context, UserHandle user)
817             throws InterruptedException {
818         if (context == null) {
819             throw new NullPointerException("context == null");
820         }
821         ensureNotOnMainThread(context);
822         if (!UserManager.get(context).isUserUnlocked(user)) {
823             throw new IllegalStateException("User must be unlocked");
824         }
825 
826         final CountDownLatch countDownLatch = new CountDownLatch(1);
827         final AtomicReference<IKeyChainService> keyChainService = new AtomicReference<>();
828         ServiceConnection keyChainServiceConnection = new ServiceConnection() {
829             volatile boolean mConnectedAtLeastOnce = false;
830             @Override public void onServiceConnected(ComponentName name, IBinder service) {
831                 if (!mConnectedAtLeastOnce) {
832                     mConnectedAtLeastOnce = true;
833                     keyChainService.set(
834                             IKeyChainService.Stub.asInterface(Binder.allowBlocking(service)));
835                     countDownLatch.countDown();
836                 }
837             }
838             @Override public void onBindingDied(ComponentName name) {
839                 if (!mConnectedAtLeastOnce) {
840                     mConnectedAtLeastOnce = true;
841                     countDownLatch.countDown();
842                 }
843             }
844             @Override public void onServiceDisconnected(ComponentName name) {}
845         };
846         Intent intent = new Intent(IKeyChainService.class.getName());
847         ComponentName comp = intent.resolveSystemService(context.getPackageManager(), 0);
848         intent.setComponent(comp);
849         if (comp == null || !context.bindServiceAsUser(
850                 intent, keyChainServiceConnection, Context.BIND_AUTO_CREATE, user)) {
851             throw new AssertionError("could not bind to KeyChainService");
852         }
853         countDownLatch.await();
854         IKeyChainService service = keyChainService.get();
855         if (service != null) {
856             return new KeyChainConnection(context, keyChainServiceConnection, service);
857         } else {
858             context.unbindService(keyChainServiceConnection);
859             throw new AssertionError("KeyChainService died while binding");
860         }
861     }
862 
ensureNotOnMainThread(@onNull Context context)863     private static void ensureNotOnMainThread(@NonNull Context context) {
864         Looper looper = Looper.myLooper();
865         if (looper != null && looper == context.getMainLooper()) {
866             throw new IllegalStateException(
867                     "calling this from your main thread can lead to deadlock");
868         }
869     }
870 }
871