blob: 5e59a64b23d43a1d4e0eb018678e0985c29efbc5 [file] [log] [blame]
Brian Carlstromb9a07c12011-04-11 09:03:51 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16package android.security;
17
Alex Klyubin54bb1592015-05-11 12:30:03 -070018import android.annotation.NonNull;
19import android.annotation.Nullable;
Robin Lee59e3baa2015-06-30 10:48:06 -070020import android.annotation.WorkerThread;
Brian Carlstromba1a6672011-05-24 21:54:37 -070021import android.app.Activity;
Brian Carlstrom67c30df2011-06-24 02:13:23 -070022import android.app.PendingIntent;
Robin Leeda236182016-08-12 12:46:28 +010023import android.app.Service;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070024import android.content.ComponentName;
25import android.content.Context;
26import android.content.Intent;
27import android.content.ServiceConnection;
Robin Lee39087b12015-05-05 15:57:17 +010028import android.net.Uri;
Jeff Sharkey0a17db12016-11-04 11:23:46 -060029import android.os.Binder;
Chad Brubaker721afae2016-07-08 11:06:09 -070030import android.os.Build;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070031import android.os.IBinder;
32import android.os.Looper;
Robin Lee306fe082014-06-19 14:04:24 +000033import android.os.Process;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070034import android.os.RemoteException;
Robin Lee306fe082014-06-19 14:04:24 +000035import android.os.UserHandle;
Alex Klyubin4a0ff7c2015-06-09 13:25:20 -070036import android.security.keystore.AndroidKeyStoreProvider;
Alex Klyubin3f8d4d82015-05-13 09:15:00 -070037import android.security.keystore.KeyProperties;
38
Brian Carlstromb9a07c12011-04-11 09:03:51 -070039import java.io.ByteArrayInputStream;
Brian Carlstromd7524722011-05-17 16:20:36 -070040import java.io.Closeable;
Brian Carlstrom93201f52011-06-09 15:05:35 -070041import java.security.Principal;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070042import java.security.PrivateKey;
Alex Klyubin4a0ff7c2015-06-09 13:25:20 -070043import java.security.UnrecoverableKeyException;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070044import java.security.cert.Certificate;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070045import java.security.cert.CertificateException;
46import java.security.cert.CertificateFactory;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070047import java.security.cert.X509Certificate;
Rubin Xub4365912016-03-23 12:13:22 +000048import java.util.ArrayList;
49import java.util.Collection;
Brian Carlstromdb93b782011-07-01 00:12:17 -070050import java.util.List;
Kenny Rootb91773b2013-09-05 13:03:16 -070051import java.util.Locale;
Brian Carlstrom8e9929c2011-05-17 00:40:28 -070052import java.util.concurrent.BlockingQueue;
53import java.util.concurrent.LinkedBlockingQueue;
Kenny Root5423e682011-11-14 08:43:13 -080054
Kenny Root12e75222013-04-23 22:34:24 -070055import com.android.org.conscrypt.TrustedCertificateStore;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070056
57/**
Brian Carlstrom93201f52011-06-09 15:05:35 -070058 * The {@code KeyChain} class provides access to private keys and
59 * their corresponding certificate chains in credential storage.
60 *
61 * <p>Applications accessing the {@code KeyChain} normally go through
62 * these steps:
63 *
64 * <ol>
65 *
66 * <li>Receive a callback from an {@link javax.net.ssl.X509KeyManager
67 * X509KeyManager} that a private key is requested.
68 *
69 * <li>Call {@link #choosePrivateKeyAlias
70 * choosePrivateKeyAlias} to allow the user to select from a
71 * list of currently available private keys and corresponding
72 * certificate chains. The chosen alias will be returned by the
73 * callback {@link KeyChainAliasCallback#alias}, or null if no private
74 * key is available or the user cancels the request.
75 *
76 * <li>Call {@link #getPrivateKey} and {@link #getCertificateChain} to
77 * retrieve the credentials to return to the corresponding {@link
78 * javax.net.ssl.X509KeyManager} callbacks.
79 *
80 * </ol>
81 *
82 * <p>An application may remember the value of a selected alias to
83 * avoid prompting the user with {@link #choosePrivateKeyAlias
84 * choosePrivateKeyAlias} on subsequent connections. If the alias is
85 * no longer valid, null will be returned on lookups using that value
Brian Carlstromca43c452011-06-29 18:53:17 -070086 *
87 * <p>An application can request the installation of private keys and
88 * certificates via the {@code Intent} provided by {@link
89 * #createInstallIntent}. Private keys installed via this {@code
90 * Intent} will be accessible via {@link #choosePrivateKeyAlias} while
91 * Certificate Authority (CA) certificates will be trusted by all
92 * applications through the default {@code X509TrustManager}.
Brian Carlstromb9a07c12011-04-11 09:03:51 -070093 */
Brian Carlstrom93201f52011-06-09 15:05:35 -070094// TODO reference intent for credential installation when public
Brian Carlstromb9a07c12011-04-11 09:03:51 -070095public final class KeyChain {
96
Brian Carlstromb9a07c12011-04-11 09:03:51 -070097 /**
98 * @hide Also used by KeyChainService implementation
99 */
100 public static final String ACCOUNT_TYPE = "com.android.keychain";
101
102 /**
Kenny Roota3659062014-03-17 16:21:53 -0700103 * Package name for KeyChain chooser.
104 */
105 private static final String KEYCHAIN_PACKAGE = "com.android.keychain";
106
107 /**
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700108 * Action to bring up the KeyChainActivity
109 */
110 private static final String ACTION_CHOOSER = "com.android.keychain.CHOOSER";
111
112 /**
Kenny Root1a88d832014-02-07 09:12:48 -0800113 * Package name for the Certificate Installer.
114 */
115 private static final String CERT_INSTALLER_PACKAGE = "com.android.certinstaller";
116
117 /**
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700118 * Extra for use with {@link #ACTION_CHOOSER}
Brian Carlstromba1a6672011-05-24 21:54:37 -0700119 * @hide Also used by KeyChainActivity implementation
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700120 */
Brian Carlstromba1a6672011-05-24 21:54:37 -0700121 public static final String EXTRA_RESPONSE = "response";
122
123 /**
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700124 * Extra for use with {@link #ACTION_CHOOSER}
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700125 * @hide Also used by KeyChainActivity implementation
126 */
Robin Lee39087b12015-05-05 15:57:17 +0100127 public static final String EXTRA_URI = "uri";
Robin Lee3798ed52015-02-03 17:55:31 +0000128
129 /**
130 * Extra for use with {@link #ACTION_CHOOSER}
131 * @hide Also used by KeyChainActivity implementation
132 */
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700133 public static final String EXTRA_ALIAS = "alias";
134
135 /**
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700136 * Extra for use with {@link #ACTION_CHOOSER}
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700137 * @hide Also used by KeyChainActivity implementation
138 */
139 public static final String EXTRA_SENDER = "sender";
140
141 /**
Selim Gurun93ba4fe2012-02-14 11:48:49 -0800142 * Action to bring up the CertInstaller.
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700143 */
144 private static final String ACTION_INSTALL = "android.credentials.INSTALL";
145
146 /**
147 * Optional extra to specify a {@code String} credential name on
148 * the {@code Intent} returned by {@link #createInstallIntent}.
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700149 */
150 // Compatible with old com.android.certinstaller.CredentialHelper.CERT_NAME_KEY
151 public static final String EXTRA_NAME = "name";
152
153 /**
154 * Optional extra to specify an X.509 certificate to install on
155 * the {@code Intent} returned by {@link #createInstallIntent}.
156 * The extra value should be a PEM or ASN.1 DER encoded {@code
157 * byte[]}. An {@link X509Certificate} can be converted to DER
158 * encoded bytes with {@link X509Certificate#getEncoded}.
159 *
160 * <p>{@link #EXTRA_NAME} may be used to provide a default alias
161 * name for the installed certificate.
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700162 */
163 // Compatible with old android.security.Credentials.CERTIFICATE
164 public static final String EXTRA_CERTIFICATE = "CERT";
165
166 /**
167 * Optional extra for use with the {@code Intent} returned by
168 * {@link #createInstallIntent} to specify a PKCS#12 key store to
169 * install. The extra value should be a {@code byte[]}. The bytes
170 * may come from an external source or be generated with {@link
Brian Carlstromca43c452011-06-29 18:53:17 -0700171 * java.security.KeyStore#store} on a "PKCS12" instance.
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700172 *
173 * <p>The user will be prompted for the password to load the key store.
174 *
175 * <p>The key store will be scanned for {@link
176 * java.security.KeyStore.PrivateKeyEntry} entries and both the
177 * private key and associated certificate chain will be installed.
178 *
179 * <p>{@link #EXTRA_NAME} may be used to provide a default alias
180 * name for the installed credentials.
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700181 */
182 // Compatible with old android.security.Credentials.PKCS12
183 public static final String EXTRA_PKCS12 = "PKCS12";
184
Selim Gurun93ba4fe2012-02-14 11:48:49 -0800185 /**
Selim Gurun93ba4fe2012-02-14 11:48:49 -0800186 * Broadcast Action: Indicates the trusted storage has changed. Sent when
187 * one of this happens:
188 *
189 * <ul>
190 * <li>a new CA is added,
191 * <li>an existing CA is removed or disabled,
192 * <li>a disabled CA is enabled,
193 * <li>trusted storage is reset (all user certs are cleared),
194 * <li>when permission to access a private key is changed.
195 * </ul>
Chad Brubaker4de59ef2016-05-02 13:17:31 -0700196 *
Chad Brubakerdbf01c12016-07-25 14:54:39 -0700197 * @deprecated Use {@link #ACTION_KEYCHAIN_CHANGED}, {@link #ACTION_TRUST_STORE_CHANGED} or
Chad Brubaker721afae2016-07-08 11:06:09 -0700198 * {@link #ACTION_KEY_ACCESS_CHANGED}. Apps that target a version higher than
199 * {@link Build.VERSION_CODES#N_MR1} will not receive this broadcast.
Selim Gurun93ba4fe2012-02-14 11:48:49 -0800200 */
201 public static final String ACTION_STORAGE_CHANGED = "android.security.STORAGE_CHANGED";
202
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700203 /**
Chad Brubaker4de59ef2016-05-02 13:17:31 -0700204 * Broadcast Action: Indicates the contents of the keychain has changed. Sent when a KeyChain
205 * entry is added, modified or removed.
206 */
207 public static final String ACTION_KEYCHAIN_CHANGED = "android.security.action.KEYCHAIN_CHANGED";
208
209 /**
210 * Broadcast Action: Indicates the contents of the trusted certificate store has changed. Sent
211 * when one the following occurs:
212 *
213 * <ul>
214 * <li>A pre-installed CA is disabled or re-enabled</li>
215 * <li>A CA is added or removed from the trust store</li>
216 * </ul>
217 */
218 public static final String ACTION_TRUST_STORE_CHANGED =
219 "android.security.action.TRUST_STORE_CHANGED";
220
221 /**
222 * Broadcast Action: Indicates that the access permissions for a private key have changed.
223 *
224 */
225 public static final String ACTION_KEY_ACCESS_CHANGED =
226 "android.security.action.KEY_ACCESS_CHANGED";
227
228 /**
229 * Used as a String extra field in {@link #ACTION_KEY_ACCESS_CHANGED} to supply the alias of
230 * the key.
231 */
232 public static final String EXTRA_KEY_ALIAS = "android.security.extra.KEY_ALIAS";
233
234 /**
235 * Used as a boolean extra field in {@link #ACTION_KEY_ACCESS_CHANGED} to supply if the key is
236 * accessible to the application.
237 */
238 public static final String EXTRA_KEY_ACCESSIBLE = "android.security.extra.KEY_ACCESSIBLE";
239
240 /**
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700241 * Returns an {@code Intent} that can be used for credential
242 * installation. The intent may be used without any extras, in
243 * which case the user will be able to install credentials from
244 * their own source.
245 *
246 * <p>Alternatively, {@link #EXTRA_CERTIFICATE} or {@link
247 * #EXTRA_PKCS12} maybe used to specify the bytes of an X.509
248 * certificate or a PKCS#12 key store for installation. These
Brian Carlstromca43c452011-06-29 18:53:17 -0700249 * extras may be combined with {@link #EXTRA_NAME} to provide a
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700250 * default alias name for credentials being installed.
251 *
252 * <p>When used with {@link Activity#startActivityForResult},
253 * {@link Activity#RESULT_OK} will be returned if a credential was
254 * successfully installed, otherwise {@link
255 * Activity#RESULT_CANCELED} will be returned.
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700256 */
Alex Klyubin54bb1592015-05-11 12:30:03 -0700257 @NonNull
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700258 public static Intent createInstallIntent() {
259 Intent intent = new Intent(ACTION_INSTALL);
Kenny Root1a88d832014-02-07 09:12:48 -0800260 intent.setClassName(CERT_INSTALLER_PACKAGE,
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700261 "com.android.certinstaller.CertInstallerMain");
262 return intent;
263 }
264
265 /**
Brian Carlstromba1a6672011-05-24 21:54:37 -0700266 * Launches an {@code Activity} for the user to select the alias
267 * for a private key and certificate pair for authentication. The
268 * selected alias or null will be returned via the
Brian Carlstrom93201f52011-06-09 15:05:35 -0700269 * KeyChainAliasCallback callback.
270 *
Robin Lee3798ed52015-02-03 17:55:31 +0000271 * <p>The device or profile owner can intercept this before the activity
272 * is shown, to pick a specific private key alias.
273 *
274 * <p>{@code keyTypes} and {@code issuers} may be used to
275 * highlight suggested choices to the user, although to cope with
276 * sometimes erroneous values provided by servers, the user may be
277 * able to override these suggestions.
278 *
279 * <p>{@code host} and {@code port} may be used to give the user
280 * more context about the server requesting the credentials.
281 *
282 * <p>{@code alias} allows the chooser to preselect an existing
283 * alias which will still be subject to user confirmation.
284 *
285 * @param activity The {@link Activity} context to use for
286 * launching the new sub-Activity to prompt the user to select
287 * a private key; used only to call startActivity(); must not
288 * be null.
289 * @param response Callback to invoke when the request completes;
290 * must not be null
291 * @param keyTypes The acceptable types of asymmetric keys such as
292 * "RSA" or "DSA", or a null array.
293 * @param issuers The acceptable certificate issuers for the
294 * certificate matching the private key, or null.
295 * @param host The host name of the server requesting the
296 * certificate, or null if unavailable.
297 * @param port The port number of the server requesting the
298 * certificate, or -1 if unavailable.
299 * @param alias The alias to preselect if available, or null if
300 * unavailable.
301 */
Alex Klyubin54bb1592015-05-11 12:30:03 -0700302 public static void choosePrivateKeyAlias(@NonNull Activity activity,
303 @NonNull KeyChainAliasCallback response,
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700304 @KeyProperties.KeyAlgorithmEnum String[] keyTypes, Principal[] issuers,
Alex Klyubin54bb1592015-05-11 12:30:03 -0700305 @Nullable String host, int port, @Nullable String alias) {
Robin Lee39087b12015-05-05 15:57:17 +0100306 Uri uri = null;
307 if (host != null) {
308 uri = new Uri.Builder()
309 .authority(host + (port != -1 ? ":" + port : ""))
310 .build();
311 }
312 choosePrivateKeyAlias(activity, response, keyTypes, issuers, uri, alias);
Robin Lee3798ed52015-02-03 17:55:31 +0000313 }
314
315 /**
316 * Launches an {@code Activity} for the user to select the alias
317 * for a private key and certificate pair for authentication. The
318 * selected alias or null will be returned via the
319 * KeyChainAliasCallback callback.
320 *
321 * <p>The device or profile owner can intercept this before the activity
322 * is shown, to pick a specific private key alias.</p>
323 *
Brian Carlstrom93201f52011-06-09 15:05:35 -0700324 * <p>{@code keyTypes} and {@code issuers} may be used to
325 * highlight suggested choices to the user, although to cope with
326 * sometimes erroneous values provided by servers, the user may be
327 * able to override these suggestions.
328 *
329 * <p>{@code host} and {@code port} may be used to give the user
330 * more context about the server requesting the credentials.
331 *
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700332 * <p>{@code alias} allows the chooser to preselect an existing
333 * alias which will still be subject to user confirmation.
334 *
Brian Carlstrom93201f52011-06-09 15:05:35 -0700335 * @param activity The {@link Activity} context to use for
336 * launching the new sub-Activity to prompt the user to select
337 * a private key; used only to call startActivity(); must not
338 * be null.
339 * @param response Callback to invoke when the request completes;
340 * must not be null
341 * @param keyTypes The acceptable types of asymmetric keys such as
Alex Klyubincd2329d2015-01-14 16:45:51 -0800342 * "EC" or "RSA", or a null array.
Brian Carlstrom93201f52011-06-09 15:05:35 -0700343 * @param issuers The acceptable certificate issuers for the
344 * certificate matching the private key, or null.
Robin Lee39087b12015-05-05 15:57:17 +0100345 * @param uri The full URI the server is requesting the certificate
Robin Lee3798ed52015-02-03 17:55:31 +0000346 * for, or null if unavailable.
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700347 * @param alias The alias to preselect if available, or null if
348 * unavailable.
Brian Carlstromba1a6672011-05-24 21:54:37 -0700349 */
Alex Klyubin54bb1592015-05-11 12:30:03 -0700350 public static void choosePrivateKeyAlias(@NonNull Activity activity,
351 @NonNull KeyChainAliasCallback response,
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700352 @KeyProperties.KeyAlgorithmEnum String[] keyTypes, Principal[] issuers,
Robin Lee39087b12015-05-05 15:57:17 +0100353 @Nullable Uri uri, @Nullable String alias) {
Brian Carlstrom93201f52011-06-09 15:05:35 -0700354 /*
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700355 * TODO currently keyTypes, issuers are unused. They are meant
356 * to follow the semantics and purpose of X509KeyManager
357 * method arguments.
Brian Carlstrom93201f52011-06-09 15:05:35 -0700358 *
359 * keyTypes would allow the list to be filtered and typically
360 * will be set correctly by the server. In practice today,
Alex Klyubincd2329d2015-01-14 16:45:51 -0800361 * most all users will want only RSA or EC, and usually
Brian Carlstrom93201f52011-06-09 15:05:35 -0700362 * only a small number of certs will be available.
363 *
364 * issuers is typically not useful. Some servers historically
365 * will send the entire list of public CAs known to the
366 * server. Others will send none. If this is used, if there
367 * are no matches after applying the constraint, it should be
368 * ignored.
Brian Carlstrom93201f52011-06-09 15:05:35 -0700369 */
Brian Carlstromba1a6672011-05-24 21:54:37 -0700370 if (activity == null) {
371 throw new NullPointerException("activity == null");
372 }
373 if (response == null) {
374 throw new NullPointerException("response == null");
375 }
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700376 Intent intent = new Intent(ACTION_CHOOSER);
Kenny Roota3659062014-03-17 16:21:53 -0700377 intent.setPackage(KEYCHAIN_PACKAGE);
Fred Quintanaab8b84a2011-07-13 14:55:39 -0700378 intent.putExtra(EXTRA_RESPONSE, new AliasResponse(response));
Robin Lee39087b12015-05-05 15:57:17 +0100379 intent.putExtra(EXTRA_URI, uri);
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700380 intent.putExtra(EXTRA_ALIAS, alias);
381 // the PendingIntent is used to get calling package name
382 intent.putExtra(EXTRA_SENDER, PendingIntent.getActivity(activity, 0, new Intent(), 0));
Brian Carlstromba1a6672011-05-24 21:54:37 -0700383 activity.startActivity(intent);
384 }
385
Brian Carlstrom93201f52011-06-09 15:05:35 -0700386 private static class AliasResponse extends IKeyChainAliasCallback.Stub {
Brian Carlstrom93201f52011-06-09 15:05:35 -0700387 private final KeyChainAliasCallback keyChainAliasResponse;
Fred Quintanaab8b84a2011-07-13 14:55:39 -0700388 private AliasResponse(KeyChainAliasCallback keyChainAliasResponse) {
Brian Carlstromba1a6672011-05-24 21:54:37 -0700389 this.keyChainAliasResponse = keyChainAliasResponse;
390 }
391 @Override public void alias(String alias) {
Fred Quintanaab8b84a2011-07-13 14:55:39 -0700392 keyChainAliasResponse.alias(alias);
Brian Carlstromba1a6672011-05-24 21:54:37 -0700393 }
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700394 }
395
396 /**
Brian Carlstromba1a6672011-05-24 21:54:37 -0700397 * Returns the {@code PrivateKey} for the requested alias, or null
Robin Lee3a435f02015-12-21 12:06:04 +0000398 * if there is no result.
Brian Carlstrom93201f52011-06-09 15:05:35 -0700399 *
Robin Lee59e3baa2015-06-30 10:48:06 -0700400 * <p> This method may block while waiting for a connection to another process, and must never
401 * be called from the main thread.
Robin Leeda236182016-08-12 12:46:28 +0100402 * <p> As {@link Activity} and {@link Service} contexts are short-lived and can be destroyed
403 * at any time from the main thread, it is safer to rely on a long-lived context such as one
404 * returned from {@link Context#getApplicationContext()}.
Robin Lee59e3baa2015-06-30 10:48:06 -0700405 *
406 * @param alias The alias of the desired private key, typically returned via
407 * {@link KeyChainAliasCallback#alias}.
Brian Carlstrom93201f52011-06-09 15:05:35 -0700408 * @throws KeyChainException if the alias was valid but there was some problem accessing it.
Robin Lee59e3baa2015-06-30 10:48:06 -0700409 * @throws IllegalStateException if called from the main thread.
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700410 */
Robin Lee59e3baa2015-06-30 10:48:06 -0700411 @Nullable @WorkerThread
Alex Klyubin54bb1592015-05-11 12:30:03 -0700412 public static PrivateKey getPrivateKey(@NonNull Context context, @NonNull String alias)
Brian Carlstrom93201f52011-06-09 15:05:35 -0700413 throws KeyChainException, InterruptedException {
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700414 if (alias == null) {
415 throw new NullPointerException("alias == null");
416 }
Robin Lee28d68b12016-07-22 16:32:32 +0100417
418 final String keyId;
419 try (KeyChainConnection keyChainConnection = bind(context.getApplicationContext())) {
420 keyId = keyChainConnection.getService().requestPrivateKey(alias);
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);
Robin Lee28d68b12016-07-22 16:32:32 +0100426 }
427
428 if (keyId == null) {
429 return null;
430 } else {
431 try {
432 return AndroidKeyStoreProvider.loadAndroidKeyStorePrivateKeyFromKeystore(
433 KeyStore.getInstance(), keyId, KeyStore.UID_SELF);
434 } catch (RuntimeException | UnrecoverableKeyException e) {
435 throw new KeyChainException(e);
436 }
Brian Carlstromba1a6672011-05-24 21:54:37 -0700437 }
438 }
439
440 /**
441 * Returns the {@code X509Certificate} chain for the requested
Rubin Xub4365912016-03-23 12:13:22 +0000442 * alias, or null if there is no result.
443 * <p>
444 * <strong>Note:</strong> If a certificate chain was explicitly specified when the alias was
445 * installed, this method will return that chain. If only the client certificate was specified
446 * at the installation time, this method will try to build a certificate chain using all
447 * available trust anchors (preinstalled and user-added).
Brian Carlstrom93201f52011-06-09 15:05:35 -0700448 *
Robin Lee59e3baa2015-06-30 10:48:06 -0700449 * <p> This method may block while waiting for a connection to another process, and must never
450 * be called from the main thread.
Robin Leeda236182016-08-12 12:46:28 +0100451 * <p> As {@link Activity} and {@link Service} contexts are short-lived and can be destroyed
452 * at any time from the main thread, it is safer to rely on a long-lived context such as one
453 * returned from {@link Context#getApplicationContext()}.
Robin Lee59e3baa2015-06-30 10:48:06 -0700454 *
Brian Carlstrom93201f52011-06-09 15:05:35 -0700455 * @param alias The alias of the desired certificate chain, typically
456 * returned via {@link KeyChainAliasCallback#alias}.
457 * @throws KeyChainException if the alias was valid but there was some problem accessing it.
Robin Lee59e3baa2015-06-30 10:48:06 -0700458 * @throws IllegalStateException if called from the main thread.
Brian Carlstromba1a6672011-05-24 21:54:37 -0700459 */
Robin Lee59e3baa2015-06-30 10:48:06 -0700460 @Nullable @WorkerThread
Alex Klyubin54bb1592015-05-11 12:30:03 -0700461 public static X509Certificate[] getCertificateChain(@NonNull Context context,
462 @NonNull String alias) throws KeyChainException, InterruptedException {
Brian Carlstromba1a6672011-05-24 21:54:37 -0700463 if (alias == null) {
464 throw new NullPointerException("alias == null");
465 }
Kenny Root0150e482013-02-13 15:22:50 -0800466
Robin Lee28d68b12016-07-22 16:32:32 +0100467 final byte[] certificateBytes;
468 final byte[] certChainBytes;
469 try (KeyChainConnection keyChainConnection = bind(context.getApplicationContext())) {
470 IKeyChainService keyChainService = keyChainConnection.getService();
471 certificateBytes = keyChainService.getCertificate(alias);
Kenny Root0150e482013-02-13 15:22:50 -0800472 if (certificateBytes == null) {
473 return null;
474 }
Robin Lee28d68b12016-07-22 16:32:32 +0100475 certChainBytes = keyChainService.getCaCertificates(alias);
476 } catch (RemoteException e) {
477 throw new KeyChainException(e);
478 } catch (RuntimeException e) {
479 // only certain RuntimeExceptions can be propagated across the IKeyChainService call
480 throw new KeyChainException(e);
481 }
482
483 try {
Rubin Xub4365912016-03-23 12:13:22 +0000484 X509Certificate leafCert = toCertificate(certificateBytes);
Rubin Xub4365912016-03-23 12:13:22 +0000485 // If the keypair is installed with a certificate chain by either
486 // DevicePolicyManager.installKeyPair or CertInstaller, return that chain.
487 if (certChainBytes != null && certChainBytes.length != 0) {
488 Collection<X509Certificate> chain = toCertificates(certChainBytes);
489 ArrayList<X509Certificate> fullChain = new ArrayList<>(chain.size() + 1);
490 fullChain.add(leafCert);
491 fullChain.addAll(chain);
492 return fullChain.toArray(new X509Certificate[fullChain.size()]);
493 } else {
494 // If there isn't a certificate chain, either due to a pre-existing keypair
495 // installed before N, or no chain is explicitly installed under the new logic,
496 // fall back to old behavior of constructing the chain from trusted credentials.
497 //
498 // This logic exists to maintain old behaviour for already installed keypair, at
499 // the cost of potentially returning extra certificate chain for new clients who
500 // explicitly installed only the client certificate without a chain. The latter
501 // case is actually no different from pre-N behaviour of getCertificateChain(),
502 // in that sense this change introduces no regression. Besides the returned chain
503 // is still valid so the consumer of the chain should have no problem verifying it.
504 TrustedCertificateStore store = new TrustedCertificateStore();
505 List<X509Certificate> chain = store.getCertificateChain(leafCert);
506 return chain.toArray(new X509Certificate[chain.size()]);
507 }
Robin Lee28d68b12016-07-22 16:32:32 +0100508 } catch (CertificateException | RuntimeException e) {
Kenny Rootcfba6a02013-05-06 15:00:58 -0700509 throw new KeyChainException(e);
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700510 }
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700511 }
512
Kenny Rootbf556ac2013-04-01 15:10:22 -0700513 /**
514 * Returns {@code true} if the current device's {@code KeyChain} supports a
515 * specific {@code PrivateKey} type indicated by {@code algorithm} (e.g.,
516 * "RSA").
517 */
Alex Klyubin4d5443f2015-05-06 15:43:52 -0700518 public static boolean isKeyAlgorithmSupported(
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700519 @NonNull @KeyProperties.KeyAlgorithmEnum String algorithm) {
Kenny Rootb91773b2013-09-05 13:03:16 -0700520 final String algUpper = algorithm.toUpperCase(Locale.US);
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700521 return KeyProperties.KEY_ALGORITHM_EC.equals(algUpper)
522 || KeyProperties.KEY_ALGORITHM_RSA.equals(algUpper);
Kenny Rootbf556ac2013-04-01 15:10:22 -0700523 }
524
525 /**
526 * Returns {@code true} if the current device's {@code KeyChain} binds any
527 * {@code PrivateKey} of the given {@code algorithm} to the device once
528 * imported or generated. This can be used to tell if there is special
529 * hardware support that can be used to bind keys to the device in a way
530 * that makes it non-exportable.
Alex Klyubin469cbf52015-06-04 12:36:27 -0700531 *
532 * @deprecated Whether the key is bound to the secure hardware is known only
533 * once the key has been imported. To find out, use:
534 * <pre>{@code
535 * PrivateKey key = ...; // private key from KeyChain
536 *
537 * KeyFactory keyFactory =
538 * KeyFactory.getInstance(key.getAlgorithm(), "AndroidKeyStore");
539 * KeyInfo keyInfo = keyFactory.getKeySpec(key, KeyInfo.class);
Neil Fuller71fbb812015-11-30 09:51:33 +0000540 * if (keyInfo.isInsideSecureHardware()) {
Alex Klyubin469cbf52015-06-04 12:36:27 -0700541 * // The key is bound to the secure hardware of this Android
Neil Fuller71fbb812015-11-30 09:51:33 +0000542 * }}</pre>
Kenny Rootbf556ac2013-04-01 15:10:22 -0700543 */
Alex Klyubin469cbf52015-06-04 12:36:27 -0700544 @Deprecated
Alex Klyubin4d5443f2015-05-06 15:43:52 -0700545 public static boolean isBoundKeyAlgorithm(
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700546 @NonNull @KeyProperties.KeyAlgorithmEnum String algorithm) {
Kenny Root5b7e90a2013-04-02 11:23:41 -0700547 if (!isKeyAlgorithmSupported(algorithm)) {
Kenny Rootbf556ac2013-04-01 15:10:22 -0700548 return false;
549 }
550
Kenny Rootb91773b2013-09-05 13:03:16 -0700551 return KeyStore.getInstance().isHardwareBacked(algorithm);
Kenny Rootbf556ac2013-04-01 15:10:22 -0700552 }
553
Zoltan Szatmary-Banf0ae1352014-08-18 10:48:33 +0100554 /** @hide */
Alex Klyubin54bb1592015-05-11 12:30:03 -0700555 @NonNull
556 public static X509Certificate toCertificate(@NonNull byte[] bytes) {
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700557 if (bytes == null) {
Brian Carlstrom8e9929c2011-05-17 00:40:28 -0700558 throw new IllegalArgumentException("bytes == null");
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700559 }
560 try {
561 CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
562 Certificate cert = certFactory.generateCertificate(new ByteArrayInputStream(bytes));
563 return (X509Certificate) cert;
564 } catch (CertificateException e) {
565 throw new AssertionError(e);
566 }
567 }
568
Rubin Xub4365912016-03-23 12:13:22 +0000569 /** @hide */
570 @NonNull
571 public static Collection<X509Certificate> toCertificates(@NonNull byte[] bytes) {
572 if (bytes == null) {
573 throw new IllegalArgumentException("bytes == null");
574 }
575 try {
576 CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
577 return (Collection<X509Certificate>) certFactory.generateCertificates(
578 new ByteArrayInputStream(bytes));
579 } catch (CertificateException e) {
580 throw new AssertionError(e);
581 }
582 }
583
Brian Carlstromd7524722011-05-17 16:20:36 -0700584 /**
585 * @hide for reuse by CertInstaller and Settings.
586 * @see KeyChain#bind
587 */
588 public final static class KeyChainConnection implements Closeable {
589 private final Context context;
590 private final ServiceConnection serviceConnection;
591 private final IKeyChainService service;
592 private KeyChainConnection(Context context,
593 ServiceConnection serviceConnection,
594 IKeyChainService service) {
595 this.context = context;
596 this.serviceConnection = serviceConnection;
597 this.service = service;
598 }
599 @Override public void close() {
600 context.unbindService(serviceConnection);
601 }
602 public IKeyChainService getService() {
603 return service;
604 }
605 }
606
607 /**
608 * @hide for reuse by CertInstaller and Settings.
609 *
610 * Caller should call unbindService on the result when finished.
611 */
Robin Lee59e3baa2015-06-30 10:48:06 -0700612 @WorkerThread
Alex Klyubin54bb1592015-05-11 12:30:03 -0700613 public static KeyChainConnection bind(@NonNull Context context) throws InterruptedException {
Robin Lee306fe082014-06-19 14:04:24 +0000614 return bindAsUser(context, Process.myUserHandle());
615 }
616
617 /**
618 * @hide
619 */
Robin Lee59e3baa2015-06-30 10:48:06 -0700620 @WorkerThread
Alex Klyubin54bb1592015-05-11 12:30:03 -0700621 public static KeyChainConnection bindAsUser(@NonNull Context context, UserHandle user)
Robin Lee306fe082014-06-19 14:04:24 +0000622 throws InterruptedException {
Brian Carlstromd7524722011-05-17 16:20:36 -0700623 if (context == null) {
624 throw new NullPointerException("context == null");
625 }
626 ensureNotOnMainThread(context);
627 final BlockingQueue<IKeyChainService> q = new LinkedBlockingQueue<IKeyChainService>(1);
628 ServiceConnection keyChainServiceConnection = new ServiceConnection() {
Fred Quintanaab8b84a2011-07-13 14:55:39 -0700629 volatile boolean mConnectedAtLeastOnce = false;
Brian Carlstromd7524722011-05-17 16:20:36 -0700630 @Override public void onServiceConnected(ComponentName name, IBinder service) {
Fred Quintanaab8b84a2011-07-13 14:55:39 -0700631 if (!mConnectedAtLeastOnce) {
632 mConnectedAtLeastOnce = true;
633 try {
Jeff Sharkey0a17db12016-11-04 11:23:46 -0600634 q.put(IKeyChainService.Stub.asInterface(Binder.allowBlocking(service)));
Fred Quintanaab8b84a2011-07-13 14:55:39 -0700635 } catch (InterruptedException e) {
636 // will never happen, since the queue starts with one available slot
637 }
Brian Carlstromd7524722011-05-17 16:20:36 -0700638 }
639 }
640 @Override public void onServiceDisconnected(ComponentName name) {}
641 };
Maggie Benthallda51e682013-08-08 22:35:44 -0400642 Intent intent = new Intent(IKeyChainService.class.getName());
643 ComponentName comp = intent.resolveSystemService(context.getPackageManager(), 0);
644 intent.setComponent(comp);
Robin Lee21bcbc52016-02-29 18:55:35 +0000645 if (comp == null || !context.bindServiceAsUser(
646 intent, keyChainServiceConnection, Context.BIND_AUTO_CREATE, user)) {
Brian Carlstromd7524722011-05-17 16:20:36 -0700647 throw new AssertionError("could not bind to KeyChainService");
648 }
649 return new KeyChainConnection(context, keyChainServiceConnection, q.take());
650 }
651
Alex Klyubin54bb1592015-05-11 12:30:03 -0700652 private static void ensureNotOnMainThread(@NonNull Context context) {
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700653 Looper looper = Looper.myLooper();
Brian Carlstrom8e9929c2011-05-17 00:40:28 -0700654 if (looper != null && looper == context.getMainLooper()) {
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700655 throw new IllegalStateException(
656 "calling this from your main thread can lead to deadlock");
657 }
658 }
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700659}