blob: be9ebb58675ef753cf8ee6d2c03ff2dc39f41f95 [file] [log] [blame]
Brian Carlstromb9a07c12011-04-11 09:03:51 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16package android.security;
17
Alex Klyubin54bb1592015-05-11 12:30:03 -070018import android.annotation.NonNull;
19import android.annotation.Nullable;
Robin Lee59e3baa2015-06-30 10:48:06 -070020import android.annotation.WorkerThread;
Brian Carlstromba1a6672011-05-24 21:54:37 -070021import android.app.Activity;
Brian Carlstrom67c30df2011-06-24 02:13:23 -070022import android.app.PendingIntent;
Robin Leeda236182016-08-12 12:46:28 +010023import android.app.Service;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070024import android.content.ComponentName;
25import android.content.Context;
26import android.content.Intent;
27import android.content.ServiceConnection;
Robin Lee39087b12015-05-05 15:57:17 +010028import android.net.Uri;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070029import android.os.IBinder;
30import android.os.Looper;
Robin Lee306fe082014-06-19 14:04:24 +000031import android.os.Process;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070032import android.os.RemoteException;
Robin Lee306fe082014-06-19 14:04:24 +000033import android.os.UserHandle;
Alex Klyubin4a0ff7c2015-06-09 13:25:20 -070034import android.security.keystore.AndroidKeyStoreProvider;
Alex Klyubin3f8d4d82015-05-13 09:15:00 -070035import android.security.keystore.KeyProperties;
36
Brian Carlstromb9a07c12011-04-11 09:03:51 -070037import java.io.ByteArrayInputStream;
Brian Carlstromd7524722011-05-17 16:20:36 -070038import java.io.Closeable;
Brian Carlstrom93201f52011-06-09 15:05:35 -070039import java.security.Principal;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070040import java.security.PrivateKey;
Alex Klyubin4a0ff7c2015-06-09 13:25:20 -070041import java.security.UnrecoverableKeyException;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070042import java.security.cert.Certificate;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070043import java.security.cert.CertificateException;
44import java.security.cert.CertificateFactory;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070045import java.security.cert.X509Certificate;
Rubin Xub4365912016-03-23 12:13:22 +000046import java.util.ArrayList;
47import java.util.Collection;
Brian Carlstromdb93b782011-07-01 00:12:17 -070048import java.util.List;
Kenny Rootb91773b2013-09-05 13:03:16 -070049import java.util.Locale;
Brian Carlstrom8e9929c2011-05-17 00:40:28 -070050import java.util.concurrent.BlockingQueue;
51import java.util.concurrent.LinkedBlockingQueue;
Kenny Root5423e682011-11-14 08:43:13 -080052
Kenny Root12e75222013-04-23 22:34:24 -070053import com.android.org.conscrypt.TrustedCertificateStore;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070054
55/**
Brian Carlstrom93201f52011-06-09 15:05:35 -070056 * The {@code KeyChain} class provides access to private keys and
57 * their corresponding certificate chains in credential storage.
58 *
59 * <p>Applications accessing the {@code KeyChain} normally go through
60 * these steps:
61 *
62 * <ol>
63 *
64 * <li>Receive a callback from an {@link javax.net.ssl.X509KeyManager
65 * X509KeyManager} that a private key is requested.
66 *
67 * <li>Call {@link #choosePrivateKeyAlias
68 * choosePrivateKeyAlias} to allow the user to select from a
69 * list of currently available private keys and corresponding
70 * certificate chains. The chosen alias will be returned by the
71 * callback {@link KeyChainAliasCallback#alias}, or null if no private
72 * key is available or the user cancels the request.
73 *
74 * <li>Call {@link #getPrivateKey} and {@link #getCertificateChain} to
75 * retrieve the credentials to return to the corresponding {@link
76 * javax.net.ssl.X509KeyManager} callbacks.
77 *
78 * </ol>
79 *
80 * <p>An application may remember the value of a selected alias to
81 * avoid prompting the user with {@link #choosePrivateKeyAlias
82 * choosePrivateKeyAlias} on subsequent connections. If the alias is
83 * no longer valid, null will be returned on lookups using that value
Brian Carlstromca43c452011-06-29 18:53:17 -070084 *
85 * <p>An application can request the installation of private keys and
86 * certificates via the {@code Intent} provided by {@link
87 * #createInstallIntent}. Private keys installed via this {@code
88 * Intent} will be accessible via {@link #choosePrivateKeyAlias} while
89 * Certificate Authority (CA) certificates will be trusted by all
90 * applications through the default {@code X509TrustManager}.
Brian Carlstromb9a07c12011-04-11 09:03:51 -070091 */
Brian Carlstrom93201f52011-06-09 15:05:35 -070092// TODO reference intent for credential installation when public
Brian Carlstromb9a07c12011-04-11 09:03:51 -070093public final class KeyChain {
94
Brian Carlstromb9a07c12011-04-11 09:03:51 -070095 /**
96 * @hide Also used by KeyChainService implementation
97 */
98 public static final String ACCOUNT_TYPE = "com.android.keychain";
99
100 /**
Kenny Roota3659062014-03-17 16:21:53 -0700101 * Package name for KeyChain chooser.
102 */
103 private static final String KEYCHAIN_PACKAGE = "com.android.keychain";
104
105 /**
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700106 * Action to bring up the KeyChainActivity
107 */
108 private static final String ACTION_CHOOSER = "com.android.keychain.CHOOSER";
109
110 /**
Kenny Root1a88d832014-02-07 09:12:48 -0800111 * Package name for the Certificate Installer.
112 */
113 private static final String CERT_INSTALLER_PACKAGE = "com.android.certinstaller";
114
115 /**
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700116 * Extra for use with {@link #ACTION_CHOOSER}
Brian Carlstromba1a6672011-05-24 21:54:37 -0700117 * @hide Also used by KeyChainActivity implementation
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700118 */
Brian Carlstromba1a6672011-05-24 21:54:37 -0700119 public static final String EXTRA_RESPONSE = "response";
120
121 /**
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700122 * Extra for use with {@link #ACTION_CHOOSER}
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700123 * @hide Also used by KeyChainActivity implementation
124 */
Robin Lee39087b12015-05-05 15:57:17 +0100125 public static final String EXTRA_URI = "uri";
Robin Lee3798ed52015-02-03 17:55:31 +0000126
127 /**
128 * Extra for use with {@link #ACTION_CHOOSER}
129 * @hide Also used by KeyChainActivity implementation
130 */
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700131 public static final String EXTRA_ALIAS = "alias";
132
133 /**
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700134 * Extra for use with {@link #ACTION_CHOOSER}
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700135 * @hide Also used by KeyChainActivity implementation
136 */
137 public static final String EXTRA_SENDER = "sender";
138
139 /**
Selim Gurun93ba4fe2012-02-14 11:48:49 -0800140 * Action to bring up the CertInstaller.
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700141 */
142 private static final String ACTION_INSTALL = "android.credentials.INSTALL";
143
144 /**
145 * Optional extra to specify a {@code String} credential name on
146 * the {@code Intent} returned by {@link #createInstallIntent}.
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700147 */
148 // Compatible with old com.android.certinstaller.CredentialHelper.CERT_NAME_KEY
149 public static final String EXTRA_NAME = "name";
150
151 /**
152 * Optional extra to specify an X.509 certificate to install on
153 * the {@code Intent} returned by {@link #createInstallIntent}.
154 * The extra value should be a PEM or ASN.1 DER encoded {@code
155 * byte[]}. An {@link X509Certificate} can be converted to DER
156 * encoded bytes with {@link X509Certificate#getEncoded}.
157 *
158 * <p>{@link #EXTRA_NAME} may be used to provide a default alias
159 * name for the installed certificate.
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700160 */
161 // Compatible with old android.security.Credentials.CERTIFICATE
162 public static final String EXTRA_CERTIFICATE = "CERT";
163
164 /**
165 * Optional extra for use with the {@code Intent} returned by
166 * {@link #createInstallIntent} to specify a PKCS#12 key store to
167 * install. The extra value should be a {@code byte[]}. The bytes
168 * may come from an external source or be generated with {@link
Brian Carlstromca43c452011-06-29 18:53:17 -0700169 * java.security.KeyStore#store} on a "PKCS12" instance.
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700170 *
171 * <p>The user will be prompted for the password to load the key store.
172 *
173 * <p>The key store will be scanned for {@link
174 * java.security.KeyStore.PrivateKeyEntry} entries and both the
175 * private key and associated certificate chain will be installed.
176 *
177 * <p>{@link #EXTRA_NAME} may be used to provide a default alias
178 * name for the installed credentials.
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700179 */
180 // Compatible with old android.security.Credentials.PKCS12
181 public static final String EXTRA_PKCS12 = "PKCS12";
182
Selim Gurun93ba4fe2012-02-14 11:48:49 -0800183
184 /**
Selim Gurun93ba4fe2012-02-14 11:48:49 -0800185 * Broadcast Action: Indicates the trusted storage has changed. Sent when
186 * one of this happens:
187 *
188 * <ul>
189 * <li>a new CA is added,
190 * <li>an existing CA is removed or disabled,
191 * <li>a disabled CA is enabled,
192 * <li>trusted storage is reset (all user certs are cleared),
193 * <li>when permission to access a private key is changed.
194 * </ul>
195 */
196 public static final String ACTION_STORAGE_CHANGED = "android.security.STORAGE_CHANGED";
197
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700198 /**
199 * Returns an {@code Intent} that can be used for credential
200 * installation. The intent may be used without any extras, in
201 * which case the user will be able to install credentials from
202 * their own source.
203 *
204 * <p>Alternatively, {@link #EXTRA_CERTIFICATE} or {@link
205 * #EXTRA_PKCS12} maybe used to specify the bytes of an X.509
206 * certificate or a PKCS#12 key store for installation. These
Brian Carlstromca43c452011-06-29 18:53:17 -0700207 * extras may be combined with {@link #EXTRA_NAME} to provide a
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700208 * default alias name for credentials being installed.
209 *
210 * <p>When used with {@link Activity#startActivityForResult},
211 * {@link Activity#RESULT_OK} will be returned if a credential was
212 * successfully installed, otherwise {@link
213 * Activity#RESULT_CANCELED} will be returned.
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700214 */
Alex Klyubin54bb1592015-05-11 12:30:03 -0700215 @NonNull
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700216 public static Intent createInstallIntent() {
217 Intent intent = new Intent(ACTION_INSTALL);
Kenny Root1a88d832014-02-07 09:12:48 -0800218 intent.setClassName(CERT_INSTALLER_PACKAGE,
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700219 "com.android.certinstaller.CertInstallerMain");
220 return intent;
221 }
222
223 /**
Brian Carlstromba1a6672011-05-24 21:54:37 -0700224 * Launches an {@code Activity} for the user to select the alias
225 * for a private key and certificate pair for authentication. The
226 * selected alias or null will be returned via the
Brian Carlstrom93201f52011-06-09 15:05:35 -0700227 * KeyChainAliasCallback callback.
228 *
Robin Lee3798ed52015-02-03 17:55:31 +0000229 * <p>The device or profile owner can intercept this before the activity
230 * is shown, to pick a specific private key alias.
231 *
232 * <p>{@code keyTypes} and {@code issuers} may be used to
233 * highlight suggested choices to the user, although to cope with
234 * sometimes erroneous values provided by servers, the user may be
235 * able to override these suggestions.
236 *
237 * <p>{@code host} and {@code port} may be used to give the user
238 * more context about the server requesting the credentials.
239 *
240 * <p>{@code alias} allows the chooser to preselect an existing
241 * alias which will still be subject to user confirmation.
242 *
243 * @param activity The {@link Activity} context to use for
244 * launching the new sub-Activity to prompt the user to select
245 * a private key; used only to call startActivity(); must not
246 * be null.
247 * @param response Callback to invoke when the request completes;
248 * must not be null
249 * @param keyTypes The acceptable types of asymmetric keys such as
250 * "RSA" or "DSA", or a null array.
251 * @param issuers The acceptable certificate issuers for the
252 * certificate matching the private key, or null.
253 * @param host The host name of the server requesting the
254 * certificate, or null if unavailable.
255 * @param port The port number of the server requesting the
256 * certificate, or -1 if unavailable.
257 * @param alias The alias to preselect if available, or null if
258 * unavailable.
259 */
Alex Klyubin54bb1592015-05-11 12:30:03 -0700260 public static void choosePrivateKeyAlias(@NonNull Activity activity,
261 @NonNull KeyChainAliasCallback response,
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700262 @KeyProperties.KeyAlgorithmEnum String[] keyTypes, Principal[] issuers,
Alex Klyubin54bb1592015-05-11 12:30:03 -0700263 @Nullable String host, int port, @Nullable String alias) {
Robin Lee39087b12015-05-05 15:57:17 +0100264 Uri uri = null;
265 if (host != null) {
266 uri = new Uri.Builder()
267 .authority(host + (port != -1 ? ":" + port : ""))
268 .build();
269 }
270 choosePrivateKeyAlias(activity, response, keyTypes, issuers, uri, alias);
Robin Lee3798ed52015-02-03 17:55:31 +0000271 }
272
273 /**
274 * Launches an {@code Activity} for the user to select the alias
275 * for a private key and certificate pair for authentication. The
276 * selected alias or null will be returned via the
277 * KeyChainAliasCallback callback.
278 *
279 * <p>The device or profile owner can intercept this before the activity
280 * is shown, to pick a specific private key alias.</p>
281 *
Brian Carlstrom93201f52011-06-09 15:05:35 -0700282 * <p>{@code keyTypes} and {@code issuers} may be used to
283 * highlight suggested choices to the user, although to cope with
284 * sometimes erroneous values provided by servers, the user may be
285 * able to override these suggestions.
286 *
287 * <p>{@code host} and {@code port} may be used to give the user
288 * more context about the server requesting the credentials.
289 *
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700290 * <p>{@code alias} allows the chooser to preselect an existing
291 * alias which will still be subject to user confirmation.
292 *
Brian Carlstrom93201f52011-06-09 15:05:35 -0700293 * @param activity The {@link Activity} context to use for
294 * launching the new sub-Activity to prompt the user to select
295 * a private key; used only to call startActivity(); must not
296 * be null.
297 * @param response Callback to invoke when the request completes;
298 * must not be null
299 * @param keyTypes The acceptable types of asymmetric keys such as
Alex Klyubincd2329d2015-01-14 16:45:51 -0800300 * "EC" or "RSA", or a null array.
Brian Carlstrom93201f52011-06-09 15:05:35 -0700301 * @param issuers The acceptable certificate issuers for the
302 * certificate matching the private key, or null.
Robin Lee39087b12015-05-05 15:57:17 +0100303 * @param uri The full URI the server is requesting the certificate
Robin Lee3798ed52015-02-03 17:55:31 +0000304 * for, or null if unavailable.
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700305 * @param alias The alias to preselect if available, or null if
306 * unavailable.
Brian Carlstromba1a6672011-05-24 21:54:37 -0700307 */
Alex Klyubin54bb1592015-05-11 12:30:03 -0700308 public static void choosePrivateKeyAlias(@NonNull Activity activity,
309 @NonNull KeyChainAliasCallback response,
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700310 @KeyProperties.KeyAlgorithmEnum String[] keyTypes, Principal[] issuers,
Robin Lee39087b12015-05-05 15:57:17 +0100311 @Nullable Uri uri, @Nullable String alias) {
Brian Carlstrom93201f52011-06-09 15:05:35 -0700312 /*
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700313 * TODO currently keyTypes, issuers are unused. They are meant
314 * to follow the semantics and purpose of X509KeyManager
315 * method arguments.
Brian Carlstrom93201f52011-06-09 15:05:35 -0700316 *
317 * keyTypes would allow the list to be filtered and typically
318 * will be set correctly by the server. In practice today,
Alex Klyubincd2329d2015-01-14 16:45:51 -0800319 * most all users will want only RSA or EC, and usually
Brian Carlstrom93201f52011-06-09 15:05:35 -0700320 * only a small number of certs will be available.
321 *
322 * issuers is typically not useful. Some servers historically
323 * will send the entire list of public CAs known to the
324 * server. Others will send none. If this is used, if there
325 * are no matches after applying the constraint, it should be
326 * ignored.
Brian Carlstrom93201f52011-06-09 15:05:35 -0700327 */
Brian Carlstromba1a6672011-05-24 21:54:37 -0700328 if (activity == null) {
329 throw new NullPointerException("activity == null");
330 }
331 if (response == null) {
332 throw new NullPointerException("response == null");
333 }
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700334 Intent intent = new Intent(ACTION_CHOOSER);
Kenny Roota3659062014-03-17 16:21:53 -0700335 intent.setPackage(KEYCHAIN_PACKAGE);
Fred Quintanaab8b84a2011-07-13 14:55:39 -0700336 intent.putExtra(EXTRA_RESPONSE, new AliasResponse(response));
Robin Lee39087b12015-05-05 15:57:17 +0100337 intent.putExtra(EXTRA_URI, uri);
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700338 intent.putExtra(EXTRA_ALIAS, alias);
339 // the PendingIntent is used to get calling package name
340 intent.putExtra(EXTRA_SENDER, PendingIntent.getActivity(activity, 0, new Intent(), 0));
Brian Carlstromba1a6672011-05-24 21:54:37 -0700341 activity.startActivity(intent);
342 }
343
Brian Carlstrom93201f52011-06-09 15:05:35 -0700344 private static class AliasResponse extends IKeyChainAliasCallback.Stub {
Brian Carlstrom93201f52011-06-09 15:05:35 -0700345 private final KeyChainAliasCallback keyChainAliasResponse;
Fred Quintanaab8b84a2011-07-13 14:55:39 -0700346 private AliasResponse(KeyChainAliasCallback keyChainAliasResponse) {
Brian Carlstromba1a6672011-05-24 21:54:37 -0700347 this.keyChainAliasResponse = keyChainAliasResponse;
348 }
349 @Override public void alias(String alias) {
Fred Quintanaab8b84a2011-07-13 14:55:39 -0700350 keyChainAliasResponse.alias(alias);
Brian Carlstromba1a6672011-05-24 21:54:37 -0700351 }
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700352 }
353
354 /**
Brian Carlstromba1a6672011-05-24 21:54:37 -0700355 * Returns the {@code PrivateKey} for the requested alias, or null
Robin Lee3a435f02015-12-21 12:06:04 +0000356 * if there is no result.
Brian Carlstrom93201f52011-06-09 15:05:35 -0700357 *
Robin Lee59e3baa2015-06-30 10:48:06 -0700358 * <p> This method may block while waiting for a connection to another process, and must never
359 * be called from the main thread.
Robin Leeda236182016-08-12 12:46:28 +0100360 * <p> As {@link Activity} and {@link Service} contexts are short-lived and can be destroyed
361 * at any time from the main thread, it is safer to rely on a long-lived context such as one
362 * returned from {@link Context#getApplicationContext()}.
Robin Lee59e3baa2015-06-30 10:48:06 -0700363 *
364 * @param alias The alias of the desired private key, typically returned via
365 * {@link KeyChainAliasCallback#alias}.
Brian Carlstrom93201f52011-06-09 15:05:35 -0700366 * @throws KeyChainException if the alias was valid but there was some problem accessing it.
Robin Lee59e3baa2015-06-30 10:48:06 -0700367 * @throws IllegalStateException if called from the main thread.
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700368 */
Robin Lee59e3baa2015-06-30 10:48:06 -0700369 @Nullable @WorkerThread
Alex Klyubin54bb1592015-05-11 12:30:03 -0700370 public static PrivateKey getPrivateKey(@NonNull Context context, @NonNull String alias)
Brian Carlstrom93201f52011-06-09 15:05:35 -0700371 throws KeyChainException, InterruptedException {
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700372 if (alias == null) {
373 throw new NullPointerException("alias == null");
374 }
Brian Carlstromd7524722011-05-17 16:20:36 -0700375 KeyChainConnection keyChainConnection = bind(context);
Brian Carlstrom8e9929c2011-05-17 00:40:28 -0700376 try {
Kenny Root5423e682011-11-14 08:43:13 -0800377 final IKeyChainService keyChainService = keyChainConnection.getService();
378 final String keyId = keyChainService.requestPrivateKey(alias);
379 if (keyId == null) {
Robin Lee3a435f02015-12-21 12:06:04 +0000380 return null;
Kenny Root5423e682011-11-14 08:43:13 -0800381 }
Alex Klyubin4a0ff7c2015-06-09 13:25:20 -0700382 return AndroidKeyStoreProvider.loadAndroidKeyStorePrivateKeyFromKeystore(
Alex Klyubin3876b1b2015-09-09 14:55:03 -0700383 KeyStore.getInstance(), keyId, KeyStore.UID_SELF);
Brian Carlstrom93201f52011-06-09 15:05:35 -0700384 } catch (RemoteException e) {
385 throw new KeyChainException(e);
386 } catch (RuntimeException e) {
387 // only certain RuntimeExceptions can be propagated across the IKeyChainService call
388 throw new KeyChainException(e);
Alex Klyubin4a0ff7c2015-06-09 13:25:20 -0700389 } catch (UnrecoverableKeyException e) {
Kenny Root5423e682011-11-14 08:43:13 -0800390 throw new KeyChainException(e);
Brian Carlstromba1a6672011-05-24 21:54:37 -0700391 } finally {
392 keyChainConnection.close();
393 }
394 }
395
396 /**
397 * Returns the {@code X509Certificate} chain for the requested
Rubin Xub4365912016-03-23 12:13:22 +0000398 * alias, or null if there is no result.
399 * <p>
400 * <strong>Note:</strong> If a certificate chain was explicitly specified when the alias was
401 * installed, this method will return that chain. If only the client certificate was specified
402 * at the installation time, this method will try to build a certificate chain using all
403 * available trust anchors (preinstalled and user-added).
Brian Carlstrom93201f52011-06-09 15:05:35 -0700404 *
Robin Lee59e3baa2015-06-30 10:48:06 -0700405 * <p> This method may block while waiting for a connection to another process, and must never
406 * be called from the main thread.
Robin Leeda236182016-08-12 12:46:28 +0100407 * <p> As {@link Activity} and {@link Service} contexts are short-lived and can be destroyed
408 * at any time from the main thread, it is safer to rely on a long-lived context such as one
409 * returned from {@link Context#getApplicationContext()}.
Robin Lee59e3baa2015-06-30 10:48:06 -0700410 *
Brian Carlstrom93201f52011-06-09 15:05:35 -0700411 * @param alias The alias of the desired certificate chain, typically
412 * returned via {@link KeyChainAliasCallback#alias}.
413 * @throws KeyChainException if the alias was valid but there was some problem accessing it.
Robin Lee59e3baa2015-06-30 10:48:06 -0700414 * @throws IllegalStateException if called from the main thread.
Brian Carlstromba1a6672011-05-24 21:54:37 -0700415 */
Robin Lee59e3baa2015-06-30 10:48:06 -0700416 @Nullable @WorkerThread
Alex Klyubin54bb1592015-05-11 12:30:03 -0700417 public static X509Certificate[] getCertificateChain(@NonNull Context context,
418 @NonNull String alias) throws KeyChainException, InterruptedException {
Brian Carlstromba1a6672011-05-24 21:54:37 -0700419 if (alias == null) {
420 throw new NullPointerException("alias == null");
421 }
422 KeyChainConnection keyChainConnection = bind(context);
423 try {
Brian Carlstromba1a6672011-05-24 21:54:37 -0700424 IKeyChainService keyChainService = keyChainConnection.getService();
Kenny Root0150e482013-02-13 15:22:50 -0800425
426 final byte[] certificateBytes = keyChainService.getCertificate(alias);
427 if (certificateBytes == null) {
428 return null;
429 }
Rubin Xub4365912016-03-23 12:13:22 +0000430 X509Certificate leafCert = toCertificate(certificateBytes);
431 final byte[] certChainBytes = keyChainService.getCaCertificates(alias);
432 // If the keypair is installed with a certificate chain by either
433 // DevicePolicyManager.installKeyPair or CertInstaller, return that chain.
434 if (certChainBytes != null && certChainBytes.length != 0) {
435 Collection<X509Certificate> chain = toCertificates(certChainBytes);
436 ArrayList<X509Certificate> fullChain = new ArrayList<>(chain.size() + 1);
437 fullChain.add(leafCert);
438 fullChain.addAll(chain);
439 return fullChain.toArray(new X509Certificate[fullChain.size()]);
440 } else {
441 // If there isn't a certificate chain, either due to a pre-existing keypair
442 // installed before N, or no chain is explicitly installed under the new logic,
443 // fall back to old behavior of constructing the chain from trusted credentials.
444 //
445 // This logic exists to maintain old behaviour for already installed keypair, at
446 // the cost of potentially returning extra certificate chain for new clients who
447 // explicitly installed only the client certificate without a chain. The latter
448 // case is actually no different from pre-N behaviour of getCertificateChain(),
449 // in that sense this change introduces no regression. Besides the returned chain
450 // is still valid so the consumer of the chain should have no problem verifying it.
451 TrustedCertificateStore store = new TrustedCertificateStore();
452 List<X509Certificate> chain = store.getCertificateChain(leafCert);
453 return chain.toArray(new X509Certificate[chain.size()]);
454 }
Kenny Rootcfba6a02013-05-06 15:00:58 -0700455 } catch (CertificateException e) {
456 throw new KeyChainException(e);
Brian Carlstrom93201f52011-06-09 15:05:35 -0700457 } catch (RemoteException e) {
458 throw new KeyChainException(e);
459 } catch (RuntimeException e) {
460 // only certain RuntimeExceptions can be propagated across the IKeyChainService call
461 throw new KeyChainException(e);
Brian Carlstrom8e9929c2011-05-17 00:40:28 -0700462 } finally {
Brian Carlstromd7524722011-05-17 16:20:36 -0700463 keyChainConnection.close();
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700464 }
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700465 }
466
Kenny Rootbf556ac2013-04-01 15:10:22 -0700467 /**
468 * Returns {@code true} if the current device's {@code KeyChain} supports a
469 * specific {@code PrivateKey} type indicated by {@code algorithm} (e.g.,
470 * "RSA").
471 */
Alex Klyubin4d5443f2015-05-06 15:43:52 -0700472 public static boolean isKeyAlgorithmSupported(
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700473 @NonNull @KeyProperties.KeyAlgorithmEnum String algorithm) {
Kenny Rootb91773b2013-09-05 13:03:16 -0700474 final String algUpper = algorithm.toUpperCase(Locale.US);
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700475 return KeyProperties.KEY_ALGORITHM_EC.equals(algUpper)
476 || KeyProperties.KEY_ALGORITHM_RSA.equals(algUpper);
Kenny Rootbf556ac2013-04-01 15:10:22 -0700477 }
478
479 /**
480 * Returns {@code true} if the current device's {@code KeyChain} binds any
481 * {@code PrivateKey} of the given {@code algorithm} to the device once
482 * imported or generated. This can be used to tell if there is special
483 * hardware support that can be used to bind keys to the device in a way
484 * that makes it non-exportable.
Alex Klyubin469cbf52015-06-04 12:36:27 -0700485 *
486 * @deprecated Whether the key is bound to the secure hardware is known only
487 * once the key has been imported. To find out, use:
488 * <pre>{@code
489 * PrivateKey key = ...; // private key from KeyChain
490 *
491 * KeyFactory keyFactory =
492 * KeyFactory.getInstance(key.getAlgorithm(), "AndroidKeyStore");
493 * KeyInfo keyInfo = keyFactory.getKeySpec(key, KeyInfo.class);
Neil Fuller71fbb812015-11-30 09:51:33 +0000494 * if (keyInfo.isInsideSecureHardware()) {
Alex Klyubin469cbf52015-06-04 12:36:27 -0700495 * // The key is bound to the secure hardware of this Android
Neil Fuller71fbb812015-11-30 09:51:33 +0000496 * }}</pre>
Kenny Rootbf556ac2013-04-01 15:10:22 -0700497 */
Alex Klyubin469cbf52015-06-04 12:36:27 -0700498 @Deprecated
Alex Klyubin4d5443f2015-05-06 15:43:52 -0700499 public static boolean isBoundKeyAlgorithm(
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700500 @NonNull @KeyProperties.KeyAlgorithmEnum String algorithm) {
Kenny Root5b7e90a2013-04-02 11:23:41 -0700501 if (!isKeyAlgorithmSupported(algorithm)) {
Kenny Rootbf556ac2013-04-01 15:10:22 -0700502 return false;
503 }
504
Kenny Rootb91773b2013-09-05 13:03:16 -0700505 return KeyStore.getInstance().isHardwareBacked(algorithm);
Kenny Rootbf556ac2013-04-01 15:10:22 -0700506 }
507
Zoltan Szatmary-Banf0ae1352014-08-18 10:48:33 +0100508 /** @hide */
Alex Klyubin54bb1592015-05-11 12:30:03 -0700509 @NonNull
510 public static X509Certificate toCertificate(@NonNull byte[] bytes) {
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700511 if (bytes == null) {
Brian Carlstrom8e9929c2011-05-17 00:40:28 -0700512 throw new IllegalArgumentException("bytes == null");
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700513 }
514 try {
515 CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
516 Certificate cert = certFactory.generateCertificate(new ByteArrayInputStream(bytes));
517 return (X509Certificate) cert;
518 } catch (CertificateException e) {
519 throw new AssertionError(e);
520 }
521 }
522
Rubin Xub4365912016-03-23 12:13:22 +0000523 /** @hide */
524 @NonNull
525 public static Collection<X509Certificate> toCertificates(@NonNull byte[] bytes) {
526 if (bytes == null) {
527 throw new IllegalArgumentException("bytes == null");
528 }
529 try {
530 CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
531 return (Collection<X509Certificate>) certFactory.generateCertificates(
532 new ByteArrayInputStream(bytes));
533 } catch (CertificateException e) {
534 throw new AssertionError(e);
535 }
536 }
537
Brian Carlstromd7524722011-05-17 16:20:36 -0700538 /**
539 * @hide for reuse by CertInstaller and Settings.
540 * @see KeyChain#bind
541 */
542 public final static class KeyChainConnection implements Closeable {
543 private final Context context;
544 private final ServiceConnection serviceConnection;
545 private final IKeyChainService service;
546 private KeyChainConnection(Context context,
547 ServiceConnection serviceConnection,
548 IKeyChainService service) {
549 this.context = context;
550 this.serviceConnection = serviceConnection;
551 this.service = service;
552 }
553 @Override public void close() {
554 context.unbindService(serviceConnection);
555 }
556 public IKeyChainService getService() {
557 return service;
558 }
559 }
560
561 /**
562 * @hide for reuse by CertInstaller and Settings.
563 *
564 * Caller should call unbindService on the result when finished.
565 */
Robin Lee59e3baa2015-06-30 10:48:06 -0700566 @WorkerThread
Alex Klyubin54bb1592015-05-11 12:30:03 -0700567 public static KeyChainConnection bind(@NonNull Context context) throws InterruptedException {
Robin Lee306fe082014-06-19 14:04:24 +0000568 return bindAsUser(context, Process.myUserHandle());
569 }
570
571 /**
572 * @hide
573 */
Robin Lee59e3baa2015-06-30 10:48:06 -0700574 @WorkerThread
Alex Klyubin54bb1592015-05-11 12:30:03 -0700575 public static KeyChainConnection bindAsUser(@NonNull Context context, UserHandle user)
Robin Lee306fe082014-06-19 14:04:24 +0000576 throws InterruptedException {
Brian Carlstromd7524722011-05-17 16:20:36 -0700577 if (context == null) {
578 throw new NullPointerException("context == null");
579 }
580 ensureNotOnMainThread(context);
581 final BlockingQueue<IKeyChainService> q = new LinkedBlockingQueue<IKeyChainService>(1);
582 ServiceConnection keyChainServiceConnection = new ServiceConnection() {
Fred Quintanaab8b84a2011-07-13 14:55:39 -0700583 volatile boolean mConnectedAtLeastOnce = false;
Brian Carlstromd7524722011-05-17 16:20:36 -0700584 @Override public void onServiceConnected(ComponentName name, IBinder service) {
Fred Quintanaab8b84a2011-07-13 14:55:39 -0700585 if (!mConnectedAtLeastOnce) {
586 mConnectedAtLeastOnce = true;
587 try {
588 q.put(IKeyChainService.Stub.asInterface(service));
589 } catch (InterruptedException e) {
590 // will never happen, since the queue starts with one available slot
591 }
Brian Carlstromd7524722011-05-17 16:20:36 -0700592 }
593 }
594 @Override public void onServiceDisconnected(ComponentName name) {}
595 };
Maggie Benthallda51e682013-08-08 22:35:44 -0400596 Intent intent = new Intent(IKeyChainService.class.getName());
597 ComponentName comp = intent.resolveSystemService(context.getPackageManager(), 0);
598 intent.setComponent(comp);
Robin Lee21bcbc52016-02-29 18:55:35 +0000599 if (comp == null || !context.bindServiceAsUser(
600 intent, keyChainServiceConnection, Context.BIND_AUTO_CREATE, user)) {
Brian Carlstromd7524722011-05-17 16:20:36 -0700601 throw new AssertionError("could not bind to KeyChainService");
602 }
603 return new KeyChainConnection(context, keyChainServiceConnection, q.take());
604 }
605
Alex Klyubin54bb1592015-05-11 12:30:03 -0700606 private static void ensureNotOnMainThread(@NonNull Context context) {
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700607 Looper looper = Looper.myLooper();
Brian Carlstrom8e9929c2011-05-17 00:40:28 -0700608 if (looper != null && looper == context.getMainLooper()) {
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700609 throw new IllegalStateException(
610 "calling this from your main thread can lead to deadlock");
611 }
612 }
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700613}