blob: 3ab60f86542c798f4806a1925b0e9b0e1451ea69 [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 Lee43e235c2016-07-25 16:09:22 +0100412 KeyChainConnection keyChainConnection = bind(context.getApplicationContext());
Brian Carlstrom8e9929c2011-05-17 00:40:28 -0700413 try {
Kenny Root5423e682011-11-14 08:43:13 -0800414 final IKeyChainService keyChainService = keyChainConnection.getService();
415 final String keyId = keyChainService.requestPrivateKey(alias);
416 if (keyId == null) {
Robin Lee3a435f02015-12-21 12:06:04 +0000417 return null;
Kenny Root5423e682011-11-14 08:43:13 -0800418 }
Alex Klyubin4a0ff7c2015-06-09 13:25:20 -0700419 return AndroidKeyStoreProvider.loadAndroidKeyStorePrivateKeyFromKeystore(
Alex Klyubin3876b1b2015-09-09 14:55:03 -0700420 KeyStore.getInstance(), keyId, KeyStore.UID_SELF);
Brian Carlstrom93201f52011-06-09 15:05:35 -0700421 } catch (RemoteException e) {
422 throw new KeyChainException(e);
423 } catch (RuntimeException e) {
424 // only certain RuntimeExceptions can be propagated across the IKeyChainService call
425 throw new KeyChainException(e);
Alex Klyubin4a0ff7c2015-06-09 13:25:20 -0700426 } catch (UnrecoverableKeyException e) {
Kenny Root5423e682011-11-14 08:43:13 -0800427 throw new KeyChainException(e);
Brian Carlstromba1a6672011-05-24 21:54:37 -0700428 } finally {
429 keyChainConnection.close();
430 }
431 }
432
433 /**
434 * Returns the {@code X509Certificate} chain for the requested
Rubin Xub4365912016-03-23 12:13:22 +0000435 * alias, or null if there is no result.
436 * <p>
437 * <strong>Note:</strong> If a certificate chain was explicitly specified when the alias was
438 * installed, this method will return that chain. If only the client certificate was specified
439 * at the installation time, this method will try to build a certificate chain using all
440 * available trust anchors (preinstalled and user-added).
Brian Carlstrom93201f52011-06-09 15:05:35 -0700441 *
Robin Lee59e3baa2015-06-30 10:48:06 -0700442 * <p> This method may block while waiting for a connection to another process, and must never
443 * be called from the main thread.
444 *
Brian Carlstrom93201f52011-06-09 15:05:35 -0700445 * @param alias The alias of the desired certificate chain, typically
446 * returned via {@link KeyChainAliasCallback#alias}.
447 * @throws KeyChainException if the alias was valid but there was some problem accessing it.
Robin Lee59e3baa2015-06-30 10:48:06 -0700448 * @throws IllegalStateException if called from the main thread.
Brian Carlstromba1a6672011-05-24 21:54:37 -0700449 */
Robin Lee59e3baa2015-06-30 10:48:06 -0700450 @Nullable @WorkerThread
Alex Klyubin54bb1592015-05-11 12:30:03 -0700451 public static X509Certificate[] getCertificateChain(@NonNull Context context,
452 @NonNull String alias) throws KeyChainException, InterruptedException {
Brian Carlstromba1a6672011-05-24 21:54:37 -0700453 if (alias == null) {
454 throw new NullPointerException("alias == null");
455 }
Robin Lee43e235c2016-07-25 16:09:22 +0100456 KeyChainConnection keyChainConnection = bind(context.getApplicationContext());
Brian Carlstromba1a6672011-05-24 21:54:37 -0700457 try {
Brian Carlstromba1a6672011-05-24 21:54:37 -0700458 IKeyChainService keyChainService = keyChainConnection.getService();
Kenny Root0150e482013-02-13 15:22:50 -0800459
460 final byte[] certificateBytes = keyChainService.getCertificate(alias);
461 if (certificateBytes == null) {
462 return null;
463 }
Rubin Xub4365912016-03-23 12:13:22 +0000464 X509Certificate leafCert = toCertificate(certificateBytes);
465 final byte[] certChainBytes = keyChainService.getCaCertificates(alias);
466 // If the keypair is installed with a certificate chain by either
467 // DevicePolicyManager.installKeyPair or CertInstaller, return that chain.
468 if (certChainBytes != null && certChainBytes.length != 0) {
469 Collection<X509Certificate> chain = toCertificates(certChainBytes);
470 ArrayList<X509Certificate> fullChain = new ArrayList<>(chain.size() + 1);
471 fullChain.add(leafCert);
472 fullChain.addAll(chain);
473 return fullChain.toArray(new X509Certificate[fullChain.size()]);
474 } else {
475 // If there isn't a certificate chain, either due to a pre-existing keypair
476 // installed before N, or no chain is explicitly installed under the new logic,
477 // fall back to old behavior of constructing the chain from trusted credentials.
478 //
479 // This logic exists to maintain old behaviour for already installed keypair, at
480 // the cost of potentially returning extra certificate chain for new clients who
481 // explicitly installed only the client certificate without a chain. The latter
482 // case is actually no different from pre-N behaviour of getCertificateChain(),
483 // in that sense this change introduces no regression. Besides the returned chain
484 // is still valid so the consumer of the chain should have no problem verifying it.
485 TrustedCertificateStore store = new TrustedCertificateStore();
486 List<X509Certificate> chain = store.getCertificateChain(leafCert);
487 return chain.toArray(new X509Certificate[chain.size()]);
488 }
Kenny Rootcfba6a02013-05-06 15:00:58 -0700489 } catch (CertificateException e) {
490 throw new KeyChainException(e);
Brian Carlstrom93201f52011-06-09 15:05:35 -0700491 } catch (RemoteException e) {
492 throw new KeyChainException(e);
493 } catch (RuntimeException e) {
494 // only certain RuntimeExceptions can be propagated across the IKeyChainService call
495 throw new KeyChainException(e);
Brian Carlstrom8e9929c2011-05-17 00:40:28 -0700496 } finally {
Brian Carlstromd7524722011-05-17 16:20:36 -0700497 keyChainConnection.close();
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700498 }
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700499 }
500
Kenny Rootbf556ac2013-04-01 15:10:22 -0700501 /**
502 * Returns {@code true} if the current device's {@code KeyChain} supports a
503 * specific {@code PrivateKey} type indicated by {@code algorithm} (e.g.,
504 * "RSA").
505 */
Alex Klyubin4d5443f2015-05-06 15:43:52 -0700506 public static boolean isKeyAlgorithmSupported(
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700507 @NonNull @KeyProperties.KeyAlgorithmEnum String algorithm) {
Kenny Rootb91773b2013-09-05 13:03:16 -0700508 final String algUpper = algorithm.toUpperCase(Locale.US);
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700509 return KeyProperties.KEY_ALGORITHM_EC.equals(algUpper)
510 || KeyProperties.KEY_ALGORITHM_RSA.equals(algUpper);
Kenny Rootbf556ac2013-04-01 15:10:22 -0700511 }
512
513 /**
514 * Returns {@code true} if the current device's {@code KeyChain} binds any
515 * {@code PrivateKey} of the given {@code algorithm} to the device once
516 * imported or generated. This can be used to tell if there is special
517 * hardware support that can be used to bind keys to the device in a way
518 * that makes it non-exportable.
Alex Klyubin469cbf52015-06-04 12:36:27 -0700519 *
520 * @deprecated Whether the key is bound to the secure hardware is known only
521 * once the key has been imported. To find out, use:
522 * <pre>{@code
523 * PrivateKey key = ...; // private key from KeyChain
524 *
525 * KeyFactory keyFactory =
526 * KeyFactory.getInstance(key.getAlgorithm(), "AndroidKeyStore");
527 * KeyInfo keyInfo = keyFactory.getKeySpec(key, KeyInfo.class);
Neil Fuller71fbb812015-11-30 09:51:33 +0000528 * if (keyInfo.isInsideSecureHardware()) {
Alex Klyubin469cbf52015-06-04 12:36:27 -0700529 * // The key is bound to the secure hardware of this Android
Neil Fuller71fbb812015-11-30 09:51:33 +0000530 * }}</pre>
Kenny Rootbf556ac2013-04-01 15:10:22 -0700531 */
Alex Klyubin469cbf52015-06-04 12:36:27 -0700532 @Deprecated
Alex Klyubin4d5443f2015-05-06 15:43:52 -0700533 public static boolean isBoundKeyAlgorithm(
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700534 @NonNull @KeyProperties.KeyAlgorithmEnum String algorithm) {
Kenny Root5b7e90a2013-04-02 11:23:41 -0700535 if (!isKeyAlgorithmSupported(algorithm)) {
Kenny Rootbf556ac2013-04-01 15:10:22 -0700536 return false;
537 }
538
Kenny Rootb91773b2013-09-05 13:03:16 -0700539 return KeyStore.getInstance().isHardwareBacked(algorithm);
Kenny Rootbf556ac2013-04-01 15:10:22 -0700540 }
541
Zoltan Szatmary-Banf0ae1352014-08-18 10:48:33 +0100542 /** @hide */
Alex Klyubin54bb1592015-05-11 12:30:03 -0700543 @NonNull
544 public static X509Certificate toCertificate(@NonNull byte[] bytes) {
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700545 if (bytes == null) {
Brian Carlstrom8e9929c2011-05-17 00:40:28 -0700546 throw new IllegalArgumentException("bytes == null");
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700547 }
548 try {
549 CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
550 Certificate cert = certFactory.generateCertificate(new ByteArrayInputStream(bytes));
551 return (X509Certificate) cert;
552 } catch (CertificateException e) {
553 throw new AssertionError(e);
554 }
555 }
556
Rubin Xub4365912016-03-23 12:13:22 +0000557 /** @hide */
558 @NonNull
559 public static Collection<X509Certificate> toCertificates(@NonNull byte[] bytes) {
560 if (bytes == null) {
561 throw new IllegalArgumentException("bytes == null");
562 }
563 try {
564 CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
565 return (Collection<X509Certificate>) certFactory.generateCertificates(
566 new ByteArrayInputStream(bytes));
567 } catch (CertificateException e) {
568 throw new AssertionError(e);
569 }
570 }
571
Brian Carlstromd7524722011-05-17 16:20:36 -0700572 /**
573 * @hide for reuse by CertInstaller and Settings.
574 * @see KeyChain#bind
575 */
576 public final static class KeyChainConnection implements Closeable {
577 private final Context context;
578 private final ServiceConnection serviceConnection;
579 private final IKeyChainService service;
580 private KeyChainConnection(Context context,
581 ServiceConnection serviceConnection,
582 IKeyChainService service) {
583 this.context = context;
584 this.serviceConnection = serviceConnection;
585 this.service = service;
586 }
587 @Override public void close() {
588 context.unbindService(serviceConnection);
589 }
590 public IKeyChainService getService() {
591 return service;
592 }
593 }
594
595 /**
596 * @hide for reuse by CertInstaller and Settings.
597 *
598 * Caller should call unbindService on the result when finished.
599 */
Robin Lee59e3baa2015-06-30 10:48:06 -0700600 @WorkerThread
Alex Klyubin54bb1592015-05-11 12:30:03 -0700601 public static KeyChainConnection bind(@NonNull Context context) throws InterruptedException {
Robin Lee306fe082014-06-19 14:04:24 +0000602 return bindAsUser(context, Process.myUserHandle());
603 }
604
605 /**
606 * @hide
607 */
Robin Lee59e3baa2015-06-30 10:48:06 -0700608 @WorkerThread
Alex Klyubin54bb1592015-05-11 12:30:03 -0700609 public static KeyChainConnection bindAsUser(@NonNull Context context, UserHandle user)
Robin Lee306fe082014-06-19 14:04:24 +0000610 throws InterruptedException {
Brian Carlstromd7524722011-05-17 16:20:36 -0700611 if (context == null) {
612 throw new NullPointerException("context == null");
613 }
614 ensureNotOnMainThread(context);
615 final BlockingQueue<IKeyChainService> q = new LinkedBlockingQueue<IKeyChainService>(1);
616 ServiceConnection keyChainServiceConnection = new ServiceConnection() {
Fred Quintanaab8b84a2011-07-13 14:55:39 -0700617 volatile boolean mConnectedAtLeastOnce = false;
Brian Carlstromd7524722011-05-17 16:20:36 -0700618 @Override public void onServiceConnected(ComponentName name, IBinder service) {
Fred Quintanaab8b84a2011-07-13 14:55:39 -0700619 if (!mConnectedAtLeastOnce) {
620 mConnectedAtLeastOnce = true;
621 try {
622 q.put(IKeyChainService.Stub.asInterface(service));
623 } catch (InterruptedException e) {
624 // will never happen, since the queue starts with one available slot
625 }
Brian Carlstromd7524722011-05-17 16:20:36 -0700626 }
627 }
628 @Override public void onServiceDisconnected(ComponentName name) {}
629 };
Maggie Benthallda51e682013-08-08 22:35:44 -0400630 Intent intent = new Intent(IKeyChainService.class.getName());
631 ComponentName comp = intent.resolveSystemService(context.getPackageManager(), 0);
632 intent.setComponent(comp);
Robin Lee21bcbc52016-02-29 18:55:35 +0000633 if (comp == null || !context.bindServiceAsUser(
634 intent, keyChainServiceConnection, Context.BIND_AUTO_CREATE, user)) {
Brian Carlstromd7524722011-05-17 16:20:36 -0700635 throw new AssertionError("could not bind to KeyChainService");
636 }
637 return new KeyChainConnection(context, keyChainServiceConnection, q.take());
638 }
639
Alex Klyubin54bb1592015-05-11 12:30:03 -0700640 private static void ensureNotOnMainThread(@NonNull Context context) {
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700641 Looper looper = Looper.myLooper();
Brian Carlstrom8e9929c2011-05-17 00:40:28 -0700642 if (looper != null && looper == context.getMainLooper()) {
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700643 throw new IllegalStateException(
644 "calling this from your main thread can lead to deadlock");
645 }
646 }
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700647}