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