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.WorkerThread;
21 import android.app.Activity;
22 import android.app.PendingIntent;
23 import android.content.ComponentName;
24 import android.content.Context;
25 import android.content.Intent;
26 import android.content.ServiceConnection;
27 import android.net.Uri;
28 import android.os.IBinder;
29 import android.os.Looper;
30 import android.os.Process;
31 import android.os.RemoteException;
32 import android.os.UserHandle;
33 import android.security.keystore.AndroidKeyStoreProvider;
34 import android.security.keystore.KeyProperties;
35 
36 import java.io.ByteArrayInputStream;
37 import java.io.Closeable;
38 import java.security.Principal;
39 import java.security.PrivateKey;
40 import java.security.UnrecoverableKeyException;
41 import java.security.cert.Certificate;
42 import java.security.cert.CertificateException;
43 import java.security.cert.CertificateFactory;
44 import java.security.cert.X509Certificate;
45 import java.util.ArrayList;
46 import java.util.Collection;
47 import java.util.List;
48 import java.util.Locale;
49 import java.util.concurrent.BlockingQueue;
50 import java.util.concurrent.LinkedBlockingQueue;
51 
52 import com.android.org.conscrypt.TrustedCertificateStore;
53 
54 /**
55  * The {@code KeyChain} class provides access to private keys and
56  * their corresponding certificate chains in credential storage.
57  *
58  * <p>Applications accessing the {@code KeyChain} normally go through
59  * these steps:
60  *
61  * <ol>
62  *
63  * <li>Receive a callback from an {@link javax.net.ssl.X509KeyManager
64  * X509KeyManager} that a private key is requested.
65  *
66  * <li>Call {@link #choosePrivateKeyAlias
67  * choosePrivateKeyAlias} to allow the user to select from a
68  * list of currently available private keys and corresponding
69  * certificate chains. The chosen alias will be returned by the
70  * callback {@link KeyChainAliasCallback#alias}, or null if no private
71  * key is available or the user cancels the request.
72  *
73  * <li>Call {@link #getPrivateKey} and {@link #getCertificateChain} to
74  * retrieve the credentials to return to the corresponding {@link
75  * javax.net.ssl.X509KeyManager} callbacks.
76  *
77  * </ol>
78  *
79  * <p>An application may remember the value of a selected alias to
80  * avoid prompting the user with {@link #choosePrivateKeyAlias
81  * choosePrivateKeyAlias} on subsequent connections. If the alias is
82  * no longer valid, null will be returned on lookups using that value
83  *
84  * <p>An application can request the installation of private keys and
85  * certificates via the {@code Intent} provided by {@link
86  * #createInstallIntent}. Private keys installed via this {@code
87  * Intent} will be accessible via {@link #choosePrivateKeyAlias} while
88  * Certificate Authority (CA) certificates will be trusted by all
89  * applications through the default {@code X509TrustManager}.
90  */
91 // TODO reference intent for credential installation when public
92 public final class KeyChain {
93 
94     /**
95      * @hide Also used by KeyChainService implementation
96      */
97     public static final String ACCOUNT_TYPE = "com.android.keychain";
98 
99     /**
100      * Package name for KeyChain chooser.
101      */
102     private static final String KEYCHAIN_PACKAGE = "com.android.keychain";
103 
104     /**
105      * Action to bring up the KeyChainActivity
106      */
107     private static final String ACTION_CHOOSER = "com.android.keychain.CHOOSER";
108 
109     /**
110      * Package name for the Certificate Installer.
111      */
112     private static final String CERT_INSTALLER_PACKAGE = "com.android.certinstaller";
113 
114     /**
115      * Extra for use with {@link #ACTION_CHOOSER}
116      * @hide Also used by KeyChainActivity implementation
117      */
118     public static final String EXTRA_RESPONSE = "response";
119 
120     /**
121      * Extra for use with {@link #ACTION_CHOOSER}
122      * @hide Also used by KeyChainActivity implementation
123      */
124     public static final String EXTRA_URI = "uri";
125 
126     /**
127      * Extra for use with {@link #ACTION_CHOOSER}
128      * @hide Also used by KeyChainActivity implementation
129      */
130     public static final String EXTRA_ALIAS = "alias";
131 
132     /**
133      * Extra for use with {@link #ACTION_CHOOSER}
134      * @hide Also used by KeyChainActivity implementation
135      */
136     public static final String EXTRA_SENDER = "sender";
137 
138     /**
139      * Action to bring up the CertInstaller.
140      */
141     private static final String ACTION_INSTALL = "android.credentials.INSTALL";
142 
143     /**
144      * Optional extra to specify a {@code String} credential name on
145      * the {@code Intent} returned by {@link #createInstallIntent}.
146      */
147     // Compatible with old com.android.certinstaller.CredentialHelper.CERT_NAME_KEY
148     public static final String EXTRA_NAME = "name";
149 
150     /**
151      * Optional extra to specify an X.509 certificate to install on
152      * the {@code Intent} returned by {@link #createInstallIntent}.
153      * The extra value should be a PEM or ASN.1 DER encoded {@code
154      * byte[]}. An {@link X509Certificate} can be converted to DER
155      * encoded bytes with {@link X509Certificate#getEncoded}.
156      *
157      * <p>{@link #EXTRA_NAME} may be used to provide a default alias
158      * name for the installed certificate.
159      */
160     // Compatible with old android.security.Credentials.CERTIFICATE
161     public static final String EXTRA_CERTIFICATE = "CERT";
162 
163     /**
164      * Optional extra for use with the {@code Intent} returned by
165      * {@link #createInstallIntent} to specify a PKCS#12 key store to
166      * install. The extra value should be a {@code byte[]}. The bytes
167      * may come from an external source or be generated with {@link
168      * java.security.KeyStore#store} on a "PKCS12" instance.
169      *
170      * <p>The user will be prompted for the password to load the key store.
171      *
172      * <p>The key store will be scanned for {@link
173      * java.security.KeyStore.PrivateKeyEntry} entries and both the
174      * private key and associated certificate chain will be installed.
175      *
176      * <p>{@link #EXTRA_NAME} may be used to provide a default alias
177      * name for the installed credentials.
178      */
179     // Compatible with old android.security.Credentials.PKCS12
180     public static final String EXTRA_PKCS12 = "PKCS12";
181 
182 
183     /**
184      * Broadcast Action: Indicates the trusted storage has changed. Sent when
185      * one of this happens:
186      *
187      * <ul>
188      * <li>a new CA is added,
189      * <li>an existing CA is removed or disabled,
190      * <li>a disabled CA is enabled,
191      * <li>trusted storage is reset (all user certs are cleared),
192      * <li>when permission to access a private key is changed.
193      * </ul>
194      */
195     public static final String ACTION_STORAGE_CHANGED = "android.security.STORAGE_CHANGED";
196 
197     /**
198      * Returns an {@code Intent} that can be used for credential
199      * installation. The intent may be used without any extras, in
200      * which case the user will be able to install credentials from
201      * their own source.
202      *
203      * <p>Alternatively, {@link #EXTRA_CERTIFICATE} or {@link
204      * #EXTRA_PKCS12} maybe used to specify the bytes of an X.509
205      * certificate or a PKCS#12 key store for installation. These
206      * extras may be combined with {@link #EXTRA_NAME} to provide a
207      * default alias name for credentials being installed.
208      *
209      * <p>When used with {@link Activity#startActivityForResult},
210      * {@link Activity#RESULT_OK} will be returned if a credential was
211      * successfully installed, otherwise {@link
212      * Activity#RESULT_CANCELED} will be returned.
213      */
214     @NonNull
createInstallIntent()215     public static Intent createInstallIntent() {
216         Intent intent = new Intent(ACTION_INSTALL);
217         intent.setClassName(CERT_INSTALLER_PACKAGE,
218                             "com.android.certinstaller.CertInstallerMain");
219         return intent;
220     }
221 
222     /**
223      * Launches an {@code Activity} for the user to select the alias
224      * for a private key and certificate pair for authentication. The
225      * selected alias or null will be returned via the
226      * KeyChainAliasCallback callback.
227      *
228      * <p>The device or profile owner can intercept this before the activity
229      * is shown, to pick a specific private key alias.
230      *
231      * <p>{@code keyTypes} and {@code issuers} may be used to
232      * highlight suggested choices to the user, although to cope with
233      * sometimes erroneous values provided by servers, the user may be
234      * able to override these suggestions.
235      *
236      * <p>{@code host} and {@code port} may be used to give the user
237      * more context about the server requesting the credentials.
238      *
239      * <p>{@code alias} allows the chooser to preselect an existing
240      * alias which will still be subject to user confirmation.
241      *
242      * @param activity The {@link Activity} context to use for
243      *     launching the new sub-Activity to prompt the user to select
244      *     a private key; used only to call startActivity(); must not
245      *     be null.
246      * @param response Callback to invoke when the request completes;
247      *     must not be null
248      * @param keyTypes The acceptable types of asymmetric keys such as
249      *     "RSA" or "DSA", or a null array.
250      * @param issuers The acceptable certificate issuers for the
251      *     certificate matching the private key, or null.
252      * @param host The host name of the server requesting the
253      *     certificate, or null if unavailable.
254      * @param port The port number of the server requesting the
255      *     certificate, or -1 if unavailable.
256      * @param alias The alias to preselect if available, or null if
257      *     unavailable.
258      */
choosePrivateKeyAlias(@onNull Activity activity, @NonNull KeyChainAliasCallback response, @KeyProperties.KeyAlgorithmEnum String[] keyTypes, Principal[] issuers, @Nullable String host, int port, @Nullable String alias)259     public static void choosePrivateKeyAlias(@NonNull Activity activity,
260             @NonNull KeyChainAliasCallback response,
261             @KeyProperties.KeyAlgorithmEnum String[] keyTypes, Principal[] issuers,
262             @Nullable String host, int port, @Nullable String alias) {
263         Uri uri = null;
264         if (host != null) {
265             uri = new Uri.Builder()
266                     .authority(host + (port != -1 ? ":" + port : ""))
267                     .build();
268         }
269         choosePrivateKeyAlias(activity, response, keyTypes, issuers, uri, alias);
270     }
271 
272     /**
273      * Launches an {@code Activity} for the user to select the alias
274      * for a private key and certificate pair for authentication. The
275      * selected alias or null will be returned via the
276      * KeyChainAliasCallback callback.
277      *
278      * <p>The device or profile owner can intercept this before the activity
279      * is shown, to pick a specific private key alias.</p>
280      *
281      * <p>{@code keyTypes} and {@code issuers} may be used to
282      * highlight suggested choices to the user, although to cope with
283      * sometimes erroneous values provided by servers, the user may be
284      * able to override these suggestions.
285      *
286      * <p>{@code host} and {@code port} may be used to give the user
287      * more context about the server requesting the credentials.
288      *
289      * <p>{@code alias} allows the chooser to preselect an existing
290      * alias which will still be subject to user confirmation.
291      *
292      * @param activity The {@link Activity} context to use for
293      *     launching the new sub-Activity to prompt the user to select
294      *     a private key; used only to call startActivity(); must not
295      *     be null.
296      * @param response Callback to invoke when the request completes;
297      *     must not be null
298      * @param keyTypes The acceptable types of asymmetric keys such as
299      *     "EC" or "RSA", or a null array.
300      * @param issuers The acceptable certificate issuers for the
301      *     certificate matching the private key, or null.
302      * @param uri The full URI the server is requesting the certificate
303      *     for, or null if unavailable.
304      * @param alias The alias to preselect if available, or null if
305      *     unavailable.
306      */
choosePrivateKeyAlias(@onNull Activity activity, @NonNull KeyChainAliasCallback response, @KeyProperties.KeyAlgorithmEnum String[] keyTypes, Principal[] issuers, @Nullable Uri uri, @Nullable String alias)307     public static void choosePrivateKeyAlias(@NonNull Activity activity,
308             @NonNull KeyChainAliasCallback response,
309             @KeyProperties.KeyAlgorithmEnum String[] keyTypes, Principal[] issuers,
310             @Nullable Uri uri, @Nullable String alias) {
311         /*
312          * TODO currently keyTypes, issuers are unused. They are meant
313          * to follow the semantics and purpose of X509KeyManager
314          * method arguments.
315          *
316          * keyTypes would allow the list to be filtered and typically
317          * will be set correctly by the server. In practice today,
318          * most all users will want only RSA or EC, and usually
319          * only a small number of certs will be available.
320          *
321          * issuers is typically not useful. Some servers historically
322          * will send the entire list of public CAs known to the
323          * server. Others will send none. If this is used, if there
324          * are no matches after applying the constraint, it should be
325          * ignored.
326          */
327         if (activity == null) {
328             throw new NullPointerException("activity == null");
329         }
330         if (response == null) {
331             throw new NullPointerException("response == null");
332         }
333         Intent intent = new Intent(ACTION_CHOOSER);
334         intent.setPackage(KEYCHAIN_PACKAGE);
335         intent.putExtra(EXTRA_RESPONSE, new AliasResponse(response));
336         intent.putExtra(EXTRA_URI, uri);
337         intent.putExtra(EXTRA_ALIAS, alias);
338         // the PendingIntent is used to get calling package name
339         intent.putExtra(EXTRA_SENDER, PendingIntent.getActivity(activity, 0, new Intent(), 0));
340         activity.startActivity(intent);
341     }
342 
343     private static class AliasResponse extends IKeyChainAliasCallback.Stub {
344         private final KeyChainAliasCallback keyChainAliasResponse;
AliasResponse(KeyChainAliasCallback keyChainAliasResponse)345         private AliasResponse(KeyChainAliasCallback keyChainAliasResponse) {
346             this.keyChainAliasResponse = keyChainAliasResponse;
347         }
alias(String alias)348         @Override public void alias(String alias) {
349             keyChainAliasResponse.alias(alias);
350         }
351     }
352 
353     /**
354      * Returns the {@code PrivateKey} for the requested alias, or null
355      * if there is no result.
356      *
357      * <p> This method may block while waiting for a connection to another process, and must never
358      * be called from the main thread.
359      *
360      * @param alias The alias of the desired private key, typically returned via
361      *              {@link KeyChainAliasCallback#alias}.
362      * @throws KeyChainException if the alias was valid but there was some problem accessing it.
363      * @throws IllegalStateException if called from the main thread.
364      */
365     @Nullable @WorkerThread
getPrivateKey(@onNull Context context, @NonNull String alias)366     public static PrivateKey getPrivateKey(@NonNull Context context, @NonNull String alias)
367             throws KeyChainException, InterruptedException {
368         if (alias == null) {
369             throw new NullPointerException("alias == null");
370         }
371         KeyChainConnection keyChainConnection = bind(context);
372         try {
373             final IKeyChainService keyChainService = keyChainConnection.getService();
374             final String keyId = keyChainService.requestPrivateKey(alias);
375             if (keyId == null) {
376                 return null;
377             }
378             return AndroidKeyStoreProvider.loadAndroidKeyStorePrivateKeyFromKeystore(
379                     KeyStore.getInstance(), keyId, KeyStore.UID_SELF);
380         } catch (RemoteException e) {
381             throw new KeyChainException(e);
382         } catch (RuntimeException e) {
383             // only certain RuntimeExceptions can be propagated across the IKeyChainService call
384             throw new KeyChainException(e);
385         } catch (UnrecoverableKeyException e) {
386             throw new KeyChainException(e);
387         } finally {
388             keyChainConnection.close();
389         }
390     }
391 
392     /**
393      * Returns the {@code X509Certificate} chain for the requested
394      * alias, or null if there is no result.
395      * <p>
396      * <strong>Note:</strong> If a certificate chain was explicitly specified when the alias was
397      * installed, this method will return that chain. If only the client certificate was specified
398      * at the installation time, this method will try to build a certificate chain using all
399      * available trust anchors (preinstalled and user-added).
400      *
401      * <p> This method may block while waiting for a connection to another process, and must never
402      * be called from the main thread.
403      *
404      * @param alias The alias of the desired certificate chain, typically
405      * returned via {@link KeyChainAliasCallback#alias}.
406      * @throws KeyChainException if the alias was valid but there was some problem accessing it.
407      * @throws IllegalStateException if called from the main thread.
408      */
409     @Nullable @WorkerThread
getCertificateChain(@onNull Context context, @NonNull String alias)410     public static X509Certificate[] getCertificateChain(@NonNull Context context,
411             @NonNull String alias) throws KeyChainException, InterruptedException {
412         if (alias == null) {
413             throw new NullPointerException("alias == null");
414         }
415         KeyChainConnection keyChainConnection = bind(context);
416         try {
417             IKeyChainService keyChainService = keyChainConnection.getService();
418 
419             final byte[] certificateBytes = keyChainService.getCertificate(alias);
420             if (certificateBytes == null) {
421                 return null;
422             }
423             X509Certificate leafCert = toCertificate(certificateBytes);
424             final byte[] certChainBytes = keyChainService.getCaCertificates(alias);
425             // If the keypair is installed with a certificate chain by either
426             // DevicePolicyManager.installKeyPair or CertInstaller, return that chain.
427             if (certChainBytes != null && certChainBytes.length != 0) {
428                 Collection<X509Certificate> chain = toCertificates(certChainBytes);
429                 ArrayList<X509Certificate> fullChain = new ArrayList<>(chain.size() + 1);
430                 fullChain.add(leafCert);
431                 fullChain.addAll(chain);
432                 return fullChain.toArray(new X509Certificate[fullChain.size()]);
433             } else {
434                 // If there isn't a certificate chain, either due to a pre-existing keypair
435                 // installed before N, or no chain is explicitly installed under the new logic,
436                 // fall back to old behavior of constructing the chain from trusted credentials.
437                 //
438                 // This logic exists to maintain old behaviour for already installed keypair, at
439                 // the cost of potentially returning extra certificate chain for new clients who
440                 // explicitly installed only the client certificate without a chain. The latter
441                 // case is actually no different from pre-N behaviour of getCertificateChain(),
442                 // in that sense this change introduces no regression. Besides the returned chain
443                 // is still valid so the consumer of the chain should have no problem verifying it.
444                 TrustedCertificateStore store = new TrustedCertificateStore();
445                 List<X509Certificate> chain = store.getCertificateChain(leafCert);
446                 return chain.toArray(new X509Certificate[chain.size()]);
447             }
448         } catch (CertificateException e) {
449             throw new KeyChainException(e);
450         } catch (RemoteException e) {
451             throw new KeyChainException(e);
452         } catch (RuntimeException e) {
453             // only certain RuntimeExceptions can be propagated across the IKeyChainService call
454             throw new KeyChainException(e);
455         } finally {
456             keyChainConnection.close();
457         }
458     }
459 
460     /**
461      * Returns {@code true} if the current device's {@code KeyChain} supports a
462      * specific {@code PrivateKey} type indicated by {@code algorithm} (e.g.,
463      * "RSA").
464      */
isKeyAlgorithmSupported( @onNull @eyProperties.KeyAlgorithmEnum String algorithm)465     public static boolean isKeyAlgorithmSupported(
466             @NonNull @KeyProperties.KeyAlgorithmEnum String algorithm) {
467         final String algUpper = algorithm.toUpperCase(Locale.US);
468         return KeyProperties.KEY_ALGORITHM_EC.equals(algUpper)
469                 || KeyProperties.KEY_ALGORITHM_RSA.equals(algUpper);
470     }
471 
472     /**
473      * Returns {@code true} if the current device's {@code KeyChain} binds any
474      * {@code PrivateKey} of the given {@code algorithm} to the device once
475      * imported or generated. This can be used to tell if there is special
476      * hardware support that can be used to bind keys to the device in a way
477      * that makes it non-exportable.
478      *
479      * @deprecated Whether the key is bound to the secure hardware is known only
480      * once the key has been imported. To find out, use:
481      * <pre>{@code
482      * PrivateKey key = ...; // private key from KeyChain
483      *
484      * KeyFactory keyFactory =
485      *     KeyFactory.getInstance(key.getAlgorithm(), "AndroidKeyStore");
486      * KeyInfo keyInfo = keyFactory.getKeySpec(key, KeyInfo.class);
487      * if (keyInfo.isInsideSecureHardware()) {
488      *     // The key is bound to the secure hardware of this Android
489      * }}</pre>
490      */
491     @Deprecated
isBoundKeyAlgorithm( @onNull @eyProperties.KeyAlgorithmEnum String algorithm)492     public static boolean isBoundKeyAlgorithm(
493             @NonNull @KeyProperties.KeyAlgorithmEnum String algorithm) {
494         if (!isKeyAlgorithmSupported(algorithm)) {
495             return false;
496         }
497 
498         return KeyStore.getInstance().isHardwareBacked(algorithm);
499     }
500 
501     /** @hide */
502     @NonNull
toCertificate(@onNull byte[] bytes)503     public static X509Certificate toCertificate(@NonNull byte[] bytes) {
504         if (bytes == null) {
505             throw new IllegalArgumentException("bytes == null");
506         }
507         try {
508             CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
509             Certificate cert = certFactory.generateCertificate(new ByteArrayInputStream(bytes));
510             return (X509Certificate) cert;
511         } catch (CertificateException e) {
512             throw new AssertionError(e);
513         }
514     }
515 
516     /** @hide */
517     @NonNull
toCertificates(@onNull byte[] bytes)518     public static Collection<X509Certificate> toCertificates(@NonNull byte[] bytes) {
519         if (bytes == null) {
520             throw new IllegalArgumentException("bytes == null");
521         }
522         try {
523             CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
524             return (Collection<X509Certificate>) certFactory.generateCertificates(
525                     new ByteArrayInputStream(bytes));
526         } catch (CertificateException e) {
527             throw new AssertionError(e);
528         }
529     }
530 
531     /**
532      * @hide for reuse by CertInstaller and Settings.
533      * @see KeyChain#bind
534      */
535     public final static class KeyChainConnection implements Closeable {
536         private final Context context;
537         private final ServiceConnection serviceConnection;
538         private final IKeyChainService service;
KeyChainConnection(Context context, ServiceConnection serviceConnection, IKeyChainService service)539         private KeyChainConnection(Context context,
540                                    ServiceConnection serviceConnection,
541                                    IKeyChainService service) {
542             this.context = context;
543             this.serviceConnection = serviceConnection;
544             this.service = service;
545         }
close()546         @Override public void close() {
547             context.unbindService(serviceConnection);
548         }
getService()549         public IKeyChainService getService() {
550             return service;
551         }
552     }
553 
554     /**
555      * @hide for reuse by CertInstaller and Settings.
556      *
557      * Caller should call unbindService on the result when finished.
558      */
559     @WorkerThread
bind(@onNull Context context)560     public static KeyChainConnection bind(@NonNull Context context) throws InterruptedException {
561         return bindAsUser(context, Process.myUserHandle());
562     }
563 
564     /**
565      * @hide
566      */
567     @WorkerThread
bindAsUser(@onNull Context context, UserHandle user)568     public static KeyChainConnection bindAsUser(@NonNull Context context, UserHandle user)
569             throws InterruptedException {
570         if (context == null) {
571             throw new NullPointerException("context == null");
572         }
573         ensureNotOnMainThread(context);
574         final BlockingQueue<IKeyChainService> q = new LinkedBlockingQueue<IKeyChainService>(1);
575         ServiceConnection keyChainServiceConnection = new ServiceConnection() {
576             volatile boolean mConnectedAtLeastOnce = false;
577             @Override public void onServiceConnected(ComponentName name, IBinder service) {
578                 if (!mConnectedAtLeastOnce) {
579                     mConnectedAtLeastOnce = true;
580                     try {
581                         q.put(IKeyChainService.Stub.asInterface(service));
582                     } catch (InterruptedException e) {
583                         // will never happen, since the queue starts with one available slot
584                     }
585                 }
586             }
587             @Override public void onServiceDisconnected(ComponentName name) {}
588         };
589         Intent intent = new Intent(IKeyChainService.class.getName());
590         ComponentName comp = intent.resolveSystemService(context.getPackageManager(), 0);
591         intent.setComponent(comp);
592         if (comp == null || !context.bindServiceAsUser(
593                 intent, keyChainServiceConnection, Context.BIND_AUTO_CREATE, user)) {
594             throw new AssertionError("could not bind to KeyChainService");
595         }
596         return new KeyChainConnection(context, keyChainServiceConnection, q.take());
597     }
598 
ensureNotOnMainThread(@onNull Context context)599     private static void ensureNotOnMainThread(@NonNull Context context) {
600         Looper looper = Looper.myLooper();
601         if (looper != null && looper == context.getMainLooper()) {
602             throw new IllegalStateException(
603                     "calling this from your main thread can lead to deadlock");
604         }
605     }
606 }
607