blob: adfdfba6a33debf25df1b5ee1d8b333231825b25 [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;
Chad Brubaker721afae2016-07-08 11:06:09 -070028import android.os.Build;
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 /**
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>
Chad Brubaker4de59ef2016-05-02 13:17:31 -0700194 *
Chad Brubakerdbf01c12016-07-25 14:54:39 -0700195 * @deprecated Use {@link #ACTION_KEYCHAIN_CHANGED}, {@link #ACTION_TRUST_STORE_CHANGED} or
Chad Brubaker721afae2016-07-08 11:06:09 -0700196 * {@link #ACTION_KEY_ACCESS_CHANGED}. Apps that target a version higher than
197 * {@link Build.VERSION_CODES#N_MR1} will not receive this broadcast.
Selim Gurun93ba4fe2012-02-14 11:48:49 -0800198 */
199 public static final String ACTION_STORAGE_CHANGED = "android.security.STORAGE_CHANGED";
200
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700201 /**
Chad Brubaker4de59ef2016-05-02 13:17:31 -0700202 * Broadcast Action: Indicates the contents of the keychain has changed. Sent when a KeyChain
203 * entry is added, modified or removed.
204 */
205 public static final String ACTION_KEYCHAIN_CHANGED = "android.security.action.KEYCHAIN_CHANGED";
206
207 /**
208 * Broadcast Action: Indicates the contents of the trusted certificate store has changed. Sent
209 * when one the following occurs:
210 *
211 * <ul>
212 * <li>A pre-installed CA is disabled or re-enabled</li>
213 * <li>A CA is added or removed from the trust store</li>
214 * </ul>
215 */
216 public static final String ACTION_TRUST_STORE_CHANGED =
217 "android.security.action.TRUST_STORE_CHANGED";
218
219 /**
220 * Broadcast Action: Indicates that the access permissions for a private key have changed.
221 *
222 */
223 public static final String ACTION_KEY_ACCESS_CHANGED =
224 "android.security.action.KEY_ACCESS_CHANGED";
225
226 /**
227 * Used as a String extra field in {@link #ACTION_KEY_ACCESS_CHANGED} to supply the alias of
228 * the key.
229 */
230 public static final String EXTRA_KEY_ALIAS = "android.security.extra.KEY_ALIAS";
231
232 /**
233 * Used as a boolean extra field in {@link #ACTION_KEY_ACCESS_CHANGED} to supply if the key is
234 * accessible to the application.
235 */
236 public static final String EXTRA_KEY_ACCESSIBLE = "android.security.extra.KEY_ACCESSIBLE";
237
238 /**
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700239 * Returns an {@code Intent} that can be used for credential
240 * installation. The intent may be used without any extras, in
241 * which case the user will be able to install credentials from
242 * their own source.
243 *
244 * <p>Alternatively, {@link #EXTRA_CERTIFICATE} or {@link
245 * #EXTRA_PKCS12} maybe used to specify the bytes of an X.509
246 * certificate or a PKCS#12 key store for installation. These
Brian Carlstromca43c452011-06-29 18:53:17 -0700247 * extras may be combined with {@link #EXTRA_NAME} to provide a
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700248 * default alias name for credentials being installed.
249 *
250 * <p>When used with {@link Activity#startActivityForResult},
251 * {@link Activity#RESULT_OK} will be returned if a credential was
252 * successfully installed, otherwise {@link
253 * Activity#RESULT_CANCELED} will be returned.
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700254 */
Alex Klyubin54bb1592015-05-11 12:30:03 -0700255 @NonNull
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700256 public static Intent createInstallIntent() {
257 Intent intent = new Intent(ACTION_INSTALL);
Kenny Root1a88d832014-02-07 09:12:48 -0800258 intent.setClassName(CERT_INSTALLER_PACKAGE,
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700259 "com.android.certinstaller.CertInstallerMain");
260 return intent;
261 }
262
263 /**
Brian Carlstromba1a6672011-05-24 21:54:37 -0700264 * Launches an {@code Activity} for the user to select the alias
265 * for a private key and certificate pair for authentication. The
266 * selected alias or null will be returned via the
Brian Carlstrom93201f52011-06-09 15:05:35 -0700267 * KeyChainAliasCallback callback.
268 *
Robin Lee3798ed52015-02-03 17:55:31 +0000269 * <p>The device or profile owner can intercept this before the activity
270 * is shown, to pick a specific private key alias.
271 *
272 * <p>{@code keyTypes} and {@code issuers} may be used to
273 * highlight suggested choices to the user, although to cope with
274 * sometimes erroneous values provided by servers, the user may be
275 * able to override these suggestions.
276 *
277 * <p>{@code host} and {@code port} may be used to give the user
278 * more context about the server requesting the credentials.
279 *
280 * <p>{@code alias} allows the chooser to preselect an existing
281 * alias which will still be subject to user confirmation.
282 *
283 * @param activity The {@link Activity} context to use for
284 * launching the new sub-Activity to prompt the user to select
285 * a private key; used only to call startActivity(); must not
286 * be null.
287 * @param response Callback to invoke when the request completes;
288 * must not be null
289 * @param keyTypes The acceptable types of asymmetric keys such as
290 * "RSA" or "DSA", or a null array.
291 * @param issuers The acceptable certificate issuers for the
292 * certificate matching the private key, or null.
293 * @param host The host name of the server requesting the
294 * certificate, or null if unavailable.
295 * @param port The port number of the server requesting the
296 * certificate, or -1 if unavailable.
297 * @param alias The alias to preselect if available, or null if
298 * unavailable.
299 */
Alex Klyubin54bb1592015-05-11 12:30:03 -0700300 public static void choosePrivateKeyAlias(@NonNull Activity activity,
301 @NonNull KeyChainAliasCallback response,
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700302 @KeyProperties.KeyAlgorithmEnum String[] keyTypes, Principal[] issuers,
Alex Klyubin54bb1592015-05-11 12:30:03 -0700303 @Nullable String host, int port, @Nullable String alias) {
Robin Lee39087b12015-05-05 15:57:17 +0100304 Uri uri = null;
305 if (host != null) {
306 uri = new Uri.Builder()
307 .authority(host + (port != -1 ? ":" + port : ""))
308 .build();
309 }
310 choosePrivateKeyAlias(activity, response, keyTypes, issuers, uri, alias);
Robin Lee3798ed52015-02-03 17:55:31 +0000311 }
312
313 /**
314 * Launches an {@code Activity} for the user to select the alias
315 * for a private key and certificate pair for authentication. The
316 * selected alias or null will be returned via the
317 * KeyChainAliasCallback callback.
318 *
319 * <p>The device or profile owner can intercept this before the activity
320 * is shown, to pick a specific private key alias.</p>
321 *
Brian Carlstrom93201f52011-06-09 15:05:35 -0700322 * <p>{@code keyTypes} and {@code issuers} may be used to
323 * highlight suggested choices to the user, although to cope with
324 * sometimes erroneous values provided by servers, the user may be
325 * able to override these suggestions.
326 *
327 * <p>{@code host} and {@code port} may be used to give the user
328 * more context about the server requesting the credentials.
329 *
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700330 * <p>{@code alias} allows the chooser to preselect an existing
331 * alias which will still be subject to user confirmation.
332 *
Brian Carlstrom93201f52011-06-09 15:05:35 -0700333 * @param activity The {@link Activity} context to use for
334 * launching the new sub-Activity to prompt the user to select
335 * a private key; used only to call startActivity(); must not
336 * be null.
337 * @param response Callback to invoke when the request completes;
338 * must not be null
339 * @param keyTypes The acceptable types of asymmetric keys such as
Alex Klyubincd2329d2015-01-14 16:45:51 -0800340 * "EC" or "RSA", or a null array.
Brian Carlstrom93201f52011-06-09 15:05:35 -0700341 * @param issuers The acceptable certificate issuers for the
342 * certificate matching the private key, or null.
Robin Lee39087b12015-05-05 15:57:17 +0100343 * @param uri The full URI the server is requesting the certificate
Robin Lee3798ed52015-02-03 17:55:31 +0000344 * for, or null if unavailable.
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700345 * @param alias The alias to preselect if available, or null if
346 * unavailable.
Brian Carlstromba1a6672011-05-24 21:54:37 -0700347 */
Alex Klyubin54bb1592015-05-11 12:30:03 -0700348 public static void choosePrivateKeyAlias(@NonNull Activity activity,
349 @NonNull KeyChainAliasCallback response,
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700350 @KeyProperties.KeyAlgorithmEnum String[] keyTypes, Principal[] issuers,
Robin Lee39087b12015-05-05 15:57:17 +0100351 @Nullable Uri uri, @Nullable String alias) {
Brian Carlstrom93201f52011-06-09 15:05:35 -0700352 /*
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700353 * TODO currently keyTypes, issuers are unused. They are meant
354 * to follow the semantics and purpose of X509KeyManager
355 * method arguments.
Brian Carlstrom93201f52011-06-09 15:05:35 -0700356 *
357 * keyTypes would allow the list to be filtered and typically
358 * will be set correctly by the server. In practice today,
Alex Klyubincd2329d2015-01-14 16:45:51 -0800359 * most all users will want only RSA or EC, and usually
Brian Carlstrom93201f52011-06-09 15:05:35 -0700360 * only a small number of certs will be available.
361 *
362 * issuers is typically not useful. Some servers historically
363 * will send the entire list of public CAs known to the
364 * server. Others will send none. If this is used, if there
365 * are no matches after applying the constraint, it should be
366 * ignored.
Brian Carlstrom93201f52011-06-09 15:05:35 -0700367 */
Brian Carlstromba1a6672011-05-24 21:54:37 -0700368 if (activity == null) {
369 throw new NullPointerException("activity == null");
370 }
371 if (response == null) {
372 throw new NullPointerException("response == null");
373 }
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700374 Intent intent = new Intent(ACTION_CHOOSER);
Kenny Roota3659062014-03-17 16:21:53 -0700375 intent.setPackage(KEYCHAIN_PACKAGE);
Fred Quintanaab8b84a2011-07-13 14:55:39 -0700376 intent.putExtra(EXTRA_RESPONSE, new AliasResponse(response));
Robin Lee39087b12015-05-05 15:57:17 +0100377 intent.putExtra(EXTRA_URI, uri);
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700378 intent.putExtra(EXTRA_ALIAS, alias);
379 // the PendingIntent is used to get calling package name
380 intent.putExtra(EXTRA_SENDER, PendingIntent.getActivity(activity, 0, new Intent(), 0));
Brian Carlstromba1a6672011-05-24 21:54:37 -0700381 activity.startActivity(intent);
382 }
383
Brian Carlstrom93201f52011-06-09 15:05:35 -0700384 private static class AliasResponse extends IKeyChainAliasCallback.Stub {
Brian Carlstrom93201f52011-06-09 15:05:35 -0700385 private final KeyChainAliasCallback keyChainAliasResponse;
Fred Quintanaab8b84a2011-07-13 14:55:39 -0700386 private AliasResponse(KeyChainAliasCallback keyChainAliasResponse) {
Brian Carlstromba1a6672011-05-24 21:54:37 -0700387 this.keyChainAliasResponse = keyChainAliasResponse;
388 }
389 @Override public void alias(String alias) {
Fred Quintanaab8b84a2011-07-13 14:55:39 -0700390 keyChainAliasResponse.alias(alias);
Brian Carlstromba1a6672011-05-24 21:54:37 -0700391 }
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700392 }
393
394 /**
Brian Carlstromba1a6672011-05-24 21:54:37 -0700395 * Returns the {@code PrivateKey} for the requested alias, or null
Robin Lee3a435f02015-12-21 12:06:04 +0000396 * if there is no result.
Brian Carlstrom93201f52011-06-09 15:05:35 -0700397 *
Robin Lee59e3baa2015-06-30 10:48:06 -0700398 * <p> This method may block while waiting for a connection to another process, and must never
399 * be called from the main thread.
400 *
401 * @param alias The alias of the desired private key, typically returned via
402 * {@link KeyChainAliasCallback#alias}.
Brian Carlstrom93201f52011-06-09 15:05:35 -0700403 * @throws KeyChainException if the alias was valid but there was some problem accessing it.
Robin Lee59e3baa2015-06-30 10:48:06 -0700404 * @throws IllegalStateException if called from the main thread.
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700405 */
Robin Lee59e3baa2015-06-30 10:48:06 -0700406 @Nullable @WorkerThread
Alex Klyubin54bb1592015-05-11 12:30:03 -0700407 public static PrivateKey getPrivateKey(@NonNull Context context, @NonNull String alias)
Brian Carlstrom93201f52011-06-09 15:05:35 -0700408 throws KeyChainException, InterruptedException {
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700409 if (alias == null) {
410 throw new NullPointerException("alias == null");
411 }
Robin Lee28d68b12016-07-22 16:32:32 +0100412
413 final String keyId;
414 try (KeyChainConnection keyChainConnection = bind(context.getApplicationContext())) {
415 keyId = keyChainConnection.getService().requestPrivateKey(alias);
Brian Carlstrom93201f52011-06-09 15:05:35 -0700416 } catch (RemoteException e) {
417 throw new KeyChainException(e);
418 } catch (RuntimeException e) {
419 // only certain RuntimeExceptions can be propagated across the IKeyChainService call
420 throw new KeyChainException(e);
Robin Lee28d68b12016-07-22 16:32:32 +0100421 }
422
423 if (keyId == null) {
424 return null;
425 } else {
426 try {
427 return AndroidKeyStoreProvider.loadAndroidKeyStorePrivateKeyFromKeystore(
428 KeyStore.getInstance(), keyId, KeyStore.UID_SELF);
429 } catch (RuntimeException | UnrecoverableKeyException e) {
430 throw new KeyChainException(e);
431 }
Brian Carlstromba1a6672011-05-24 21:54:37 -0700432 }
433 }
434
435 /**
436 * Returns the {@code X509Certificate} chain for the requested
Rubin Xub4365912016-03-23 12:13:22 +0000437 * alias, or null if there is no result.
438 * <p>
439 * <strong>Note:</strong> If a certificate chain was explicitly specified when the alias was
440 * installed, this method will return that chain. If only the client certificate was specified
441 * at the installation time, this method will try to build a certificate chain using all
442 * available trust anchors (preinstalled and user-added).
Brian Carlstrom93201f52011-06-09 15:05:35 -0700443 *
Robin Lee59e3baa2015-06-30 10:48:06 -0700444 * <p> This method may block while waiting for a connection to another process, and must never
445 * be called from the main thread.
446 *
Brian Carlstrom93201f52011-06-09 15:05:35 -0700447 * @param alias The alias of the desired certificate chain, typically
448 * returned via {@link KeyChainAliasCallback#alias}.
449 * @throws KeyChainException if the alias was valid but there was some problem accessing it.
Robin Lee59e3baa2015-06-30 10:48:06 -0700450 * @throws IllegalStateException if called from the main thread.
Brian Carlstromba1a6672011-05-24 21:54:37 -0700451 */
Robin Lee59e3baa2015-06-30 10:48:06 -0700452 @Nullable @WorkerThread
Alex Klyubin54bb1592015-05-11 12:30:03 -0700453 public static X509Certificate[] getCertificateChain(@NonNull Context context,
454 @NonNull String alias) throws KeyChainException, InterruptedException {
Brian Carlstromba1a6672011-05-24 21:54:37 -0700455 if (alias == null) {
456 throw new NullPointerException("alias == null");
457 }
Kenny Root0150e482013-02-13 15:22:50 -0800458
Robin Lee28d68b12016-07-22 16:32:32 +0100459 final byte[] certificateBytes;
460 final byte[] certChainBytes;
461 try (KeyChainConnection keyChainConnection = bind(context.getApplicationContext())) {
462 IKeyChainService keyChainService = keyChainConnection.getService();
463 certificateBytes = keyChainService.getCertificate(alias);
Kenny Root0150e482013-02-13 15:22:50 -0800464 if (certificateBytes == null) {
465 return null;
466 }
Robin Lee28d68b12016-07-22 16:32:32 +0100467 certChainBytes = keyChainService.getCaCertificates(alias);
468 } catch (RemoteException e) {
469 throw new KeyChainException(e);
470 } catch (RuntimeException e) {
471 // only certain RuntimeExceptions can be propagated across the IKeyChainService call
472 throw new KeyChainException(e);
473 }
474
475 try {
Rubin Xub4365912016-03-23 12:13:22 +0000476 X509Certificate leafCert = toCertificate(certificateBytes);
Rubin Xub4365912016-03-23 12:13:22 +0000477 // If the keypair is installed with a certificate chain by either
478 // DevicePolicyManager.installKeyPair or CertInstaller, return that chain.
479 if (certChainBytes != null && certChainBytes.length != 0) {
480 Collection<X509Certificate> chain = toCertificates(certChainBytes);
481 ArrayList<X509Certificate> fullChain = new ArrayList<>(chain.size() + 1);
482 fullChain.add(leafCert);
483 fullChain.addAll(chain);
484 return fullChain.toArray(new X509Certificate[fullChain.size()]);
485 } else {
486 // If there isn't a certificate chain, either due to a pre-existing keypair
487 // installed before N, or no chain is explicitly installed under the new logic,
488 // fall back to old behavior of constructing the chain from trusted credentials.
489 //
490 // This logic exists to maintain old behaviour for already installed keypair, at
491 // the cost of potentially returning extra certificate chain for new clients who
492 // explicitly installed only the client certificate without a chain. The latter
493 // case is actually no different from pre-N behaviour of getCertificateChain(),
494 // in that sense this change introduces no regression. Besides the returned chain
495 // is still valid so the consumer of the chain should have no problem verifying it.
496 TrustedCertificateStore store = new TrustedCertificateStore();
497 List<X509Certificate> chain = store.getCertificateChain(leafCert);
498 return chain.toArray(new X509Certificate[chain.size()]);
499 }
Robin Lee28d68b12016-07-22 16:32:32 +0100500 } catch (CertificateException | RuntimeException e) {
Kenny Rootcfba6a02013-05-06 15:00:58 -0700501 throw new KeyChainException(e);
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700502 }
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700503 }
504
Kenny Rootbf556ac2013-04-01 15:10:22 -0700505 /**
506 * Returns {@code true} if the current device's {@code KeyChain} supports a
507 * specific {@code PrivateKey} type indicated by {@code algorithm} (e.g.,
508 * "RSA").
509 */
Alex Klyubin4d5443f2015-05-06 15:43:52 -0700510 public static boolean isKeyAlgorithmSupported(
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700511 @NonNull @KeyProperties.KeyAlgorithmEnum String algorithm) {
Kenny Rootb91773b2013-09-05 13:03:16 -0700512 final String algUpper = algorithm.toUpperCase(Locale.US);
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700513 return KeyProperties.KEY_ALGORITHM_EC.equals(algUpper)
514 || KeyProperties.KEY_ALGORITHM_RSA.equals(algUpper);
Kenny Rootbf556ac2013-04-01 15:10:22 -0700515 }
516
517 /**
518 * Returns {@code true} if the current device's {@code KeyChain} binds any
519 * {@code PrivateKey} of the given {@code algorithm} to the device once
520 * imported or generated. This can be used to tell if there is special
521 * hardware support that can be used to bind keys to the device in a way
522 * that makes it non-exportable.
Alex Klyubin469cbf52015-06-04 12:36:27 -0700523 *
524 * @deprecated Whether the key is bound to the secure hardware is known only
525 * once the key has been imported. To find out, use:
526 * <pre>{@code
527 * PrivateKey key = ...; // private key from KeyChain
528 *
529 * KeyFactory keyFactory =
530 * KeyFactory.getInstance(key.getAlgorithm(), "AndroidKeyStore");
531 * KeyInfo keyInfo = keyFactory.getKeySpec(key, KeyInfo.class);
Neil Fuller71fbb812015-11-30 09:51:33 +0000532 * if (keyInfo.isInsideSecureHardware()) {
Alex Klyubin469cbf52015-06-04 12:36:27 -0700533 * // The key is bound to the secure hardware of this Android
Neil Fuller71fbb812015-11-30 09:51:33 +0000534 * }}</pre>
Kenny Rootbf556ac2013-04-01 15:10:22 -0700535 */
Alex Klyubin469cbf52015-06-04 12:36:27 -0700536 @Deprecated
Alex Klyubin4d5443f2015-05-06 15:43:52 -0700537 public static boolean isBoundKeyAlgorithm(
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700538 @NonNull @KeyProperties.KeyAlgorithmEnum String algorithm) {
Kenny Root5b7e90a2013-04-02 11:23:41 -0700539 if (!isKeyAlgorithmSupported(algorithm)) {
Kenny Rootbf556ac2013-04-01 15:10:22 -0700540 return false;
541 }
542
Kenny Rootb91773b2013-09-05 13:03:16 -0700543 return KeyStore.getInstance().isHardwareBacked(algorithm);
Kenny Rootbf556ac2013-04-01 15:10:22 -0700544 }
545
Zoltan Szatmary-Banf0ae1352014-08-18 10:48:33 +0100546 /** @hide */
Alex Klyubin54bb1592015-05-11 12:30:03 -0700547 @NonNull
548 public static X509Certificate toCertificate(@NonNull byte[] bytes) {
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700549 if (bytes == null) {
Brian Carlstrom8e9929c2011-05-17 00:40:28 -0700550 throw new IllegalArgumentException("bytes == null");
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700551 }
552 try {
553 CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
554 Certificate cert = certFactory.generateCertificate(new ByteArrayInputStream(bytes));
555 return (X509Certificate) cert;
556 } catch (CertificateException e) {
557 throw new AssertionError(e);
558 }
559 }
560
Rubin Xub4365912016-03-23 12:13:22 +0000561 /** @hide */
562 @NonNull
563 public static Collection<X509Certificate> toCertificates(@NonNull byte[] bytes) {
564 if (bytes == null) {
565 throw new IllegalArgumentException("bytes == null");
566 }
567 try {
568 CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
569 return (Collection<X509Certificate>) certFactory.generateCertificates(
570 new ByteArrayInputStream(bytes));
571 } catch (CertificateException e) {
572 throw new AssertionError(e);
573 }
574 }
575
Brian Carlstromd7524722011-05-17 16:20:36 -0700576 /**
577 * @hide for reuse by CertInstaller and Settings.
578 * @see KeyChain#bind
579 */
580 public final static class KeyChainConnection implements Closeable {
581 private final Context context;
582 private final ServiceConnection serviceConnection;
583 private final IKeyChainService service;
584 private KeyChainConnection(Context context,
585 ServiceConnection serviceConnection,
586 IKeyChainService service) {
587 this.context = context;
588 this.serviceConnection = serviceConnection;
589 this.service = service;
590 }
591 @Override public void close() {
592 context.unbindService(serviceConnection);
593 }
594 public IKeyChainService getService() {
595 return service;
596 }
597 }
598
599 /**
600 * @hide for reuse by CertInstaller and Settings.
601 *
602 * Caller should call unbindService on the result when finished.
603 */
Robin Lee59e3baa2015-06-30 10:48:06 -0700604 @WorkerThread
Alex Klyubin54bb1592015-05-11 12:30:03 -0700605 public static KeyChainConnection bind(@NonNull Context context) throws InterruptedException {
Robin Lee306fe082014-06-19 14:04:24 +0000606 return bindAsUser(context, Process.myUserHandle());
607 }
608
609 /**
610 * @hide
611 */
Robin Lee59e3baa2015-06-30 10:48:06 -0700612 @WorkerThread
Alex Klyubin54bb1592015-05-11 12:30:03 -0700613 public static KeyChainConnection bindAsUser(@NonNull Context context, UserHandle user)
Robin Lee306fe082014-06-19 14:04:24 +0000614 throws InterruptedException {
Brian Carlstromd7524722011-05-17 16:20:36 -0700615 if (context == null) {
616 throw new NullPointerException("context == null");
617 }
618 ensureNotOnMainThread(context);
619 final BlockingQueue<IKeyChainService> q = new LinkedBlockingQueue<IKeyChainService>(1);
620 ServiceConnection keyChainServiceConnection = new ServiceConnection() {
Fred Quintanaab8b84a2011-07-13 14:55:39 -0700621 volatile boolean mConnectedAtLeastOnce = false;
Brian Carlstromd7524722011-05-17 16:20:36 -0700622 @Override public void onServiceConnected(ComponentName name, IBinder service) {
Fred Quintanaab8b84a2011-07-13 14:55:39 -0700623 if (!mConnectedAtLeastOnce) {
624 mConnectedAtLeastOnce = true;
625 try {
626 q.put(IKeyChainService.Stub.asInterface(service));
627 } catch (InterruptedException e) {
628 // will never happen, since the queue starts with one available slot
629 }
Brian Carlstromd7524722011-05-17 16:20:36 -0700630 }
631 }
632 @Override public void onServiceDisconnected(ComponentName name) {}
633 };
Maggie Benthallda51e682013-08-08 22:35:44 -0400634 Intent intent = new Intent(IKeyChainService.class.getName());
635 ComponentName comp = intent.resolveSystemService(context.getPackageManager(), 0);
636 intent.setComponent(comp);
Robin Lee21bcbc52016-02-29 18:55:35 +0000637 if (comp == null || !context.bindServiceAsUser(
638 intent, keyChainServiceConnection, Context.BIND_AUTO_CREATE, user)) {
Brian Carlstromd7524722011-05-17 16:20:36 -0700639 throw new AssertionError("could not bind to KeyChainService");
640 }
641 return new KeyChainConnection(context, keyChainServiceConnection, q.take());
642 }
643
Alex Klyubin54bb1592015-05-11 12:30:03 -0700644 private static void ensureNotOnMainThread(@NonNull Context context) {
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700645 Looper looper = Looper.myLooper();
Brian Carlstrom8e9929c2011-05-17 00:40:28 -0700646 if (looper != null && looper == context.getMainLooper()) {
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700647 throw new IllegalStateException(
648 "calling this from your main thread can lead to deadlock");
649 }
650 }
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700651}