KeyChain.java revision da23618043667e9cee680688b7413f65b400516e
1b9a07c18e678da35b4c2a618b315fa174a21e818Brian Carlstrom/*
2b9a07c18e678da35b4c2a618b315fa174a21e818Brian Carlstrom * Copyright (C) 2011 The Android Open Source Project
3b9a07c18e678da35b4c2a618b315fa174a21e818Brian Carlstrom *
4b9a07c18e678da35b4c2a618b315fa174a21e818Brian Carlstrom * Licensed under the Apache License, Version 2.0 (the "License");
5b9a07c18e678da35b4c2a618b315fa174a21e818Brian Carlstrom * you may not use this file except in compliance with the License.
6b9a07c18e678da35b4c2a618b315fa174a21e818Brian Carlstrom * You may obtain a copy of the License at
7b9a07c18e678da35b4c2a618b315fa174a21e818Brian Carlstrom *
8b9a07c18e678da35b4c2a618b315fa174a21e818Brian Carlstrom *      http://www.apache.org/licenses/LICENSE-2.0
9b9a07c18e678da35b4c2a618b315fa174a21e818Brian Carlstrom *
10b9a07c18e678da35b4c2a618b315fa174a21e818Brian Carlstrom * Unless required by applicable law or agreed to in writing, software
11b9a07c18e678da35b4c2a618b315fa174a21e818Brian Carlstrom * distributed under the License is distributed on an "AS IS" BASIS,
12b9a07c18e678da35b4c2a618b315fa174a21e818Brian Carlstrom * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13b9a07c18e678da35b4c2a618b315fa174a21e818Brian Carlstrom * See the License for the specific language governing permissions and
14b9a07c18e678da35b4c2a618b315fa174a21e818Brian Carlstrom * limitations under the License.
15b9a07c18e678da35b4c2a618b315fa174a21e818Brian Carlstrom */
16b9a07c18e678da35b4c2a618b315fa174a21e818Brian Carlstrompackage android.security;
17b9a07c18e678da35b4c2a618b315fa174a21e818Brian Carlstrom
1854bb1596e470144932943046ec7a99551d020ba0Alex Klyubinimport android.annotation.NonNull;
1954bb1596e470144932943046ec7a99551d020ba0Alex Klyubinimport android.annotation.Nullable;
2059e3baa8ab08c4da270023540ba15268c87e0d67Robin Leeimport android.annotation.WorkerThread;
21ba1a667b1d6c95050f6c88316ac58fe9e0ff878bBrian Carlstromimport android.app.Activity;
2267c30dfe8e4bff11a4660ac23e8679b5deb59457Brian Carlstromimport android.app.PendingIntent;
23da23618043667e9cee680688b7413f65b400516eRobin Leeimport android.app.Service;
24b9a07c18e678da35b4c2a618b315fa174a21e818Brian Carlstromimport android.content.ComponentName;
25b9a07c18e678da35b4c2a618b315fa174a21e818Brian Carlstromimport android.content.Context;
26b9a07c18e678da35b4c2a618b315fa174a21e818Brian Carlstromimport android.content.Intent;
27b9a07c18e678da35b4c2a618b315fa174a21e818Brian Carlstromimport android.content.ServiceConnection;
2839087b1cec6a54e96ab9eafe8317952720790533Robin Leeimport android.net.Uri;
29b9a07c18e678da35b4c2a618b315fa174a21e818Brian Carlstromimport android.os.IBinder;
30b9a07c18e678da35b4c2a618b315fa174a21e818Brian Carlstromimport android.os.Looper;
31306fe08ce2b06671336e67a87afaa0851f0105ebRobin Leeimport android.os.Process;
32b9a07c18e678da35b4c2a618b315fa174a21e818Brian Carlstromimport android.os.RemoteException;
33306fe08ce2b06671336e67a87afaa0851f0105ebRobin Leeimport android.os.UserHandle;
344a0ff7ca984d29bd34b02e54441957cad65e8b53Alex Klyubinimport android.security.keystore.AndroidKeyStoreProvider;
353f8d4d840894468f2be8a5b56ff266cef2d71c50Alex Klyubinimport android.security.keystore.KeyProperties;
363f8d4d840894468f2be8a5b56ff266cef2d71c50Alex Klyubin
37b9a07c18e678da35b4c2a618b315fa174a21e818Brian Carlstromimport java.io.ByteArrayInputStream;
38d752472d9abf03fda637d43716bc6bd632e1f5c3Brian Carlstromimport java.io.Closeable;
3993201f545b67da15cb69830a5988810aef52c0b2Brian Carlstromimport java.security.Principal;
40b9a07c18e678da35b4c2a618b315fa174a21e818Brian Carlstromimport java.security.PrivateKey;
414a0ff7ca984d29bd34b02e54441957cad65e8b53Alex Klyubinimport java.security.UnrecoverableKeyException;
42b9a07c18e678da35b4c2a618b315fa174a21e818Brian Carlstromimport java.security.cert.Certificate;
43b9a07c18e678da35b4c2a618b315fa174a21e818Brian Carlstromimport java.security.cert.CertificateException;
44b9a07c18e678da35b4c2a618b315fa174a21e818Brian Carlstromimport java.security.cert.CertificateFactory;
45b9a07c18e678da35b4c2a618b315fa174a21e818Brian Carlstromimport java.security.cert.X509Certificate;
46b43659170824dd8d753d9249fe6ccfd37c6221aeRubin Xuimport java.util.ArrayList;
47b43659170824dd8d753d9249fe6ccfd37c6221aeRubin Xuimport java.util.Collection;
48db93b78385d694402760ad63de0795f3902030d9Brian Carlstromimport java.util.List;
49b91773bce1126d28a93f73fbef18f3a79245f24eKenny Rootimport java.util.Locale;
508e9929c4d0730de4c9f01435a7cfe2db8855e24dBrian Carlstromimport java.util.concurrent.BlockingQueue;
518e9929c4d0730de4c9f01435a7cfe2db8855e24dBrian Carlstromimport java.util.concurrent.LinkedBlockingQueue;
525423e68d5dbe048ec6f042cce52a33f94184e9fbKenny Root
5312e752225aa96888358294be0d725d499a1c9f03Kenny Rootimport com.android.org.conscrypt.TrustedCertificateStore;
54b9a07c18e678da35b4c2a618b315fa174a21e818Brian Carlstrom
55b9a07c18e678da35b4c2a618b315fa174a21e818Brian Carlstrom/**
5693201f545b67da15cb69830a5988810aef52c0b2Brian Carlstrom * The {@code KeyChain} class provides access to private keys and
5793201f545b67da15cb69830a5988810aef52c0b2Brian Carlstrom * their corresponding certificate chains in credential storage.
5893201f545b67da15cb69830a5988810aef52c0b2Brian Carlstrom *
5993201f545b67da15cb69830a5988810aef52c0b2Brian Carlstrom * <p>Applications accessing the {@code KeyChain} normally go through
6093201f545b67da15cb69830a5988810aef52c0b2Brian Carlstrom * these steps:
6193201f545b67da15cb69830a5988810aef52c0b2Brian Carlstrom *
6293201f545b67da15cb69830a5988810aef52c0b2Brian Carlstrom * <ol>
6393201f545b67da15cb69830a5988810aef52c0b2Brian Carlstrom *
6493201f545b67da15cb69830a5988810aef52c0b2Brian Carlstrom * <li>Receive a callback from an {@link javax.net.ssl.X509KeyManager
6593201f545b67da15cb69830a5988810aef52c0b2Brian Carlstrom * X509KeyManager} that a private key is requested.
6693201f545b67da15cb69830a5988810aef52c0b2Brian Carlstrom *
6793201f545b67da15cb69830a5988810aef52c0b2Brian Carlstrom * <li>Call {@link #choosePrivateKeyAlias
6893201f545b67da15cb69830a5988810aef52c0b2Brian Carlstrom * choosePrivateKeyAlias} to allow the user to select from a
6993201f545b67da15cb69830a5988810aef52c0b2Brian Carlstrom * list of currently available private keys and corresponding
7093201f545b67da15cb69830a5988810aef52c0b2Brian Carlstrom * certificate chains. The chosen alias will be returned by the
7193201f545b67da15cb69830a5988810aef52c0b2Brian Carlstrom * callback {@link KeyChainAliasCallback#alias}, or null if no private
7293201f545b67da15cb69830a5988810aef52c0b2Brian Carlstrom * key is available or the user cancels the request.
7393201f545b67da15cb69830a5988810aef52c0b2Brian Carlstrom *
7493201f545b67da15cb69830a5988810aef52c0b2Brian Carlstrom * <li>Call {@link #getPrivateKey} and {@link #getCertificateChain} to
7593201f545b67da15cb69830a5988810aef52c0b2Brian Carlstrom * retrieve the credentials to return to the corresponding {@link
7693201f545b67da15cb69830a5988810aef52c0b2Brian Carlstrom * javax.net.ssl.X509KeyManager} callbacks.
7793201f545b67da15cb69830a5988810aef52c0b2Brian Carlstrom *
7893201f545b67da15cb69830a5988810aef52c0b2Brian Carlstrom * </ol>
7993201f545b67da15cb69830a5988810aef52c0b2Brian Carlstrom *
8093201f545b67da15cb69830a5988810aef52c0b2Brian Carlstrom * <p>An application may remember the value of a selected alias to
8193201f545b67da15cb69830a5988810aef52c0b2Brian Carlstrom * avoid prompting the user with {@link #choosePrivateKeyAlias
8293201f545b67da15cb69830a5988810aef52c0b2Brian Carlstrom * choosePrivateKeyAlias} on subsequent connections. If the alias is
8393201f545b67da15cb69830a5988810aef52c0b2Brian Carlstrom * no longer valid, null will be returned on lookups using that value
84ca43c458ad0ee8cfa7f5eabc8ba1a65ae473976bBrian Carlstrom *
85ca43c458ad0ee8cfa7f5eabc8ba1a65ae473976bBrian Carlstrom * <p>An application can request the installation of private keys and
86ca43c458ad0ee8cfa7f5eabc8ba1a65ae473976bBrian Carlstrom * certificates via the {@code Intent} provided by {@link
87ca43c458ad0ee8cfa7f5eabc8ba1a65ae473976bBrian Carlstrom * #createInstallIntent}. Private keys installed via this {@code
88ca43c458ad0ee8cfa7f5eabc8ba1a65ae473976bBrian Carlstrom * Intent} will be accessible via {@link #choosePrivateKeyAlias} while
89ca43c458ad0ee8cfa7f5eabc8ba1a65ae473976bBrian Carlstrom * Certificate Authority (CA) certificates will be trusted by all
90ca43c458ad0ee8cfa7f5eabc8ba1a65ae473976bBrian Carlstrom * applications through the default {@code X509TrustManager}.
91b9a07c18e678da35b4c2a618b315fa174a21e818Brian Carlstrom */
9293201f545b67da15cb69830a5988810aef52c0b2Brian Carlstrom// TODO reference intent for credential installation when public
93b9a07c18e678da35b4c2a618b315fa174a21e818Brian Carlstrompublic final class KeyChain {
94b9a07c18e678da35b4c2a618b315fa174a21e818Brian Carlstrom
95b9a07c18e678da35b4c2a618b315fa174a21e818Brian Carlstrom    /**
96b9a07c18e678da35b4c2a618b315fa174a21e818Brian Carlstrom     * @hide Also used by KeyChainService implementation
97b9a07c18e678da35b4c2a618b315fa174a21e818Brian Carlstrom     */
98b9a07c18e678da35b4c2a618b315fa174a21e818Brian Carlstrom    public static final String ACCOUNT_TYPE = "com.android.keychain";
99b9a07c18e678da35b4c2a618b315fa174a21e818Brian Carlstrom
100b9a07c18e678da35b4c2a618b315fa174a21e818Brian Carlstrom    /**
101a365906e670c89674fb3383b5bcb33e682910c29Kenny Root     * Package name for KeyChain chooser.
102a365906e670c89674fb3383b5bcb33e682910c29Kenny Root     */
103a365906e670c89674fb3383b5bcb33e682910c29Kenny Root    private static final String KEYCHAIN_PACKAGE = "com.android.keychain";
104a365906e670c89674fb3383b5bcb33e682910c29Kenny Root
105a365906e670c89674fb3383b5bcb33e682910c29Kenny Root    /**
106a00a2b33ccc6bc079c3ee57a938f62947b48a001Brian Carlstrom     * Action to bring up the KeyChainActivity
107a00a2b33ccc6bc079c3ee57a938f62947b48a001Brian Carlstrom     */
108a00a2b33ccc6bc079c3ee57a938f62947b48a001Brian Carlstrom    private static final String ACTION_CHOOSER = "com.android.keychain.CHOOSER";
109a00a2b33ccc6bc079c3ee57a938f62947b48a001Brian Carlstrom
110a00a2b33ccc6bc079c3ee57a938f62947b48a001Brian Carlstrom    /**
1111a88d834e8f7d21e714121c011fec82369a2e9f1Kenny Root     * Package name for the Certificate Installer.
1121a88d834e8f7d21e714121c011fec82369a2e9f1Kenny Root     */
1131a88d834e8f7d21e714121c011fec82369a2e9f1Kenny Root    private static final String CERT_INSTALLER_PACKAGE = "com.android.certinstaller";
1141a88d834e8f7d21e714121c011fec82369a2e9f1Kenny Root
1151a88d834e8f7d21e714121c011fec82369a2e9f1Kenny Root    /**
116a00a2b33ccc6bc079c3ee57a938f62947b48a001Brian Carlstrom     * Extra for use with {@link #ACTION_CHOOSER}
117ba1a667b1d6c95050f6c88316ac58fe9e0ff878bBrian Carlstrom     * @hide Also used by KeyChainActivity implementation
118b9a07c18e678da35b4c2a618b315fa174a21e818Brian Carlstrom     */
119ba1a667b1d6c95050f6c88316ac58fe9e0ff878bBrian Carlstrom    public static final String EXTRA_RESPONSE = "response";
120b9a07c18e678da35b4c2a618b315fa174a21e818Brian Carlstrom
121b9a07c18e678da35b4c2a618b315fa174a21e818Brian Carlstrom    /**
122a00a2b33ccc6bc079c3ee57a938f62947b48a001Brian Carlstrom     * Extra for use with {@link #ACTION_CHOOSER}
12367c30dfe8e4bff11a4660ac23e8679b5deb59457Brian Carlstrom     * @hide Also used by KeyChainActivity implementation
12467c30dfe8e4bff11a4660ac23e8679b5deb59457Brian Carlstrom     */
12539087b1cec6a54e96ab9eafe8317952720790533Robin Lee    public static final String EXTRA_URI = "uri";
1263798ed5e0b56ab03e7022a9922b50a4a25474033Robin Lee
1273798ed5e0b56ab03e7022a9922b50a4a25474033Robin Lee    /**
1283798ed5e0b56ab03e7022a9922b50a4a25474033Robin Lee     * Extra for use with {@link #ACTION_CHOOSER}
1293798ed5e0b56ab03e7022a9922b50a4a25474033Robin Lee     * @hide Also used by KeyChainActivity implementation
1303798ed5e0b56ab03e7022a9922b50a4a25474033Robin Lee     */
13167c30dfe8e4bff11a4660ac23e8679b5deb59457Brian Carlstrom    public static final String EXTRA_ALIAS = "alias";
13267c30dfe8e4bff11a4660ac23e8679b5deb59457Brian Carlstrom
13367c30dfe8e4bff11a4660ac23e8679b5deb59457Brian Carlstrom    /**
134a00a2b33ccc6bc079c3ee57a938f62947b48a001Brian Carlstrom     * Extra for use with {@link #ACTION_CHOOSER}
13567c30dfe8e4bff11a4660ac23e8679b5deb59457Brian Carlstrom     * @hide Also used by KeyChainActivity implementation
13667c30dfe8e4bff11a4660ac23e8679b5deb59457Brian Carlstrom     */
13767c30dfe8e4bff11a4660ac23e8679b5deb59457Brian Carlstrom    public static final String EXTRA_SENDER = "sender";
13867c30dfe8e4bff11a4660ac23e8679b5deb59457Brian Carlstrom
13967c30dfe8e4bff11a4660ac23e8679b5deb59457Brian Carlstrom    /**
14093ba4fedebb78ba47c24e8472c8960ea8fdc933aSelim Gurun     * Action to bring up the CertInstaller.
141a00a2b33ccc6bc079c3ee57a938f62947b48a001Brian Carlstrom     */
142a00a2b33ccc6bc079c3ee57a938f62947b48a001Brian Carlstrom    private static final String ACTION_INSTALL = "android.credentials.INSTALL";
143a00a2b33ccc6bc079c3ee57a938f62947b48a001Brian Carlstrom
144a00a2b33ccc6bc079c3ee57a938f62947b48a001Brian Carlstrom    /**
145a00a2b33ccc6bc079c3ee57a938f62947b48a001Brian Carlstrom     * Optional extra to specify a {@code String} credential name on
146a00a2b33ccc6bc079c3ee57a938f62947b48a001Brian Carlstrom     * the {@code Intent} returned by {@link #createInstallIntent}.
147a00a2b33ccc6bc079c3ee57a938f62947b48a001Brian Carlstrom     */
148a00a2b33ccc6bc079c3ee57a938f62947b48a001Brian Carlstrom    // Compatible with old com.android.certinstaller.CredentialHelper.CERT_NAME_KEY
149a00a2b33ccc6bc079c3ee57a938f62947b48a001Brian Carlstrom    public static final String EXTRA_NAME = "name";
150a00a2b33ccc6bc079c3ee57a938f62947b48a001Brian Carlstrom
151a00a2b33ccc6bc079c3ee57a938f62947b48a001Brian Carlstrom    /**
152a00a2b33ccc6bc079c3ee57a938f62947b48a001Brian Carlstrom     * Optional extra to specify an X.509 certificate to install on
153a00a2b33ccc6bc079c3ee57a938f62947b48a001Brian Carlstrom     * the {@code Intent} returned by {@link #createInstallIntent}.
154a00a2b33ccc6bc079c3ee57a938f62947b48a001Brian Carlstrom     * The extra value should be a PEM or ASN.1 DER encoded {@code
155a00a2b33ccc6bc079c3ee57a938f62947b48a001Brian Carlstrom     * byte[]}. An {@link X509Certificate} can be converted to DER
156a00a2b33ccc6bc079c3ee57a938f62947b48a001Brian Carlstrom     * encoded bytes with {@link X509Certificate#getEncoded}.
157a00a2b33ccc6bc079c3ee57a938f62947b48a001Brian Carlstrom     *
158a00a2b33ccc6bc079c3ee57a938f62947b48a001Brian Carlstrom     * <p>{@link #EXTRA_NAME} may be used to provide a default alias
159a00a2b33ccc6bc079c3ee57a938f62947b48a001Brian Carlstrom     * name for the installed certificate.
160a00a2b33ccc6bc079c3ee57a938f62947b48a001Brian Carlstrom     */
161a00a2b33ccc6bc079c3ee57a938f62947b48a001Brian Carlstrom    // Compatible with old android.security.Credentials.CERTIFICATE
162a00a2b33ccc6bc079c3ee57a938f62947b48a001Brian Carlstrom    public static final String EXTRA_CERTIFICATE = "CERT";
163a00a2b33ccc6bc079c3ee57a938f62947b48a001Brian Carlstrom
164a00a2b33ccc6bc079c3ee57a938f62947b48a001Brian Carlstrom    /**
165a00a2b33ccc6bc079c3ee57a938f62947b48a001Brian Carlstrom     * Optional extra for use with the {@code Intent} returned by
166a00a2b33ccc6bc079c3ee57a938f62947b48a001Brian Carlstrom     * {@link #createInstallIntent} to specify a PKCS#12 key store to
167a00a2b33ccc6bc079c3ee57a938f62947b48a001Brian Carlstrom     * install. The extra value should be a {@code byte[]}. The bytes
168a00a2b33ccc6bc079c3ee57a938f62947b48a001Brian Carlstrom     * may come from an external source or be generated with {@link
169ca43c458ad0ee8cfa7f5eabc8ba1a65ae473976bBrian Carlstrom     * java.security.KeyStore#store} on a "PKCS12" instance.
170a00a2b33ccc6bc079c3ee57a938f62947b48a001Brian Carlstrom     *
171a00a2b33ccc6bc079c3ee57a938f62947b48a001Brian Carlstrom     * <p>The user will be prompted for the password to load the key store.
172a00a2b33ccc6bc079c3ee57a938f62947b48a001Brian Carlstrom     *
173a00a2b33ccc6bc079c3ee57a938f62947b48a001Brian Carlstrom     * <p>The key store will be scanned for {@link
174a00a2b33ccc6bc079c3ee57a938f62947b48a001Brian Carlstrom     * java.security.KeyStore.PrivateKeyEntry} entries and both the
175a00a2b33ccc6bc079c3ee57a938f62947b48a001Brian Carlstrom     * private key and associated certificate chain will be installed.
176a00a2b33ccc6bc079c3ee57a938f62947b48a001Brian Carlstrom     *
177a00a2b33ccc6bc079c3ee57a938f62947b48a001Brian Carlstrom     * <p>{@link #EXTRA_NAME} may be used to provide a default alias
178a00a2b33ccc6bc079c3ee57a938f62947b48a001Brian Carlstrom     * name for the installed credentials.
179a00a2b33ccc6bc079c3ee57a938f62947b48a001Brian Carlstrom     */
180a00a2b33ccc6bc079c3ee57a938f62947b48a001Brian Carlstrom    // Compatible with old android.security.Credentials.PKCS12
181a00a2b33ccc6bc079c3ee57a938f62947b48a001Brian Carlstrom    public static final String EXTRA_PKCS12 = "PKCS12";
182a00a2b33ccc6bc079c3ee57a938f62947b48a001Brian Carlstrom
18393ba4fedebb78ba47c24e8472c8960ea8fdc933aSelim Gurun
18493ba4fedebb78ba47c24e8472c8960ea8fdc933aSelim Gurun    /**
18593ba4fedebb78ba47c24e8472c8960ea8fdc933aSelim Gurun     * Broadcast Action: Indicates the trusted storage has changed. Sent when
18693ba4fedebb78ba47c24e8472c8960ea8fdc933aSelim Gurun     * one of this happens:
18793ba4fedebb78ba47c24e8472c8960ea8fdc933aSelim Gurun     *
18893ba4fedebb78ba47c24e8472c8960ea8fdc933aSelim Gurun     * <ul>
18993ba4fedebb78ba47c24e8472c8960ea8fdc933aSelim Gurun     * <li>a new CA is added,
19093ba4fedebb78ba47c24e8472c8960ea8fdc933aSelim Gurun     * <li>an existing CA is removed or disabled,
19193ba4fedebb78ba47c24e8472c8960ea8fdc933aSelim Gurun     * <li>a disabled CA is enabled,
19293ba4fedebb78ba47c24e8472c8960ea8fdc933aSelim Gurun     * <li>trusted storage is reset (all user certs are cleared),
19393ba4fedebb78ba47c24e8472c8960ea8fdc933aSelim Gurun     * <li>when permission to access a private key is changed.
19493ba4fedebb78ba47c24e8472c8960ea8fdc933aSelim Gurun     * </ul>
19593ba4fedebb78ba47c24e8472c8960ea8fdc933aSelim Gurun     */
19693ba4fedebb78ba47c24e8472c8960ea8fdc933aSelim Gurun    public static final String ACTION_STORAGE_CHANGED = "android.security.STORAGE_CHANGED";
19793ba4fedebb78ba47c24e8472c8960ea8fdc933aSelim Gurun
198a00a2b33ccc6bc079c3ee57a938f62947b48a001Brian Carlstrom    /**
199a00a2b33ccc6bc079c3ee57a938f62947b48a001Brian Carlstrom     * Returns an {@code Intent} that can be used for credential
200a00a2b33ccc6bc079c3ee57a938f62947b48a001Brian Carlstrom     * installation. The intent may be used without any extras, in
201a00a2b33ccc6bc079c3ee57a938f62947b48a001Brian Carlstrom     * which case the user will be able to install credentials from
202a00a2b33ccc6bc079c3ee57a938f62947b48a001Brian Carlstrom     * their own source.
203a00a2b33ccc6bc079c3ee57a938f62947b48a001Brian Carlstrom     *
204a00a2b33ccc6bc079c3ee57a938f62947b48a001Brian Carlstrom     * <p>Alternatively, {@link #EXTRA_CERTIFICATE} or {@link
205a00a2b33ccc6bc079c3ee57a938f62947b48a001Brian Carlstrom     * #EXTRA_PKCS12} maybe used to specify the bytes of an X.509
206a00a2b33ccc6bc079c3ee57a938f62947b48a001Brian Carlstrom     * certificate or a PKCS#12 key store for installation. These
207ca43c458ad0ee8cfa7f5eabc8ba1a65ae473976bBrian Carlstrom     * extras may be combined with {@link #EXTRA_NAME} to provide a
208a00a2b33ccc6bc079c3ee57a938f62947b48a001Brian Carlstrom     * default alias name for credentials being installed.
209a00a2b33ccc6bc079c3ee57a938f62947b48a001Brian Carlstrom     *
210a00a2b33ccc6bc079c3ee57a938f62947b48a001Brian Carlstrom     * <p>When used with {@link Activity#startActivityForResult},
211a00a2b33ccc6bc079c3ee57a938f62947b48a001Brian Carlstrom     * {@link Activity#RESULT_OK} will be returned if a credential was
212a00a2b33ccc6bc079c3ee57a938f62947b48a001Brian Carlstrom     * successfully installed, otherwise {@link
213a00a2b33ccc6bc079c3ee57a938f62947b48a001Brian Carlstrom     * Activity#RESULT_CANCELED} will be returned.
214a00a2b33ccc6bc079c3ee57a938f62947b48a001Brian Carlstrom     */
21554bb1596e470144932943046ec7a99551d020ba0Alex Klyubin    @NonNull
216a00a2b33ccc6bc079c3ee57a938f62947b48a001Brian Carlstrom    public static Intent createInstallIntent() {
217a00a2b33ccc6bc079c3ee57a938f62947b48a001Brian Carlstrom        Intent intent = new Intent(ACTION_INSTALL);
2181a88d834e8f7d21e714121c011fec82369a2e9f1Kenny Root        intent.setClassName(CERT_INSTALLER_PACKAGE,
219a00a2b33ccc6bc079c3ee57a938f62947b48a001Brian Carlstrom                            "com.android.certinstaller.CertInstallerMain");
220a00a2b33ccc6bc079c3ee57a938f62947b48a001Brian Carlstrom        return intent;
221a00a2b33ccc6bc079c3ee57a938f62947b48a001Brian Carlstrom    }
222a00a2b33ccc6bc079c3ee57a938f62947b48a001Brian Carlstrom
223a00a2b33ccc6bc079c3ee57a938f62947b48a001Brian Carlstrom    /**
224ba1a667b1d6c95050f6c88316ac58fe9e0ff878bBrian Carlstrom     * Launches an {@code Activity} for the user to select the alias
225ba1a667b1d6c95050f6c88316ac58fe9e0ff878bBrian Carlstrom     * for a private key and certificate pair for authentication. The
226ba1a667b1d6c95050f6c88316ac58fe9e0ff878bBrian Carlstrom     * selected alias or null will be returned via the
22793201f545b67da15cb69830a5988810aef52c0b2Brian Carlstrom     * KeyChainAliasCallback callback.
22893201f545b67da15cb69830a5988810aef52c0b2Brian Carlstrom     *
2293798ed5e0b56ab03e7022a9922b50a4a25474033Robin Lee     * <p>The device or profile owner can intercept this before the activity
2303798ed5e0b56ab03e7022a9922b50a4a25474033Robin Lee     * is shown, to pick a specific private key alias.
2313798ed5e0b56ab03e7022a9922b50a4a25474033Robin Lee     *
2323798ed5e0b56ab03e7022a9922b50a4a25474033Robin Lee     * <p>{@code keyTypes} and {@code issuers} may be used to
2333798ed5e0b56ab03e7022a9922b50a4a25474033Robin Lee     * highlight suggested choices to the user, although to cope with
2343798ed5e0b56ab03e7022a9922b50a4a25474033Robin Lee     * sometimes erroneous values provided by servers, the user may be
2353798ed5e0b56ab03e7022a9922b50a4a25474033Robin Lee     * able to override these suggestions.
2363798ed5e0b56ab03e7022a9922b50a4a25474033Robin Lee     *
2373798ed5e0b56ab03e7022a9922b50a4a25474033Robin Lee     * <p>{@code host} and {@code port} may be used to give the user
2383798ed5e0b56ab03e7022a9922b50a4a25474033Robin Lee     * more context about the server requesting the credentials.
2393798ed5e0b56ab03e7022a9922b50a4a25474033Robin Lee     *
2403798ed5e0b56ab03e7022a9922b50a4a25474033Robin Lee     * <p>{@code alias} allows the chooser to preselect an existing
2413798ed5e0b56ab03e7022a9922b50a4a25474033Robin Lee     * alias which will still be subject to user confirmation.
2423798ed5e0b56ab03e7022a9922b50a4a25474033Robin Lee     *
2433798ed5e0b56ab03e7022a9922b50a4a25474033Robin Lee     * @param activity The {@link Activity} context to use for
2443798ed5e0b56ab03e7022a9922b50a4a25474033Robin Lee     *     launching the new sub-Activity to prompt the user to select
2453798ed5e0b56ab03e7022a9922b50a4a25474033Robin Lee     *     a private key; used only to call startActivity(); must not
2463798ed5e0b56ab03e7022a9922b50a4a25474033Robin Lee     *     be null.
2473798ed5e0b56ab03e7022a9922b50a4a25474033Robin Lee     * @param response Callback to invoke when the request completes;
2483798ed5e0b56ab03e7022a9922b50a4a25474033Robin Lee     *     must not be null
2493798ed5e0b56ab03e7022a9922b50a4a25474033Robin Lee     * @param keyTypes The acceptable types of asymmetric keys such as
2503798ed5e0b56ab03e7022a9922b50a4a25474033Robin Lee     *     "RSA" or "DSA", or a null array.
2513798ed5e0b56ab03e7022a9922b50a4a25474033Robin Lee     * @param issuers The acceptable certificate issuers for the
2523798ed5e0b56ab03e7022a9922b50a4a25474033Robin Lee     *     certificate matching the private key, or null.
2533798ed5e0b56ab03e7022a9922b50a4a25474033Robin Lee     * @param host The host name of the server requesting the
2543798ed5e0b56ab03e7022a9922b50a4a25474033Robin Lee     *     certificate, or null if unavailable.
2553798ed5e0b56ab03e7022a9922b50a4a25474033Robin Lee     * @param port The port number of the server requesting the
2563798ed5e0b56ab03e7022a9922b50a4a25474033Robin Lee     *     certificate, or -1 if unavailable.
2573798ed5e0b56ab03e7022a9922b50a4a25474033Robin Lee     * @param alias The alias to preselect if available, or null if
2583798ed5e0b56ab03e7022a9922b50a4a25474033Robin Lee     *     unavailable.
2593798ed5e0b56ab03e7022a9922b50a4a25474033Robin Lee     */
26054bb1596e470144932943046ec7a99551d020ba0Alex Klyubin    public static void choosePrivateKeyAlias(@NonNull Activity activity,
26154bb1596e470144932943046ec7a99551d020ba0Alex Klyubin            @NonNull KeyChainAliasCallback response,
2623f8d4d840894468f2be8a5b56ff266cef2d71c50Alex Klyubin            @KeyProperties.KeyAlgorithmEnum String[] keyTypes, Principal[] issuers,
26354bb1596e470144932943046ec7a99551d020ba0Alex Klyubin            @Nullable String host, int port, @Nullable String alias) {
26439087b1cec6a54e96ab9eafe8317952720790533Robin Lee        Uri uri = null;
26539087b1cec6a54e96ab9eafe8317952720790533Robin Lee        if (host != null) {
26639087b1cec6a54e96ab9eafe8317952720790533Robin Lee            uri = new Uri.Builder()
26739087b1cec6a54e96ab9eafe8317952720790533Robin Lee                    .authority(host + (port != -1 ? ":" + port : ""))
26839087b1cec6a54e96ab9eafe8317952720790533Robin Lee                    .build();
26939087b1cec6a54e96ab9eafe8317952720790533Robin Lee        }
27039087b1cec6a54e96ab9eafe8317952720790533Robin Lee        choosePrivateKeyAlias(activity, response, keyTypes, issuers, uri, alias);
2713798ed5e0b56ab03e7022a9922b50a4a25474033Robin Lee    }
2723798ed5e0b56ab03e7022a9922b50a4a25474033Robin Lee
2733798ed5e0b56ab03e7022a9922b50a4a25474033Robin Lee    /**
2743798ed5e0b56ab03e7022a9922b50a4a25474033Robin Lee     * Launches an {@code Activity} for the user to select the alias
2753798ed5e0b56ab03e7022a9922b50a4a25474033Robin Lee     * for a private key and certificate pair for authentication. The
2763798ed5e0b56ab03e7022a9922b50a4a25474033Robin Lee     * selected alias or null will be returned via the
2773798ed5e0b56ab03e7022a9922b50a4a25474033Robin Lee     * KeyChainAliasCallback callback.
2783798ed5e0b56ab03e7022a9922b50a4a25474033Robin Lee     *
2793798ed5e0b56ab03e7022a9922b50a4a25474033Robin Lee     * <p>The device or profile owner can intercept this before the activity
2803798ed5e0b56ab03e7022a9922b50a4a25474033Robin Lee     * is shown, to pick a specific private key alias.</p>
2813798ed5e0b56ab03e7022a9922b50a4a25474033Robin Lee     *
28293201f545b67da15cb69830a5988810aef52c0b2Brian Carlstrom     * <p>{@code keyTypes} and {@code issuers} may be used to
28393201f545b67da15cb69830a5988810aef52c0b2Brian Carlstrom     * highlight suggested choices to the user, although to cope with
28493201f545b67da15cb69830a5988810aef52c0b2Brian Carlstrom     * sometimes erroneous values provided by servers, the user may be
28593201f545b67da15cb69830a5988810aef52c0b2Brian Carlstrom     * able to override these suggestions.
28693201f545b67da15cb69830a5988810aef52c0b2Brian Carlstrom     *
28793201f545b67da15cb69830a5988810aef52c0b2Brian Carlstrom     * <p>{@code host} and {@code port} may be used to give the user
28893201f545b67da15cb69830a5988810aef52c0b2Brian Carlstrom     * more context about the server requesting the credentials.
28993201f545b67da15cb69830a5988810aef52c0b2Brian Carlstrom     *
29067c30dfe8e4bff11a4660ac23e8679b5deb59457Brian Carlstrom     * <p>{@code alias} allows the chooser to preselect an existing
29167c30dfe8e4bff11a4660ac23e8679b5deb59457Brian Carlstrom     * alias which will still be subject to user confirmation.
29267c30dfe8e4bff11a4660ac23e8679b5deb59457Brian Carlstrom     *
29393201f545b67da15cb69830a5988810aef52c0b2Brian Carlstrom     * @param activity The {@link Activity} context to use for
29493201f545b67da15cb69830a5988810aef52c0b2Brian Carlstrom     *     launching the new sub-Activity to prompt the user to select
29593201f545b67da15cb69830a5988810aef52c0b2Brian Carlstrom     *     a private key; used only to call startActivity(); must not
29693201f545b67da15cb69830a5988810aef52c0b2Brian Carlstrom     *     be null.
29793201f545b67da15cb69830a5988810aef52c0b2Brian Carlstrom     * @param response Callback to invoke when the request completes;
29893201f545b67da15cb69830a5988810aef52c0b2Brian Carlstrom     *     must not be null
29993201f545b67da15cb69830a5988810aef52c0b2Brian Carlstrom     * @param keyTypes The acceptable types of asymmetric keys such as
300cd2329dbfa5aef82c38ffa36a478bbaf5088af92Alex Klyubin     *     "EC" or "RSA", or a null array.
30193201f545b67da15cb69830a5988810aef52c0b2Brian Carlstrom     * @param issuers The acceptable certificate issuers for the
30293201f545b67da15cb69830a5988810aef52c0b2Brian Carlstrom     *     certificate matching the private key, or null.
30339087b1cec6a54e96ab9eafe8317952720790533Robin Lee     * @param uri The full URI the server is requesting the certificate
3043798ed5e0b56ab03e7022a9922b50a4a25474033Robin Lee     *     for, or null if unavailable.
30567c30dfe8e4bff11a4660ac23e8679b5deb59457Brian Carlstrom     * @param alias The alias to preselect if available, or null if
30667c30dfe8e4bff11a4660ac23e8679b5deb59457Brian Carlstrom     *     unavailable.
307b9a07c18e678da35b4c2a618b315fa174a21e818Brian Carlstrom     */
30854bb1596e470144932943046ec7a99551d020ba0Alex Klyubin    public static void choosePrivateKeyAlias(@NonNull Activity activity,
30954bb1596e470144932943046ec7a99551d020ba0Alex Klyubin            @NonNull KeyChainAliasCallback response,
3103f8d4d840894468f2be8a5b56ff266cef2d71c50Alex Klyubin            @KeyProperties.KeyAlgorithmEnum String[] keyTypes, Principal[] issuers,
31139087b1cec6a54e96ab9eafe8317952720790533Robin Lee            @Nullable Uri uri, @Nullable String alias) {
31293201f545b67da15cb69830a5988810aef52c0b2Brian Carlstrom        /*
31367c30dfe8e4bff11a4660ac23e8679b5deb59457Brian Carlstrom         * TODO currently keyTypes, issuers are unused. They are meant
31467c30dfe8e4bff11a4660ac23e8679b5deb59457Brian Carlstrom         * to follow the semantics and purpose of X509KeyManager
31567c30dfe8e4bff11a4660ac23e8679b5deb59457Brian Carlstrom         * method arguments.
31693201f545b67da15cb69830a5988810aef52c0b2Brian Carlstrom         *
31793201f545b67da15cb69830a5988810aef52c0b2Brian Carlstrom         * keyTypes would allow the list to be filtered and typically
31893201f545b67da15cb69830a5988810aef52c0b2Brian Carlstrom         * will be set correctly by the server. In practice today,
319cd2329dbfa5aef82c38ffa36a478bbaf5088af92Alex Klyubin         * most all users will want only RSA or EC, and usually
32093201f545b67da15cb69830a5988810aef52c0b2Brian Carlstrom         * only a small number of certs will be available.
32193201f545b67da15cb69830a5988810aef52c0b2Brian Carlstrom         *
32293201f545b67da15cb69830a5988810aef52c0b2Brian Carlstrom         * issuers is typically not useful. Some servers historically
32393201f545b67da15cb69830a5988810aef52c0b2Brian Carlstrom         * will send the entire list of public CAs known to the
32493201f545b67da15cb69830a5988810aef52c0b2Brian Carlstrom         * server. Others will send none. If this is used, if there
32593201f545b67da15cb69830a5988810aef52c0b2Brian Carlstrom         * are no matches after applying the constraint, it should be
32693201f545b67da15cb69830a5988810aef52c0b2Brian Carlstrom         * ignored.
32793201f545b67da15cb69830a5988810aef52c0b2Brian Carlstrom         */
328ba1a667b1d6c95050f6c88316ac58fe9e0ff878bBrian Carlstrom        if (activity == null) {
329ba1a667b1d6c95050f6c88316ac58fe9e0ff878bBrian Carlstrom            throw new NullPointerException("activity == null");
330b9a07c18e678da35b4c2a618b315fa174a21e818Brian Carlstrom        }
331ba1a667b1d6c95050f6c88316ac58fe9e0ff878bBrian Carlstrom        if (response == null) {
332ba1a667b1d6c95050f6c88316ac58fe9e0ff878bBrian Carlstrom            throw new NullPointerException("response == null");
333ba1a667b1d6c95050f6c88316ac58fe9e0ff878bBrian Carlstrom        }
334a00a2b33ccc6bc079c3ee57a938f62947b48a001Brian Carlstrom        Intent intent = new Intent(ACTION_CHOOSER);
335a365906e670c89674fb3383b5bcb33e682910c29Kenny Root        intent.setPackage(KEYCHAIN_PACKAGE);
336ab8b84ad3847788d83da557606aa27d4102e6b52Fred Quintana        intent.putExtra(EXTRA_RESPONSE, new AliasResponse(response));
33739087b1cec6a54e96ab9eafe8317952720790533Robin Lee        intent.putExtra(EXTRA_URI, uri);
33867c30dfe8e4bff11a4660ac23e8679b5deb59457Brian Carlstrom        intent.putExtra(EXTRA_ALIAS, alias);
33967c30dfe8e4bff11a4660ac23e8679b5deb59457Brian Carlstrom        // the PendingIntent is used to get calling package name
34067c30dfe8e4bff11a4660ac23e8679b5deb59457Brian Carlstrom        intent.putExtra(EXTRA_SENDER, PendingIntent.getActivity(activity, 0, new Intent(), 0));
341ba1a667b1d6c95050f6c88316ac58fe9e0ff878bBrian Carlstrom        activity.startActivity(intent);
342ba1a667b1d6c95050f6c88316ac58fe9e0ff878bBrian Carlstrom    }
343ba1a667b1d6c95050f6c88316ac58fe9e0ff878bBrian Carlstrom
34493201f545b67da15cb69830a5988810aef52c0b2Brian Carlstrom    private static class AliasResponse extends IKeyChainAliasCallback.Stub {
34593201f545b67da15cb69830a5988810aef52c0b2Brian Carlstrom        private final KeyChainAliasCallback keyChainAliasResponse;
346ab8b84ad3847788d83da557606aa27d4102e6b52Fred Quintana        private AliasResponse(KeyChainAliasCallback keyChainAliasResponse) {
347ba1a667b1d6c95050f6c88316ac58fe9e0ff878bBrian Carlstrom            this.keyChainAliasResponse = keyChainAliasResponse;
348ba1a667b1d6c95050f6c88316ac58fe9e0ff878bBrian Carlstrom        }
349ba1a667b1d6c95050f6c88316ac58fe9e0ff878bBrian Carlstrom        @Override public void alias(String alias) {
350ab8b84ad3847788d83da557606aa27d4102e6b52Fred Quintana            keyChainAliasResponse.alias(alias);
351ba1a667b1d6c95050f6c88316ac58fe9e0ff878bBrian Carlstrom        }
352ba1a667b1d6c95050f6c88316ac58fe9e0ff878bBrian Carlstrom    }
353b9a07c18e678da35b4c2a618b315fa174a21e818Brian Carlstrom
354ba1a667b1d6c95050f6c88316ac58fe9e0ff878bBrian Carlstrom    /**
355ba1a667b1d6c95050f6c88316ac58fe9e0ff878bBrian Carlstrom     * Returns the {@code PrivateKey} for the requested alias, or null
3563a435f03906778677b846baa7ebedadd3119e892Robin Lee     * if there is no result.
35793201f545b67da15cb69830a5988810aef52c0b2Brian Carlstrom     *
35859e3baa8ab08c4da270023540ba15268c87e0d67Robin Lee     * <p> This method may block while waiting for a connection to another process, and must never
35959e3baa8ab08c4da270023540ba15268c87e0d67Robin Lee     * be called from the main thread.
360da23618043667e9cee680688b7413f65b400516eRobin Lee     * <p> As {@link Activity} and {@link Service} contexts are short-lived and can be destroyed
361da23618043667e9cee680688b7413f65b400516eRobin Lee     * at any time from the main thread, it is safer to rely on a long-lived context such as one
362da23618043667e9cee680688b7413f65b400516eRobin Lee     * returned from {@link Context#getApplicationContext()}.
36359e3baa8ab08c4da270023540ba15268c87e0d67Robin Lee     *
36459e3baa8ab08c4da270023540ba15268c87e0d67Robin Lee     * @param alias The alias of the desired private key, typically returned via
36559e3baa8ab08c4da270023540ba15268c87e0d67Robin Lee     *              {@link KeyChainAliasCallback#alias}.
36693201f545b67da15cb69830a5988810aef52c0b2Brian Carlstrom     * @throws KeyChainException if the alias was valid but there was some problem accessing it.
36759e3baa8ab08c4da270023540ba15268c87e0d67Robin Lee     * @throws IllegalStateException if called from the main thread.
368ba1a667b1d6c95050f6c88316ac58fe9e0ff878bBrian Carlstrom     */
36959e3baa8ab08c4da270023540ba15268c87e0d67Robin Lee    @Nullable @WorkerThread
37054bb1596e470144932943046ec7a99551d020ba0Alex Klyubin    public static PrivateKey getPrivateKey(@NonNull Context context, @NonNull String alias)
37193201f545b67da15cb69830a5988810aef52c0b2Brian Carlstrom            throws KeyChainException, InterruptedException {
372ba1a667b1d6c95050f6c88316ac58fe9e0ff878bBrian Carlstrom        if (alias == null) {
373ba1a667b1d6c95050f6c88316ac58fe9e0ff878bBrian Carlstrom            throw new NullPointerException("alias == null");
374ba1a667b1d6c95050f6c88316ac58fe9e0ff878bBrian Carlstrom        }
375ba1a667b1d6c95050f6c88316ac58fe9e0ff878bBrian Carlstrom        KeyChainConnection keyChainConnection = bind(context);
376ba1a667b1d6c95050f6c88316ac58fe9e0ff878bBrian Carlstrom        try {
3775423e68d5dbe048ec6f042cce52a33f94184e9fbKenny Root            final IKeyChainService keyChainService = keyChainConnection.getService();
3785423e68d5dbe048ec6f042cce52a33f94184e9fbKenny Root            final String keyId = keyChainService.requestPrivateKey(alias);
3795423e68d5dbe048ec6f042cce52a33f94184e9fbKenny Root            if (keyId == null) {
3803a435f03906778677b846baa7ebedadd3119e892Robin Lee                return null;
3815423e68d5dbe048ec6f042cce52a33f94184e9fbKenny Root            }
3824a0ff7ca984d29bd34b02e54441957cad65e8b53Alex Klyubin            return AndroidKeyStoreProvider.loadAndroidKeyStorePrivateKeyFromKeystore(
3833876b1be27e3aefde9a72eb2e4f856e94fc5f946Alex Klyubin                    KeyStore.getInstance(), keyId, KeyStore.UID_SELF);
38493201f545b67da15cb69830a5988810aef52c0b2Brian Carlstrom        } catch (RemoteException e) {
38593201f545b67da15cb69830a5988810aef52c0b2Brian Carlstrom            throw new KeyChainException(e);
38693201f545b67da15cb69830a5988810aef52c0b2Brian Carlstrom        } catch (RuntimeException e) {
38793201f545b67da15cb69830a5988810aef52c0b2Brian Carlstrom            // only certain RuntimeExceptions can be propagated across the IKeyChainService call
38893201f545b67da15cb69830a5988810aef52c0b2Brian Carlstrom            throw new KeyChainException(e);
3894a0ff7ca984d29bd34b02e54441957cad65e8b53Alex Klyubin        } catch (UnrecoverableKeyException e) {
3905423e68d5dbe048ec6f042cce52a33f94184e9fbKenny Root            throw new KeyChainException(e);
391ba1a667b1d6c95050f6c88316ac58fe9e0ff878bBrian Carlstrom        } finally {
392ba1a667b1d6c95050f6c88316ac58fe9e0ff878bBrian Carlstrom            keyChainConnection.close();
393ba1a667b1d6c95050f6c88316ac58fe9e0ff878bBrian Carlstrom        }
394ba1a667b1d6c95050f6c88316ac58fe9e0ff878bBrian Carlstrom    }
395ba1a667b1d6c95050f6c88316ac58fe9e0ff878bBrian Carlstrom
396ba1a667b1d6c95050f6c88316ac58fe9e0ff878bBrian Carlstrom    /**
397ba1a667b1d6c95050f6c88316ac58fe9e0ff878bBrian Carlstrom     * Returns the {@code X509Certificate} chain for the requested
398b43659170824dd8d753d9249fe6ccfd37c6221aeRubin Xu     * alias, or null if there is no result.
399b43659170824dd8d753d9249fe6ccfd37c6221aeRubin Xu     * <p>
400b43659170824dd8d753d9249fe6ccfd37c6221aeRubin Xu     * <strong>Note:</strong> If a certificate chain was explicitly specified when the alias was
401b43659170824dd8d753d9249fe6ccfd37c6221aeRubin Xu     * installed, this method will return that chain. If only the client certificate was specified
402b43659170824dd8d753d9249fe6ccfd37c6221aeRubin Xu     * at the installation time, this method will try to build a certificate chain using all
403b43659170824dd8d753d9249fe6ccfd37c6221aeRubin Xu     * available trust anchors (preinstalled and user-added).
40493201f545b67da15cb69830a5988810aef52c0b2Brian Carlstrom     *
40559e3baa8ab08c4da270023540ba15268c87e0d67Robin Lee     * <p> This method may block while waiting for a connection to another process, and must never
40659e3baa8ab08c4da270023540ba15268c87e0d67Robin Lee     * be called from the main thread.
407da23618043667e9cee680688b7413f65b400516eRobin Lee     * <p> As {@link Activity} and {@link Service} contexts are short-lived and can be destroyed
408da23618043667e9cee680688b7413f65b400516eRobin Lee     * at any time from the main thread, it is safer to rely on a long-lived context such as one
409da23618043667e9cee680688b7413f65b400516eRobin Lee     * returned from {@link Context#getApplicationContext()}.
41059e3baa8ab08c4da270023540ba15268c87e0d67Robin Lee     *
41193201f545b67da15cb69830a5988810aef52c0b2Brian Carlstrom     * @param alias The alias of the desired certificate chain, typically
41293201f545b67da15cb69830a5988810aef52c0b2Brian Carlstrom     * returned via {@link KeyChainAliasCallback#alias}.
41393201f545b67da15cb69830a5988810aef52c0b2Brian Carlstrom     * @throws KeyChainException if the alias was valid but there was some problem accessing it.
41459e3baa8ab08c4da270023540ba15268c87e0d67Robin Lee     * @throws IllegalStateException if called from the main thread.
415ba1a667b1d6c95050f6c88316ac58fe9e0ff878bBrian Carlstrom     */
41659e3baa8ab08c4da270023540ba15268c87e0d67Robin Lee    @Nullable @WorkerThread
41754bb1596e470144932943046ec7a99551d020ba0Alex Klyubin    public static X509Certificate[] getCertificateChain(@NonNull Context context,
41854bb1596e470144932943046ec7a99551d020ba0Alex Klyubin            @NonNull String alias) throws KeyChainException, InterruptedException {
419ba1a667b1d6c95050f6c88316ac58fe9e0ff878bBrian Carlstrom        if (alias == null) {
420ba1a667b1d6c95050f6c88316ac58fe9e0ff878bBrian Carlstrom            throw new NullPointerException("alias == null");
421ba1a667b1d6c95050f6c88316ac58fe9e0ff878bBrian Carlstrom        }
422ba1a667b1d6c95050f6c88316ac58fe9e0ff878bBrian Carlstrom        KeyChainConnection keyChainConnection = bind(context);
423ba1a667b1d6c95050f6c88316ac58fe9e0ff878bBrian Carlstrom        try {
424ba1a667b1d6c95050f6c88316ac58fe9e0ff878bBrian Carlstrom            IKeyChainService keyChainService = keyChainConnection.getService();
4250150e48200a967aead3c2ac6f1283ae2df54c305Kenny Root
4260150e48200a967aead3c2ac6f1283ae2df54c305Kenny Root            final byte[] certificateBytes = keyChainService.getCertificate(alias);
4270150e48200a967aead3c2ac6f1283ae2df54c305Kenny Root            if (certificateBytes == null) {
4280150e48200a967aead3c2ac6f1283ae2df54c305Kenny Root                return null;
4290150e48200a967aead3c2ac6f1283ae2df54c305Kenny Root            }
430b43659170824dd8d753d9249fe6ccfd37c6221aeRubin Xu            X509Certificate leafCert = toCertificate(certificateBytes);
431b43659170824dd8d753d9249fe6ccfd37c6221aeRubin Xu            final byte[] certChainBytes = keyChainService.getCaCertificates(alias);
432b43659170824dd8d753d9249fe6ccfd37c6221aeRubin Xu            // If the keypair is installed with a certificate chain by either
433b43659170824dd8d753d9249fe6ccfd37c6221aeRubin Xu            // DevicePolicyManager.installKeyPair or CertInstaller, return that chain.
434b43659170824dd8d753d9249fe6ccfd37c6221aeRubin Xu            if (certChainBytes != null && certChainBytes.length != 0) {
435b43659170824dd8d753d9249fe6ccfd37c6221aeRubin Xu                Collection<X509Certificate> chain = toCertificates(certChainBytes);
436b43659170824dd8d753d9249fe6ccfd37c6221aeRubin Xu                ArrayList<X509Certificate> fullChain = new ArrayList<>(chain.size() + 1);
437b43659170824dd8d753d9249fe6ccfd37c6221aeRubin Xu                fullChain.add(leafCert);
438b43659170824dd8d753d9249fe6ccfd37c6221aeRubin Xu                fullChain.addAll(chain);
439b43659170824dd8d753d9249fe6ccfd37c6221aeRubin Xu                return fullChain.toArray(new X509Certificate[fullChain.size()]);
440b43659170824dd8d753d9249fe6ccfd37c6221aeRubin Xu            } else {
441b43659170824dd8d753d9249fe6ccfd37c6221aeRubin Xu                // If there isn't a certificate chain, either due to a pre-existing keypair
442b43659170824dd8d753d9249fe6ccfd37c6221aeRubin Xu                // installed before N, or no chain is explicitly installed under the new logic,
443b43659170824dd8d753d9249fe6ccfd37c6221aeRubin Xu                // fall back to old behavior of constructing the chain from trusted credentials.
444b43659170824dd8d753d9249fe6ccfd37c6221aeRubin Xu                //
445b43659170824dd8d753d9249fe6ccfd37c6221aeRubin Xu                // This logic exists to maintain old behaviour for already installed keypair, at
446b43659170824dd8d753d9249fe6ccfd37c6221aeRubin Xu                // the cost of potentially returning extra certificate chain for new clients who
447b43659170824dd8d753d9249fe6ccfd37c6221aeRubin Xu                // explicitly installed only the client certificate without a chain. The latter
448b43659170824dd8d753d9249fe6ccfd37c6221aeRubin Xu                // case is actually no different from pre-N behaviour of getCertificateChain(),
449b43659170824dd8d753d9249fe6ccfd37c6221aeRubin Xu                // in that sense this change introduces no regression. Besides the returned chain
450b43659170824dd8d753d9249fe6ccfd37c6221aeRubin Xu                // is still valid so the consumer of the chain should have no problem verifying it.
451b43659170824dd8d753d9249fe6ccfd37c6221aeRubin Xu                TrustedCertificateStore store = new TrustedCertificateStore();
452b43659170824dd8d753d9249fe6ccfd37c6221aeRubin Xu                List<X509Certificate> chain = store.getCertificateChain(leafCert);
453b43659170824dd8d753d9249fe6ccfd37c6221aeRubin Xu                return chain.toArray(new X509Certificate[chain.size()]);
454b43659170824dd8d753d9249fe6ccfd37c6221aeRubin Xu            }
455cfba6a07fd24559bfb6bb51007520b8ca3cd5c48Kenny Root        } catch (CertificateException e) {
456cfba6a07fd24559bfb6bb51007520b8ca3cd5c48Kenny Root            throw new KeyChainException(e);
45793201f545b67da15cb69830a5988810aef52c0b2Brian Carlstrom        } catch (RemoteException e) {
45893201f545b67da15cb69830a5988810aef52c0b2Brian Carlstrom            throw new KeyChainException(e);
45993201f545b67da15cb69830a5988810aef52c0b2Brian Carlstrom        } catch (RuntimeException e) {
46093201f545b67da15cb69830a5988810aef52c0b2Brian Carlstrom            // only certain RuntimeExceptions can be propagated across the IKeyChainService call
46193201f545b67da15cb69830a5988810aef52c0b2Brian Carlstrom            throw new KeyChainException(e);
4628e9929c4d0730de4c9f01435a7cfe2db8855e24dBrian Carlstrom        } finally {
463d752472d9abf03fda637d43716bc6bd632e1f5c3Brian Carlstrom            keyChainConnection.close();
464b9a07c18e678da35b4c2a618b315fa174a21e818Brian Carlstrom        }
465b9a07c18e678da35b4c2a618b315fa174a21e818Brian Carlstrom    }
466b9a07c18e678da35b4c2a618b315fa174a21e818Brian Carlstrom
467bf556ac636a39c1d0fe5451a921b88400dd1c695Kenny Root    /**
468bf556ac636a39c1d0fe5451a921b88400dd1c695Kenny Root     * Returns {@code true} if the current device's {@code KeyChain} supports a
469bf556ac636a39c1d0fe5451a921b88400dd1c695Kenny Root     * specific {@code PrivateKey} type indicated by {@code algorithm} (e.g.,
470bf556ac636a39c1d0fe5451a921b88400dd1c695Kenny Root     * "RSA").
471bf556ac636a39c1d0fe5451a921b88400dd1c695Kenny Root     */
4724d5443f37f2bc58be8d22ed50024c39a5a1fbc8fAlex Klyubin    public static boolean isKeyAlgorithmSupported(
4733f8d4d840894468f2be8a5b56ff266cef2d71c50Alex Klyubin            @NonNull @KeyProperties.KeyAlgorithmEnum String algorithm) {
474b91773bce1126d28a93f73fbef18f3a79245f24eKenny Root        final String algUpper = algorithm.toUpperCase(Locale.US);
4753f8d4d840894468f2be8a5b56ff266cef2d71c50Alex Klyubin        return KeyProperties.KEY_ALGORITHM_EC.equals(algUpper)
4763f8d4d840894468f2be8a5b56ff266cef2d71c50Alex Klyubin                || KeyProperties.KEY_ALGORITHM_RSA.equals(algUpper);
477bf556ac636a39c1d0fe5451a921b88400dd1c695Kenny Root    }
478bf556ac636a39c1d0fe5451a921b88400dd1c695Kenny Root
479bf556ac636a39c1d0fe5451a921b88400dd1c695Kenny Root    /**
480bf556ac636a39c1d0fe5451a921b88400dd1c695Kenny Root     * Returns {@code true} if the current device's {@code KeyChain} binds any
481bf556ac636a39c1d0fe5451a921b88400dd1c695Kenny Root     * {@code PrivateKey} of the given {@code algorithm} to the device once
482bf556ac636a39c1d0fe5451a921b88400dd1c695Kenny Root     * imported or generated. This can be used to tell if there is special
483bf556ac636a39c1d0fe5451a921b88400dd1c695Kenny Root     * hardware support that can be used to bind keys to the device in a way
484bf556ac636a39c1d0fe5451a921b88400dd1c695Kenny Root     * that makes it non-exportable.
485469cbf5156ad54650726ade59f2ee5aa01359ec2Alex Klyubin     *
486469cbf5156ad54650726ade59f2ee5aa01359ec2Alex Klyubin     * @deprecated Whether the key is bound to the secure hardware is known only
487469cbf5156ad54650726ade59f2ee5aa01359ec2Alex Klyubin     * once the key has been imported. To find out, use:
488469cbf5156ad54650726ade59f2ee5aa01359ec2Alex Klyubin     * <pre>{@code
489469cbf5156ad54650726ade59f2ee5aa01359ec2Alex Klyubin     * PrivateKey key = ...; // private key from KeyChain
490469cbf5156ad54650726ade59f2ee5aa01359ec2Alex Klyubin     *
491469cbf5156ad54650726ade59f2ee5aa01359ec2Alex Klyubin     * KeyFactory keyFactory =
492469cbf5156ad54650726ade59f2ee5aa01359ec2Alex Klyubin     *     KeyFactory.getInstance(key.getAlgorithm(), "AndroidKeyStore");
493469cbf5156ad54650726ade59f2ee5aa01359ec2Alex Klyubin     * KeyInfo keyInfo = keyFactory.getKeySpec(key, KeyInfo.class);
49471fbb81b14958b80fe55738607740c6630e4e9daNeil Fuller     * if (keyInfo.isInsideSecureHardware()) {
495469cbf5156ad54650726ade59f2ee5aa01359ec2Alex Klyubin     *     // The key is bound to the secure hardware of this Android
49671fbb81b14958b80fe55738607740c6630e4e9daNeil Fuller     * }}</pre>
497bf556ac636a39c1d0fe5451a921b88400dd1c695Kenny Root     */
498469cbf5156ad54650726ade59f2ee5aa01359ec2Alex Klyubin    @Deprecated
4994d5443f37f2bc58be8d22ed50024c39a5a1fbc8fAlex Klyubin    public static boolean isBoundKeyAlgorithm(
5003f8d4d840894468f2be8a5b56ff266cef2d71c50Alex Klyubin            @NonNull @KeyProperties.KeyAlgorithmEnum String algorithm) {
5015b7e90ac937857c10a3d49b244ec75ca539b9a22Kenny Root        if (!isKeyAlgorithmSupported(algorithm)) {
502bf556ac636a39c1d0fe5451a921b88400dd1c695Kenny Root            return false;
503bf556ac636a39c1d0fe5451a921b88400dd1c695Kenny Root        }
504bf556ac636a39c1d0fe5451a921b88400dd1c695Kenny Root
505b91773bce1126d28a93f73fbef18f3a79245f24eKenny Root        return KeyStore.getInstance().isHardwareBacked(algorithm);
506bf556ac636a39c1d0fe5451a921b88400dd1c695Kenny Root    }
507bf556ac636a39c1d0fe5451a921b88400dd1c695Kenny Root
508f0ae135049048424bceccb0799b12377181b25f0Zoltan Szatmary-Ban    /** @hide */
50954bb1596e470144932943046ec7a99551d020ba0Alex Klyubin    @NonNull
51054bb1596e470144932943046ec7a99551d020ba0Alex Klyubin    public static X509Certificate toCertificate(@NonNull byte[] bytes) {
511b9a07c18e678da35b4c2a618b315fa174a21e818Brian Carlstrom        if (bytes == null) {
5128e9929c4d0730de4c9f01435a7cfe2db8855e24dBrian Carlstrom            throw new IllegalArgumentException("bytes == null");
513b9a07c18e678da35b4c2a618b315fa174a21e818Brian Carlstrom        }
514b9a07c18e678da35b4c2a618b315fa174a21e818Brian Carlstrom        try {
515b9a07c18e678da35b4c2a618b315fa174a21e818Brian Carlstrom            CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
516b9a07c18e678da35b4c2a618b315fa174a21e818Brian Carlstrom            Certificate cert = certFactory.generateCertificate(new ByteArrayInputStream(bytes));
517b9a07c18e678da35b4c2a618b315fa174a21e818Brian Carlstrom            return (X509Certificate) cert;
518b9a07c18e678da35b4c2a618b315fa174a21e818Brian Carlstrom        } catch (CertificateException e) {
519b9a07c18e678da35b4c2a618b315fa174a21e818Brian Carlstrom            throw new AssertionError(e);
520b9a07c18e678da35b4c2a618b315fa174a21e818Brian Carlstrom        }
521b9a07c18e678da35b4c2a618b315fa174a21e818Brian Carlstrom    }
522b9a07c18e678da35b4c2a618b315fa174a21e818Brian Carlstrom
523b43659170824dd8d753d9249fe6ccfd37c6221aeRubin Xu    /** @hide */
524b43659170824dd8d753d9249fe6ccfd37c6221aeRubin Xu    @NonNull
525b43659170824dd8d753d9249fe6ccfd37c6221aeRubin Xu    public static Collection<X509Certificate> toCertificates(@NonNull byte[] bytes) {
526b43659170824dd8d753d9249fe6ccfd37c6221aeRubin Xu        if (bytes == null) {
527b43659170824dd8d753d9249fe6ccfd37c6221aeRubin Xu            throw new IllegalArgumentException("bytes == null");
528b43659170824dd8d753d9249fe6ccfd37c6221aeRubin Xu        }
529b43659170824dd8d753d9249fe6ccfd37c6221aeRubin Xu        try {
530b43659170824dd8d753d9249fe6ccfd37c6221aeRubin Xu            CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
531b43659170824dd8d753d9249fe6ccfd37c6221aeRubin Xu            return (Collection<X509Certificate>) certFactory.generateCertificates(
532b43659170824dd8d753d9249fe6ccfd37c6221aeRubin Xu                    new ByteArrayInputStream(bytes));
533b43659170824dd8d753d9249fe6ccfd37c6221aeRubin Xu        } catch (CertificateException e) {
534b43659170824dd8d753d9249fe6ccfd37c6221aeRubin Xu            throw new AssertionError(e);
535b43659170824dd8d753d9249fe6ccfd37c6221aeRubin Xu        }
536b43659170824dd8d753d9249fe6ccfd37c6221aeRubin Xu    }
537b43659170824dd8d753d9249fe6ccfd37c6221aeRubin Xu
538d752472d9abf03fda637d43716bc6bd632e1f5c3Brian Carlstrom    /**
539d752472d9abf03fda637d43716bc6bd632e1f5c3Brian Carlstrom     * @hide for reuse by CertInstaller and Settings.
540d752472d9abf03fda637d43716bc6bd632e1f5c3Brian Carlstrom     * @see KeyChain#bind
541d752472d9abf03fda637d43716bc6bd632e1f5c3Brian Carlstrom     */
542d752472d9abf03fda637d43716bc6bd632e1f5c3Brian Carlstrom    public final static class KeyChainConnection implements Closeable {
543d752472d9abf03fda637d43716bc6bd632e1f5c3Brian Carlstrom        private final Context context;
544d752472d9abf03fda637d43716bc6bd632e1f5c3Brian Carlstrom        private final ServiceConnection serviceConnection;
545d752472d9abf03fda637d43716bc6bd632e1f5c3Brian Carlstrom        private final IKeyChainService service;
546d752472d9abf03fda637d43716bc6bd632e1f5c3Brian Carlstrom        private KeyChainConnection(Context context,
547d752472d9abf03fda637d43716bc6bd632e1f5c3Brian Carlstrom                                   ServiceConnection serviceConnection,
548d752472d9abf03fda637d43716bc6bd632e1f5c3Brian Carlstrom                                   IKeyChainService service) {
549d752472d9abf03fda637d43716bc6bd632e1f5c3Brian Carlstrom            this.context = context;
550d752472d9abf03fda637d43716bc6bd632e1f5c3Brian Carlstrom            this.serviceConnection = serviceConnection;
551d752472d9abf03fda637d43716bc6bd632e1f5c3Brian Carlstrom            this.service = service;
552d752472d9abf03fda637d43716bc6bd632e1f5c3Brian Carlstrom        }
553d752472d9abf03fda637d43716bc6bd632e1f5c3Brian Carlstrom        @Override public void close() {
554d752472d9abf03fda637d43716bc6bd632e1f5c3Brian Carlstrom            context.unbindService(serviceConnection);
555d752472d9abf03fda637d43716bc6bd632e1f5c3Brian Carlstrom        }
556d752472d9abf03fda637d43716bc6bd632e1f5c3Brian Carlstrom        public IKeyChainService getService() {
557d752472d9abf03fda637d43716bc6bd632e1f5c3Brian Carlstrom            return service;
558d752472d9abf03fda637d43716bc6bd632e1f5c3Brian Carlstrom        }
559d752472d9abf03fda637d43716bc6bd632e1f5c3Brian Carlstrom    }
560d752472d9abf03fda637d43716bc6bd632e1f5c3Brian Carlstrom
561d752472d9abf03fda637d43716bc6bd632e1f5c3Brian Carlstrom    /**
562d752472d9abf03fda637d43716bc6bd632e1f5c3Brian Carlstrom     * @hide for reuse by CertInstaller and Settings.
563d752472d9abf03fda637d43716bc6bd632e1f5c3Brian Carlstrom     *
564d752472d9abf03fda637d43716bc6bd632e1f5c3Brian Carlstrom     * Caller should call unbindService on the result when finished.
565d752472d9abf03fda637d43716bc6bd632e1f5c3Brian Carlstrom     */
56659e3baa8ab08c4da270023540ba15268c87e0d67Robin Lee    @WorkerThread
56754bb1596e470144932943046ec7a99551d020ba0Alex Klyubin    public static KeyChainConnection bind(@NonNull Context context) throws InterruptedException {
568306fe08ce2b06671336e67a87afaa0851f0105ebRobin Lee        return bindAsUser(context, Process.myUserHandle());
569306fe08ce2b06671336e67a87afaa0851f0105ebRobin Lee    }
570306fe08ce2b06671336e67a87afaa0851f0105ebRobin Lee
571306fe08ce2b06671336e67a87afaa0851f0105ebRobin Lee    /**
572306fe08ce2b06671336e67a87afaa0851f0105ebRobin Lee     * @hide
573306fe08ce2b06671336e67a87afaa0851f0105ebRobin Lee     */
57459e3baa8ab08c4da270023540ba15268c87e0d67Robin Lee    @WorkerThread
57554bb1596e470144932943046ec7a99551d020ba0Alex Klyubin    public static KeyChainConnection bindAsUser(@NonNull Context context, UserHandle user)
576306fe08ce2b06671336e67a87afaa0851f0105ebRobin Lee            throws InterruptedException {
577d752472d9abf03fda637d43716bc6bd632e1f5c3Brian Carlstrom        if (context == null) {
578d752472d9abf03fda637d43716bc6bd632e1f5c3Brian Carlstrom            throw new NullPointerException("context == null");
579d752472d9abf03fda637d43716bc6bd632e1f5c3Brian Carlstrom        }
580d752472d9abf03fda637d43716bc6bd632e1f5c3Brian Carlstrom        ensureNotOnMainThread(context);
581d752472d9abf03fda637d43716bc6bd632e1f5c3Brian Carlstrom        final BlockingQueue<IKeyChainService> q = new LinkedBlockingQueue<IKeyChainService>(1);
582d752472d9abf03fda637d43716bc6bd632e1f5c3Brian Carlstrom        ServiceConnection keyChainServiceConnection = new ServiceConnection() {
583ab8b84ad3847788d83da557606aa27d4102e6b52Fred Quintana            volatile boolean mConnectedAtLeastOnce = false;
584d752472d9abf03fda637d43716bc6bd632e1f5c3Brian Carlstrom            @Override public void onServiceConnected(ComponentName name, IBinder service) {
585ab8b84ad3847788d83da557606aa27d4102e6b52Fred Quintana                if (!mConnectedAtLeastOnce) {
586ab8b84ad3847788d83da557606aa27d4102e6b52Fred Quintana                    mConnectedAtLeastOnce = true;
587ab8b84ad3847788d83da557606aa27d4102e6b52Fred Quintana                    try {
588ab8b84ad3847788d83da557606aa27d4102e6b52Fred Quintana                        q.put(IKeyChainService.Stub.asInterface(service));
589ab8b84ad3847788d83da557606aa27d4102e6b52Fred Quintana                    } catch (InterruptedException e) {
590ab8b84ad3847788d83da557606aa27d4102e6b52Fred Quintana                        // will never happen, since the queue starts with one available slot
591ab8b84ad3847788d83da557606aa27d4102e6b52Fred Quintana                    }
592d752472d9abf03fda637d43716bc6bd632e1f5c3Brian Carlstrom                }
593d752472d9abf03fda637d43716bc6bd632e1f5c3Brian Carlstrom            }
594d752472d9abf03fda637d43716bc6bd632e1f5c3Brian Carlstrom            @Override public void onServiceDisconnected(ComponentName name) {}
595d752472d9abf03fda637d43716bc6bd632e1f5c3Brian Carlstrom        };
596da51e68e582ffa017543982297c831680d201a91Maggie Benthall        Intent intent = new Intent(IKeyChainService.class.getName());
597da51e68e582ffa017543982297c831680d201a91Maggie Benthall        ComponentName comp = intent.resolveSystemService(context.getPackageManager(), 0);
598da51e68e582ffa017543982297c831680d201a91Maggie Benthall        intent.setComponent(comp);
59921bcbc54dd6b1f029f4973bef27c20e55d057432Robin Lee        if (comp == null || !context.bindServiceAsUser(
60021bcbc54dd6b1f029f4973bef27c20e55d057432Robin Lee                intent, keyChainServiceConnection, Context.BIND_AUTO_CREATE, user)) {
601d752472d9abf03fda637d43716bc6bd632e1f5c3Brian Carlstrom            throw new AssertionError("could not bind to KeyChainService");
602d752472d9abf03fda637d43716bc6bd632e1f5c3Brian Carlstrom        }
603d752472d9abf03fda637d43716bc6bd632e1f5c3Brian Carlstrom        return new KeyChainConnection(context, keyChainServiceConnection, q.take());
604d752472d9abf03fda637d43716bc6bd632e1f5c3Brian Carlstrom    }
605d752472d9abf03fda637d43716bc6bd632e1f5c3Brian Carlstrom
60654bb1596e470144932943046ec7a99551d020ba0Alex Klyubin    private static void ensureNotOnMainThread(@NonNull Context context) {
607b9a07c18e678da35b4c2a618b315fa174a21e818Brian Carlstrom        Looper looper = Looper.myLooper();
6088e9929c4d0730de4c9f01435a7cfe2db8855e24dBrian Carlstrom        if (looper != null && looper == context.getMainLooper()) {
609b9a07c18e678da35b4c2a618b315fa174a21e818Brian Carlstrom            throw new IllegalStateException(
610b9a07c18e678da35b4c2a618b315fa174a21e818Brian Carlstrom                    "calling this from your main thread can lead to deadlock");
611b9a07c18e678da35b4c2a618b315fa174a21e818Brian Carlstrom        }
612b9a07c18e678da35b4c2a618b315fa174a21e818Brian Carlstrom    }
613b9a07c18e678da35b4c2a618b315fa174a21e818Brian Carlstrom}
614