blob: cce58c2096f352b64c2c3cc7685af7b8f9ea52b3 [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;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070023import android.content.ComponentName;
24import android.content.Context;
25import android.content.Intent;
26import android.content.ServiceConnection;
Robin Lee39087b12015-05-05 15:57:17 +010027import android.net.Uri;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070028import android.os.IBinder;
29import android.os.Looper;
Robin Lee306fe082014-06-19 14:04:24 +000030import android.os.Process;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070031import android.os.RemoteException;
Robin Lee306fe082014-06-19 14:04:24 +000032import android.os.UserHandle;
Alex Klyubin4a0ff7c2015-06-09 13:25:20 -070033import android.security.keystore.AndroidKeyStoreProvider;
Alex Klyubin3f8d4d82015-05-13 09:15:00 -070034import android.security.keystore.KeyProperties;
35
Brian Carlstromb9a07c12011-04-11 09:03:51 -070036import java.io.ByteArrayInputStream;
Brian Carlstromd7524722011-05-17 16:20:36 -070037import java.io.Closeable;
Brian Carlstrom93201f52011-06-09 15:05:35 -070038import java.security.Principal;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070039import java.security.PrivateKey;
Alex Klyubin4a0ff7c2015-06-09 13:25:20 -070040import java.security.UnrecoverableKeyException;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070041import java.security.cert.Certificate;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070042import java.security.cert.CertificateException;
43import java.security.cert.CertificateFactory;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070044import java.security.cert.X509Certificate;
Rubin Xub4365912016-03-23 12:13:22 +000045import java.util.ArrayList;
46import java.util.Collection;
Brian Carlstromdb93b782011-07-01 00:12:17 -070047import java.util.List;
Kenny Rootb91773b2013-09-05 13:03:16 -070048import java.util.Locale;
Brian Carlstrom8e9929c2011-05-17 00:40:28 -070049import java.util.concurrent.BlockingQueue;
50import java.util.concurrent.LinkedBlockingQueue;
Kenny Root5423e682011-11-14 08:43:13 -080051
Kenny Root12e75222013-04-23 22:34:24 -070052import com.android.org.conscrypt.TrustedCertificateStore;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070053
54/**
Brian Carlstrom93201f52011-06-09 15:05:35 -070055 * The {@code KeyChain} class provides access to private keys and
56 * their corresponding certificate chains in credential storage.
57 *
58 * <p>Applications accessing the {@code KeyChain} normally go through
59 * these steps:
60 *
61 * <ol>
62 *
63 * <li>Receive a callback from an {@link javax.net.ssl.X509KeyManager
64 * X509KeyManager} that a private key is requested.
65 *
66 * <li>Call {@link #choosePrivateKeyAlias
67 * choosePrivateKeyAlias} to allow the user to select from a
68 * list of currently available private keys and corresponding
69 * certificate chains. The chosen alias will be returned by the
70 * callback {@link KeyChainAliasCallback#alias}, or null if no private
71 * key is available or the user cancels the request.
72 *
73 * <li>Call {@link #getPrivateKey} and {@link #getCertificateChain} to
74 * retrieve the credentials to return to the corresponding {@link
75 * javax.net.ssl.X509KeyManager} callbacks.
76 *
77 * </ol>
78 *
79 * <p>An application may remember the value of a selected alias to
80 * avoid prompting the user with {@link #choosePrivateKeyAlias
81 * choosePrivateKeyAlias} on subsequent connections. If the alias is
82 * no longer valid, null will be returned on lookups using that value
Brian Carlstromca43c452011-06-29 18:53:17 -070083 *
84 * <p>An application can request the installation of private keys and
85 * certificates via the {@code Intent} provided by {@link
86 * #createInstallIntent}. Private keys installed via this {@code
87 * Intent} will be accessible via {@link #choosePrivateKeyAlias} while
88 * Certificate Authority (CA) certificates will be trusted by all
89 * applications through the default {@code X509TrustManager}.
Brian Carlstromb9a07c12011-04-11 09:03:51 -070090 */
Brian Carlstrom93201f52011-06-09 15:05:35 -070091// TODO reference intent for credential installation when public
Brian Carlstromb9a07c12011-04-11 09:03:51 -070092public final class KeyChain {
93
Brian Carlstromb9a07c12011-04-11 09:03:51 -070094 /**
95 * @hide Also used by KeyChainService implementation
96 */
97 public static final String ACCOUNT_TYPE = "com.android.keychain";
98
99 /**
Kenny Roota3659062014-03-17 16:21:53 -0700100 * Package name for KeyChain chooser.
101 */
102 private static final String KEYCHAIN_PACKAGE = "com.android.keychain";
103
104 /**
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700105 * Action to bring up the KeyChainActivity
106 */
107 private static final String ACTION_CHOOSER = "com.android.keychain.CHOOSER";
108
109 /**
Kenny Root1a88d832014-02-07 09:12:48 -0800110 * Package name for the Certificate Installer.
111 */
112 private static final String CERT_INSTALLER_PACKAGE = "com.android.certinstaller";
113
114 /**
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700115 * Extra for use with {@link #ACTION_CHOOSER}
Brian Carlstromba1a6672011-05-24 21:54:37 -0700116 * @hide Also used by KeyChainActivity implementation
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700117 */
Brian Carlstromba1a6672011-05-24 21:54:37 -0700118 public static final String EXTRA_RESPONSE = "response";
119
120 /**
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700121 * Extra for use with {@link #ACTION_CHOOSER}
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700122 * @hide Also used by KeyChainActivity implementation
123 */
Robin Lee39087b12015-05-05 15:57:17 +0100124 public static final String EXTRA_URI = "uri";
Robin Lee3798ed52015-02-03 17:55:31 +0000125
126 /**
127 * Extra for use with {@link #ACTION_CHOOSER}
128 * @hide Also used by KeyChainActivity implementation
129 */
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700130 public static final String EXTRA_ALIAS = "alias";
131
132 /**
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700133 * Extra for use with {@link #ACTION_CHOOSER}
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700134 * @hide Also used by KeyChainActivity implementation
135 */
136 public static final String EXTRA_SENDER = "sender";
137
138 /**
Selim Gurun93ba4fe2012-02-14 11:48:49 -0800139 * Action to bring up the CertInstaller.
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700140 */
141 private static final String ACTION_INSTALL = "android.credentials.INSTALL";
142
143 /**
144 * Optional extra to specify a {@code String} credential name on
145 * the {@code Intent} returned by {@link #createInstallIntent}.
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700146 */
147 // Compatible with old com.android.certinstaller.CredentialHelper.CERT_NAME_KEY
148 public static final String EXTRA_NAME = "name";
149
150 /**
151 * Optional extra to specify an X.509 certificate to install on
152 * the {@code Intent} returned by {@link #createInstallIntent}.
153 * The extra value should be a PEM or ASN.1 DER encoded {@code
154 * byte[]}. An {@link X509Certificate} can be converted to DER
155 * encoded bytes with {@link X509Certificate#getEncoded}.
156 *
157 * <p>{@link #EXTRA_NAME} may be used to provide a default alias
158 * name for the installed certificate.
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700159 */
160 // Compatible with old android.security.Credentials.CERTIFICATE
161 public static final String EXTRA_CERTIFICATE = "CERT";
162
163 /**
164 * Optional extra for use with the {@code Intent} returned by
165 * {@link #createInstallIntent} to specify a PKCS#12 key store to
166 * install. The extra value should be a {@code byte[]}. The bytes
167 * may come from an external source or be generated with {@link
Brian Carlstromca43c452011-06-29 18:53:17 -0700168 * java.security.KeyStore#store} on a "PKCS12" instance.
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700169 *
170 * <p>The user will be prompted for the password to load the key store.
171 *
172 * <p>The key store will be scanned for {@link
173 * java.security.KeyStore.PrivateKeyEntry} entries and both the
174 * private key and associated certificate chain will be installed.
175 *
176 * <p>{@link #EXTRA_NAME} may be used to provide a default alias
177 * name for the installed credentials.
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700178 */
179 // Compatible with old android.security.Credentials.PKCS12
180 public static final String EXTRA_PKCS12 = "PKCS12";
181
Selim Gurun93ba4fe2012-02-14 11:48:49 -0800182
183 /**
Selim Gurun93ba4fe2012-02-14 11:48:49 -0800184 * Broadcast Action: Indicates the trusted storage has changed. Sent when
185 * one of this happens:
186 *
187 * <ul>
188 * <li>a new CA is added,
189 * <li>an existing CA is removed or disabled,
190 * <li>a disabled CA is enabled,
191 * <li>trusted storage is reset (all user certs are cleared),
192 * <li>when permission to access a private key is changed.
193 * </ul>
194 */
195 public static final String ACTION_STORAGE_CHANGED = "android.security.STORAGE_CHANGED";
196
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700197 /**
198 * Returns an {@code Intent} that can be used for credential
199 * installation. The intent may be used without any extras, in
200 * which case the user will be able to install credentials from
201 * their own source.
202 *
203 * <p>Alternatively, {@link #EXTRA_CERTIFICATE} or {@link
204 * #EXTRA_PKCS12} maybe used to specify the bytes of an X.509
205 * certificate or a PKCS#12 key store for installation. These
Brian Carlstromca43c452011-06-29 18:53:17 -0700206 * extras may be combined with {@link #EXTRA_NAME} to provide a
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700207 * default alias name for credentials being installed.
208 *
209 * <p>When used with {@link Activity#startActivityForResult},
210 * {@link Activity#RESULT_OK} will be returned if a credential was
211 * successfully installed, otherwise {@link
212 * Activity#RESULT_CANCELED} will be returned.
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700213 */
Alex Klyubin54bb1592015-05-11 12:30:03 -0700214 @NonNull
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700215 public static Intent createInstallIntent() {
216 Intent intent = new Intent(ACTION_INSTALL);
Kenny Root1a88d832014-02-07 09:12:48 -0800217 intent.setClassName(CERT_INSTALLER_PACKAGE,
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700218 "com.android.certinstaller.CertInstallerMain");
219 return intent;
220 }
221
222 /**
Brian Carlstromba1a6672011-05-24 21:54:37 -0700223 * Launches an {@code Activity} for the user to select the alias
224 * for a private key and certificate pair for authentication. The
225 * selected alias or null will be returned via the
Brian Carlstrom93201f52011-06-09 15:05:35 -0700226 * KeyChainAliasCallback callback.
227 *
Robin Lee3798ed52015-02-03 17:55:31 +0000228 * <p>The device or profile owner can intercept this before the activity
229 * is shown, to pick a specific private key alias.
230 *
231 * <p>{@code keyTypes} and {@code issuers} may be used to
232 * highlight suggested choices to the user, although to cope with
233 * sometimes erroneous values provided by servers, the user may be
234 * able to override these suggestions.
235 *
236 * <p>{@code host} and {@code port} may be used to give the user
237 * more context about the server requesting the credentials.
238 *
239 * <p>{@code alias} allows the chooser to preselect an existing
240 * alias which will still be subject to user confirmation.
241 *
242 * @param activity The {@link Activity} context to use for
243 * launching the new sub-Activity to prompt the user to select
244 * a private key; used only to call startActivity(); must not
245 * be null.
246 * @param response Callback to invoke when the request completes;
247 * must not be null
248 * @param keyTypes The acceptable types of asymmetric keys such as
249 * "RSA" or "DSA", or a null array.
250 * @param issuers The acceptable certificate issuers for the
251 * certificate matching the private key, or null.
252 * @param host The host name of the server requesting the
253 * certificate, or null if unavailable.
254 * @param port The port number of the server requesting the
255 * certificate, or -1 if unavailable.
256 * @param alias The alias to preselect if available, or null if
257 * unavailable.
258 */
Alex Klyubin54bb1592015-05-11 12:30:03 -0700259 public static void choosePrivateKeyAlias(@NonNull Activity activity,
260 @NonNull KeyChainAliasCallback response,
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700261 @KeyProperties.KeyAlgorithmEnum String[] keyTypes, Principal[] issuers,
Alex Klyubin54bb1592015-05-11 12:30:03 -0700262 @Nullable String host, int port, @Nullable String alias) {
Robin Lee39087b12015-05-05 15:57:17 +0100263 Uri uri = null;
264 if (host != null) {
265 uri = new Uri.Builder()
266 .authority(host + (port != -1 ? ":" + port : ""))
267 .build();
268 }
269 choosePrivateKeyAlias(activity, response, keyTypes, issuers, uri, alias);
Robin Lee3798ed52015-02-03 17:55:31 +0000270 }
271
272 /**
273 * Launches an {@code Activity} for the user to select the alias
274 * for a private key and certificate pair for authentication. The
275 * selected alias or null will be returned via the
276 * KeyChainAliasCallback callback.
277 *
278 * <p>The device or profile owner can intercept this before the activity
279 * is shown, to pick a specific private key alias.</p>
280 *
Brian Carlstrom93201f52011-06-09 15:05:35 -0700281 * <p>{@code keyTypes} and {@code issuers} may be used to
282 * highlight suggested choices to the user, although to cope with
283 * sometimes erroneous values provided by servers, the user may be
284 * able to override these suggestions.
285 *
286 * <p>{@code host} and {@code port} may be used to give the user
287 * more context about the server requesting the credentials.
288 *
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700289 * <p>{@code alias} allows the chooser to preselect an existing
290 * alias which will still be subject to user confirmation.
291 *
Brian Carlstrom93201f52011-06-09 15:05:35 -0700292 * @param activity The {@link Activity} context to use for
293 * launching the new sub-Activity to prompt the user to select
294 * a private key; used only to call startActivity(); must not
295 * be null.
296 * @param response Callback to invoke when the request completes;
297 * must not be null
298 * @param keyTypes The acceptable types of asymmetric keys such as
Alex Klyubincd2329d2015-01-14 16:45:51 -0800299 * "EC" or "RSA", or a null array.
Brian Carlstrom93201f52011-06-09 15:05:35 -0700300 * @param issuers The acceptable certificate issuers for the
301 * certificate matching the private key, or null.
Robin Lee39087b12015-05-05 15:57:17 +0100302 * @param uri The full URI the server is requesting the certificate
Robin Lee3798ed52015-02-03 17:55:31 +0000303 * for, or null if unavailable.
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700304 * @param alias The alias to preselect if available, or null if
305 * unavailable.
Brian Carlstromba1a6672011-05-24 21:54:37 -0700306 */
Alex Klyubin54bb1592015-05-11 12:30:03 -0700307 public static void choosePrivateKeyAlias(@NonNull Activity activity,
308 @NonNull KeyChainAliasCallback response,
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700309 @KeyProperties.KeyAlgorithmEnum String[] keyTypes, Principal[] issuers,
Robin Lee39087b12015-05-05 15:57:17 +0100310 @Nullable Uri uri, @Nullable String alias) {
Brian Carlstrom93201f52011-06-09 15:05:35 -0700311 /*
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700312 * TODO currently keyTypes, issuers are unused. They are meant
313 * to follow the semantics and purpose of X509KeyManager
314 * method arguments.
Brian Carlstrom93201f52011-06-09 15:05:35 -0700315 *
316 * keyTypes would allow the list to be filtered and typically
317 * will be set correctly by the server. In practice today,
Alex Klyubincd2329d2015-01-14 16:45:51 -0800318 * most all users will want only RSA or EC, and usually
Brian Carlstrom93201f52011-06-09 15:05:35 -0700319 * only a small number of certs will be available.
320 *
321 * issuers is typically not useful. Some servers historically
322 * will send the entire list of public CAs known to the
323 * server. Others will send none. If this is used, if there
324 * are no matches after applying the constraint, it should be
325 * ignored.
Brian Carlstrom93201f52011-06-09 15:05:35 -0700326 */
Brian Carlstromba1a6672011-05-24 21:54:37 -0700327 if (activity == null) {
328 throw new NullPointerException("activity == null");
329 }
330 if (response == null) {
331 throw new NullPointerException("response == null");
332 }
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700333 Intent intent = new Intent(ACTION_CHOOSER);
Kenny Roota3659062014-03-17 16:21:53 -0700334 intent.setPackage(KEYCHAIN_PACKAGE);
Fred Quintanaab8b84a2011-07-13 14:55:39 -0700335 intent.putExtra(EXTRA_RESPONSE, new AliasResponse(response));
Robin Lee39087b12015-05-05 15:57:17 +0100336 intent.putExtra(EXTRA_URI, uri);
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700337 intent.putExtra(EXTRA_ALIAS, alias);
338 // the PendingIntent is used to get calling package name
339 intent.putExtra(EXTRA_SENDER, PendingIntent.getActivity(activity, 0, new Intent(), 0));
Brian Carlstromba1a6672011-05-24 21:54:37 -0700340 activity.startActivity(intent);
341 }
342
Brian Carlstrom93201f52011-06-09 15:05:35 -0700343 private static class AliasResponse extends IKeyChainAliasCallback.Stub {
Brian Carlstrom93201f52011-06-09 15:05:35 -0700344 private final KeyChainAliasCallback keyChainAliasResponse;
Fred Quintanaab8b84a2011-07-13 14:55:39 -0700345 private AliasResponse(KeyChainAliasCallback keyChainAliasResponse) {
Brian Carlstromba1a6672011-05-24 21:54:37 -0700346 this.keyChainAliasResponse = keyChainAliasResponse;
347 }
348 @Override public void alias(String alias) {
Fred Quintanaab8b84a2011-07-13 14:55:39 -0700349 keyChainAliasResponse.alias(alias);
Brian Carlstromba1a6672011-05-24 21:54:37 -0700350 }
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700351 }
352
353 /**
Brian Carlstromba1a6672011-05-24 21:54:37 -0700354 * Returns the {@code PrivateKey} for the requested alias, or null
Robin Lee3a435f02015-12-21 12:06:04 +0000355 * if there is no result.
Brian Carlstrom93201f52011-06-09 15:05:35 -0700356 *
Robin Lee59e3baa2015-06-30 10:48:06 -0700357 * <p> This method may block while waiting for a connection to another process, and must never
358 * be called from the main thread.
359 *
360 * @param alias The alias of the desired private key, typically returned via
361 * {@link KeyChainAliasCallback#alias}.
Brian Carlstrom93201f52011-06-09 15:05:35 -0700362 * @throws KeyChainException if the alias was valid but there was some problem accessing it.
Robin Lee59e3baa2015-06-30 10:48:06 -0700363 * @throws IllegalStateException if called from the main thread.
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700364 */
Robin Lee59e3baa2015-06-30 10:48:06 -0700365 @Nullable @WorkerThread
Alex Klyubin54bb1592015-05-11 12:30:03 -0700366 public static PrivateKey getPrivateKey(@NonNull Context context, @NonNull String alias)
Brian Carlstrom93201f52011-06-09 15:05:35 -0700367 throws KeyChainException, InterruptedException {
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700368 if (alias == null) {
369 throw new NullPointerException("alias == null");
370 }
Brian Carlstromd7524722011-05-17 16:20:36 -0700371 KeyChainConnection keyChainConnection = bind(context);
Brian Carlstrom8e9929c2011-05-17 00:40:28 -0700372 try {
Kenny Root5423e682011-11-14 08:43:13 -0800373 final IKeyChainService keyChainService = keyChainConnection.getService();
374 final String keyId = keyChainService.requestPrivateKey(alias);
375 if (keyId == null) {
Robin Lee3a435f02015-12-21 12:06:04 +0000376 return null;
Kenny Root5423e682011-11-14 08:43:13 -0800377 }
Alex Klyubin4a0ff7c2015-06-09 13:25:20 -0700378 return AndroidKeyStoreProvider.loadAndroidKeyStorePrivateKeyFromKeystore(
Alex Klyubin3876b1b2015-09-09 14:55:03 -0700379 KeyStore.getInstance(), keyId, KeyStore.UID_SELF);
Brian Carlstrom93201f52011-06-09 15:05:35 -0700380 } catch (RemoteException e) {
381 throw new KeyChainException(e);
382 } catch (RuntimeException e) {
383 // only certain RuntimeExceptions can be propagated across the IKeyChainService call
384 throw new KeyChainException(e);
Alex Klyubin4a0ff7c2015-06-09 13:25:20 -0700385 } catch (UnrecoverableKeyException e) {
Kenny Root5423e682011-11-14 08:43:13 -0800386 throw new KeyChainException(e);
Brian Carlstromba1a6672011-05-24 21:54:37 -0700387 } finally {
388 keyChainConnection.close();
389 }
390 }
391
392 /**
393 * Returns the {@code X509Certificate} chain for the requested
Rubin Xub4365912016-03-23 12:13:22 +0000394 * alias, or null if there is no result.
395 * <p>
396 * <strong>Note:</strong> If a certificate chain was explicitly specified when the alias was
397 * installed, this method will return that chain. If only the client certificate was specified
398 * at the installation time, this method will try to build a certificate chain using all
399 * available trust anchors (preinstalled and user-added).
Brian Carlstrom93201f52011-06-09 15:05:35 -0700400 *
Robin Lee59e3baa2015-06-30 10:48:06 -0700401 * <p> This method may block while waiting for a connection to another process, and must never
402 * be called from the main thread.
403 *
Brian Carlstrom93201f52011-06-09 15:05:35 -0700404 * @param alias The alias of the desired certificate chain, typically
405 * returned via {@link KeyChainAliasCallback#alias}.
406 * @throws KeyChainException if the alias was valid but there was some problem accessing it.
Robin Lee59e3baa2015-06-30 10:48:06 -0700407 * @throws IllegalStateException if called from the main thread.
Brian Carlstromba1a6672011-05-24 21:54:37 -0700408 */
Robin Lee59e3baa2015-06-30 10:48:06 -0700409 @Nullable @WorkerThread
Alex Klyubin54bb1592015-05-11 12:30:03 -0700410 public static X509Certificate[] getCertificateChain(@NonNull Context context,
411 @NonNull String alias) throws KeyChainException, InterruptedException {
Brian Carlstromba1a6672011-05-24 21:54:37 -0700412 if (alias == null) {
413 throw new NullPointerException("alias == null");
414 }
415 KeyChainConnection keyChainConnection = bind(context);
416 try {
Brian Carlstromba1a6672011-05-24 21:54:37 -0700417 IKeyChainService keyChainService = keyChainConnection.getService();
Kenny Root0150e482013-02-13 15:22:50 -0800418
419 final byte[] certificateBytes = keyChainService.getCertificate(alias);
420 if (certificateBytes == null) {
421 return null;
422 }
Rubin Xub4365912016-03-23 12:13:22 +0000423 X509Certificate leafCert = toCertificate(certificateBytes);
424 final byte[] certChainBytes = keyChainService.getCaCertificates(alias);
425 // If the keypair is installed with a certificate chain by either
426 // DevicePolicyManager.installKeyPair or CertInstaller, return that chain.
427 if (certChainBytes != null && certChainBytes.length != 0) {
428 Collection<X509Certificate> chain = toCertificates(certChainBytes);
429 ArrayList<X509Certificate> fullChain = new ArrayList<>(chain.size() + 1);
430 fullChain.add(leafCert);
431 fullChain.addAll(chain);
432 return fullChain.toArray(new X509Certificate[fullChain.size()]);
433 } else {
434 // If there isn't a certificate chain, either due to a pre-existing keypair
435 // installed before N, or no chain is explicitly installed under the new logic,
436 // fall back to old behavior of constructing the chain from trusted credentials.
437 //
438 // This logic exists to maintain old behaviour for already installed keypair, at
439 // the cost of potentially returning extra certificate chain for new clients who
440 // explicitly installed only the client certificate without a chain. The latter
441 // case is actually no different from pre-N behaviour of getCertificateChain(),
442 // in that sense this change introduces no regression. Besides the returned chain
443 // is still valid so the consumer of the chain should have no problem verifying it.
444 TrustedCertificateStore store = new TrustedCertificateStore();
445 List<X509Certificate> chain = store.getCertificateChain(leafCert);
446 return chain.toArray(new X509Certificate[chain.size()]);
447 }
Kenny Rootcfba6a02013-05-06 15:00:58 -0700448 } catch (CertificateException e) {
449 throw new KeyChainException(e);
Brian Carlstrom93201f52011-06-09 15:05:35 -0700450 } catch (RemoteException e) {
451 throw new KeyChainException(e);
452 } catch (RuntimeException e) {
453 // only certain RuntimeExceptions can be propagated across the IKeyChainService call
454 throw new KeyChainException(e);
Brian Carlstrom8e9929c2011-05-17 00:40:28 -0700455 } finally {
Brian Carlstromd7524722011-05-17 16:20:36 -0700456 keyChainConnection.close();
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700457 }
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700458 }
459
Kenny Rootbf556ac2013-04-01 15:10:22 -0700460 /**
461 * Returns {@code true} if the current device's {@code KeyChain} supports a
462 * specific {@code PrivateKey} type indicated by {@code algorithm} (e.g.,
463 * "RSA").
464 */
Alex Klyubin4d5443f2015-05-06 15:43:52 -0700465 public static boolean isKeyAlgorithmSupported(
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700466 @NonNull @KeyProperties.KeyAlgorithmEnum String algorithm) {
Kenny Rootb91773b2013-09-05 13:03:16 -0700467 final String algUpper = algorithm.toUpperCase(Locale.US);
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700468 return KeyProperties.KEY_ALGORITHM_EC.equals(algUpper)
469 || KeyProperties.KEY_ALGORITHM_RSA.equals(algUpper);
Kenny Rootbf556ac2013-04-01 15:10:22 -0700470 }
471
472 /**
473 * Returns {@code true} if the current device's {@code KeyChain} binds any
474 * {@code PrivateKey} of the given {@code algorithm} to the device once
475 * imported or generated. This can be used to tell if there is special
476 * hardware support that can be used to bind keys to the device in a way
477 * that makes it non-exportable.
Alex Klyubin469cbf52015-06-04 12:36:27 -0700478 *
479 * @deprecated Whether the key is bound to the secure hardware is known only
480 * once the key has been imported. To find out, use:
481 * <pre>{@code
482 * PrivateKey key = ...; // private key from KeyChain
483 *
484 * KeyFactory keyFactory =
485 * KeyFactory.getInstance(key.getAlgorithm(), "AndroidKeyStore");
486 * KeyInfo keyInfo = keyFactory.getKeySpec(key, KeyInfo.class);
Neil Fuller71fbb812015-11-30 09:51:33 +0000487 * if (keyInfo.isInsideSecureHardware()) {
Alex Klyubin469cbf52015-06-04 12:36:27 -0700488 * // The key is bound to the secure hardware of this Android
Neil Fuller71fbb812015-11-30 09:51:33 +0000489 * }}</pre>
Kenny Rootbf556ac2013-04-01 15:10:22 -0700490 */
Alex Klyubin469cbf52015-06-04 12:36:27 -0700491 @Deprecated
Alex Klyubin4d5443f2015-05-06 15:43:52 -0700492 public static boolean isBoundKeyAlgorithm(
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700493 @NonNull @KeyProperties.KeyAlgorithmEnum String algorithm) {
Kenny Root5b7e90a2013-04-02 11:23:41 -0700494 if (!isKeyAlgorithmSupported(algorithm)) {
Kenny Rootbf556ac2013-04-01 15:10:22 -0700495 return false;
496 }
497
Kenny Rootb91773b2013-09-05 13:03:16 -0700498 return KeyStore.getInstance().isHardwareBacked(algorithm);
Kenny Rootbf556ac2013-04-01 15:10:22 -0700499 }
500
Zoltan Szatmary-Banf0ae1352014-08-18 10:48:33 +0100501 /** @hide */
Alex Klyubin54bb1592015-05-11 12:30:03 -0700502 @NonNull
503 public static X509Certificate toCertificate(@NonNull byte[] bytes) {
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700504 if (bytes == null) {
Brian Carlstrom8e9929c2011-05-17 00:40:28 -0700505 throw new IllegalArgumentException("bytes == null");
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700506 }
507 try {
508 CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
509 Certificate cert = certFactory.generateCertificate(new ByteArrayInputStream(bytes));
510 return (X509Certificate) cert;
511 } catch (CertificateException e) {
512 throw new AssertionError(e);
513 }
514 }
515
Rubin Xub4365912016-03-23 12:13:22 +0000516 /** @hide */
517 @NonNull
518 public static Collection<X509Certificate> toCertificates(@NonNull byte[] bytes) {
519 if (bytes == null) {
520 throw new IllegalArgumentException("bytes == null");
521 }
522 try {
523 CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
524 return (Collection<X509Certificate>) certFactory.generateCertificates(
525 new ByteArrayInputStream(bytes));
526 } catch (CertificateException e) {
527 throw new AssertionError(e);
528 }
529 }
530
Brian Carlstromd7524722011-05-17 16:20:36 -0700531 /**
532 * @hide for reuse by CertInstaller and Settings.
533 * @see KeyChain#bind
534 */
535 public final static class KeyChainConnection implements Closeable {
536 private final Context context;
537 private final ServiceConnection serviceConnection;
538 private final IKeyChainService service;
539 private KeyChainConnection(Context context,
540 ServiceConnection serviceConnection,
541 IKeyChainService service) {
542 this.context = context;
543 this.serviceConnection = serviceConnection;
544 this.service = service;
545 }
546 @Override public void close() {
547 context.unbindService(serviceConnection);
548 }
549 public IKeyChainService getService() {
550 return service;
551 }
552 }
553
554 /**
555 * @hide for reuse by CertInstaller and Settings.
556 *
557 * Caller should call unbindService on the result when finished.
558 */
Robin Lee59e3baa2015-06-30 10:48:06 -0700559 @WorkerThread
Alex Klyubin54bb1592015-05-11 12:30:03 -0700560 public static KeyChainConnection bind(@NonNull Context context) throws InterruptedException {
Robin Lee306fe082014-06-19 14:04:24 +0000561 return bindAsUser(context, Process.myUserHandle());
562 }
563
564 /**
565 * @hide
566 */
Robin Lee59e3baa2015-06-30 10:48:06 -0700567 @WorkerThread
Alex Klyubin54bb1592015-05-11 12:30:03 -0700568 public static KeyChainConnection bindAsUser(@NonNull Context context, UserHandle user)
Robin Lee306fe082014-06-19 14:04:24 +0000569 throws InterruptedException {
Brian Carlstromd7524722011-05-17 16:20:36 -0700570 if (context == null) {
571 throw new NullPointerException("context == null");
572 }
573 ensureNotOnMainThread(context);
574 final BlockingQueue<IKeyChainService> q = new LinkedBlockingQueue<IKeyChainService>(1);
575 ServiceConnection keyChainServiceConnection = new ServiceConnection() {
Fred Quintanaab8b84a2011-07-13 14:55:39 -0700576 volatile boolean mConnectedAtLeastOnce = false;
Brian Carlstromd7524722011-05-17 16:20:36 -0700577 @Override public void onServiceConnected(ComponentName name, IBinder service) {
Fred Quintanaab8b84a2011-07-13 14:55:39 -0700578 if (!mConnectedAtLeastOnce) {
579 mConnectedAtLeastOnce = true;
580 try {
581 q.put(IKeyChainService.Stub.asInterface(service));
582 } catch (InterruptedException e) {
583 // will never happen, since the queue starts with one available slot
584 }
Brian Carlstromd7524722011-05-17 16:20:36 -0700585 }
586 }
587 @Override public void onServiceDisconnected(ComponentName name) {}
588 };
Maggie Benthallda51e682013-08-08 22:35:44 -0400589 Intent intent = new Intent(IKeyChainService.class.getName());
590 ComponentName comp = intent.resolveSystemService(context.getPackageManager(), 0);
591 intent.setComponent(comp);
Robin Lee21bcbc52016-02-29 18:55:35 +0000592 if (comp == null || !context.bindServiceAsUser(
593 intent, keyChainServiceConnection, Context.BIND_AUTO_CREATE, user)) {
Brian Carlstromd7524722011-05-17 16:20:36 -0700594 throw new AssertionError("could not bind to KeyChainService");
595 }
596 return new KeyChainConnection(context, keyChainServiceConnection, q.take());
597 }
598
Alex Klyubin54bb1592015-05-11 12:30:03 -0700599 private static void ensureNotOnMainThread(@NonNull Context context) {
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700600 Looper looper = Looper.myLooper();
Brian Carlstrom8e9929c2011-05-17 00:40:28 -0700601 if (looper != null && looper == context.getMainLooper()) {
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700602 throw new IllegalStateException(
603 "calling this from your main thread can lead to deadlock");
604 }
605 }
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700606}