blob: 5c64566f79870a4b8426f9a6b18b2a64f5985e57 [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
Chad Brubaker8b651bf2017-03-23 09:26:09 -0700199 * {@link Build.VERSION_CODES#N_MR1} will only receive this broadcast if they register for it
200 * at runtime.
Selim Gurun93ba4fe2012-02-14 11:48:49 -0800201 */
202 public static final String ACTION_STORAGE_CHANGED = "android.security.STORAGE_CHANGED";
203
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700204 /**
Chad Brubaker4de59ef2016-05-02 13:17:31 -0700205 * Broadcast Action: Indicates the contents of the keychain has changed. Sent when a KeyChain
206 * entry is added, modified or removed.
207 */
208 public static final String ACTION_KEYCHAIN_CHANGED = "android.security.action.KEYCHAIN_CHANGED";
209
210 /**
211 * Broadcast Action: Indicates the contents of the trusted certificate store has changed. Sent
212 * when one the following occurs:
213 *
214 * <ul>
215 * <li>A pre-installed CA is disabled or re-enabled</li>
216 * <li>A CA is added or removed from the trust store</li>
217 * </ul>
218 */
219 public static final String ACTION_TRUST_STORE_CHANGED =
220 "android.security.action.TRUST_STORE_CHANGED";
221
222 /**
223 * Broadcast Action: Indicates that the access permissions for a private key have changed.
224 *
225 */
226 public static final String ACTION_KEY_ACCESS_CHANGED =
227 "android.security.action.KEY_ACCESS_CHANGED";
228
229 /**
230 * Used as a String extra field in {@link #ACTION_KEY_ACCESS_CHANGED} to supply the alias of
231 * the key.
232 */
233 public static final String EXTRA_KEY_ALIAS = "android.security.extra.KEY_ALIAS";
234
235 /**
236 * Used as a boolean extra field in {@link #ACTION_KEY_ACCESS_CHANGED} to supply if the key is
237 * accessible to the application.
238 */
239 public static final String EXTRA_KEY_ACCESSIBLE = "android.security.extra.KEY_ACCESSIBLE";
240
241 /**
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700242 * Returns an {@code Intent} that can be used for credential
243 * installation. The intent may be used without any extras, in
244 * which case the user will be able to install credentials from
245 * their own source.
246 *
247 * <p>Alternatively, {@link #EXTRA_CERTIFICATE} or {@link
248 * #EXTRA_PKCS12} maybe used to specify the bytes of an X.509
249 * certificate or a PKCS#12 key store for installation. These
Brian Carlstromca43c452011-06-29 18:53:17 -0700250 * extras may be combined with {@link #EXTRA_NAME} to provide a
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700251 * default alias name for credentials being installed.
252 *
253 * <p>When used with {@link Activity#startActivityForResult},
254 * {@link Activity#RESULT_OK} will be returned if a credential was
255 * successfully installed, otherwise {@link
256 * Activity#RESULT_CANCELED} will be returned.
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700257 */
Alex Klyubin54bb1592015-05-11 12:30:03 -0700258 @NonNull
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700259 public static Intent createInstallIntent() {
260 Intent intent = new Intent(ACTION_INSTALL);
Kenny Root1a88d832014-02-07 09:12:48 -0800261 intent.setClassName(CERT_INSTALLER_PACKAGE,
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700262 "com.android.certinstaller.CertInstallerMain");
263 return intent;
264 }
265
266 /**
Brian Carlstromba1a6672011-05-24 21:54:37 -0700267 * Launches an {@code Activity} for the user to select the alias
268 * for a private key and certificate pair for authentication. The
269 * selected alias or null will be returned via the
Brian Carlstrom93201f52011-06-09 15:05:35 -0700270 * KeyChainAliasCallback callback.
271 *
Robin Lee3798ed52015-02-03 17:55:31 +0000272 * <p>The device or profile owner can intercept this before the activity
273 * is shown, to pick a specific private key alias.
274 *
275 * <p>{@code keyTypes} and {@code issuers} may be used to
276 * highlight suggested choices to the user, although to cope with
277 * sometimes erroneous values provided by servers, the user may be
278 * able to override these suggestions.
279 *
280 * <p>{@code host} and {@code port} may be used to give the user
281 * more context about the server requesting the credentials.
282 *
283 * <p>{@code alias} allows the chooser to preselect an existing
284 * alias which will still be subject to user confirmation.
285 *
286 * @param activity The {@link Activity} context to use for
287 * launching the new sub-Activity to prompt the user to select
288 * a private key; used only to call startActivity(); must not
289 * be null.
290 * @param response Callback to invoke when the request completes;
291 * must not be null
292 * @param keyTypes The acceptable types of asymmetric keys such as
293 * "RSA" or "DSA", or a null array.
294 * @param issuers The acceptable certificate issuers for the
295 * certificate matching the private key, or null.
296 * @param host The host name of the server requesting the
297 * certificate, or null if unavailable.
298 * @param port The port number of the server requesting the
299 * certificate, or -1 if unavailable.
300 * @param alias The alias to preselect if available, or null if
301 * unavailable.
302 */
Alex Klyubin54bb1592015-05-11 12:30:03 -0700303 public static void choosePrivateKeyAlias(@NonNull Activity activity,
304 @NonNull KeyChainAliasCallback response,
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700305 @KeyProperties.KeyAlgorithmEnum String[] keyTypes, Principal[] issuers,
Alex Klyubin54bb1592015-05-11 12:30:03 -0700306 @Nullable String host, int port, @Nullable String alias) {
Robin Lee39087b12015-05-05 15:57:17 +0100307 Uri uri = null;
308 if (host != null) {
309 uri = new Uri.Builder()
310 .authority(host + (port != -1 ? ":" + port : ""))
311 .build();
312 }
313 choosePrivateKeyAlias(activity, response, keyTypes, issuers, uri, alias);
Robin Lee3798ed52015-02-03 17:55:31 +0000314 }
315
316 /**
317 * Launches an {@code Activity} for the user to select the alias
318 * for a private key and certificate pair for authentication. The
319 * selected alias or null will be returned via the
320 * KeyChainAliasCallback callback.
321 *
322 * <p>The device or profile owner can intercept this before the activity
323 * is shown, to pick a specific private key alias.</p>
324 *
Brian Carlstrom93201f52011-06-09 15:05:35 -0700325 * <p>{@code keyTypes} and {@code issuers} may be used to
326 * highlight suggested choices to the user, although to cope with
327 * sometimes erroneous values provided by servers, the user may be
328 * able to override these suggestions.
329 *
330 * <p>{@code host} and {@code port} may be used to give the user
331 * more context about the server requesting the credentials.
332 *
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700333 * <p>{@code alias} allows the chooser to preselect an existing
334 * alias which will still be subject to user confirmation.
335 *
Brian Carlstrom93201f52011-06-09 15:05:35 -0700336 * @param activity The {@link Activity} context to use for
337 * launching the new sub-Activity to prompt the user to select
338 * a private key; used only to call startActivity(); must not
339 * be null.
340 * @param response Callback to invoke when the request completes;
341 * must not be null
342 * @param keyTypes The acceptable types of asymmetric keys such as
Alex Klyubincd2329d2015-01-14 16:45:51 -0800343 * "EC" or "RSA", or a null array.
Brian Carlstrom93201f52011-06-09 15:05:35 -0700344 * @param issuers The acceptable certificate issuers for the
345 * certificate matching the private key, or null.
Robin Lee39087b12015-05-05 15:57:17 +0100346 * @param uri The full URI the server is requesting the certificate
Robin Lee3798ed52015-02-03 17:55:31 +0000347 * for, or null if unavailable.
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700348 * @param alias The alias to preselect if available, or null if
349 * unavailable.
Brian Carlstromba1a6672011-05-24 21:54:37 -0700350 */
Alex Klyubin54bb1592015-05-11 12:30:03 -0700351 public static void choosePrivateKeyAlias(@NonNull Activity activity,
352 @NonNull KeyChainAliasCallback response,
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700353 @KeyProperties.KeyAlgorithmEnum String[] keyTypes, Principal[] issuers,
Robin Lee39087b12015-05-05 15:57:17 +0100354 @Nullable Uri uri, @Nullable String alias) {
Brian Carlstrom93201f52011-06-09 15:05:35 -0700355 /*
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700356 * TODO currently keyTypes, issuers are unused. They are meant
357 * to follow the semantics and purpose of X509KeyManager
358 * method arguments.
Brian Carlstrom93201f52011-06-09 15:05:35 -0700359 *
360 * keyTypes would allow the list to be filtered and typically
361 * will be set correctly by the server. In practice today,
Alex Klyubincd2329d2015-01-14 16:45:51 -0800362 * most all users will want only RSA or EC, and usually
Brian Carlstrom93201f52011-06-09 15:05:35 -0700363 * only a small number of certs will be available.
364 *
365 * issuers is typically not useful. Some servers historically
366 * will send the entire list of public CAs known to the
367 * server. Others will send none. If this is used, if there
368 * are no matches after applying the constraint, it should be
369 * ignored.
Brian Carlstrom93201f52011-06-09 15:05:35 -0700370 */
Brian Carlstromba1a6672011-05-24 21:54:37 -0700371 if (activity == null) {
372 throw new NullPointerException("activity == null");
373 }
374 if (response == null) {
375 throw new NullPointerException("response == null");
376 }
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700377 Intent intent = new Intent(ACTION_CHOOSER);
Kenny Roota3659062014-03-17 16:21:53 -0700378 intent.setPackage(KEYCHAIN_PACKAGE);
Fred Quintanaab8b84a2011-07-13 14:55:39 -0700379 intent.putExtra(EXTRA_RESPONSE, new AliasResponse(response));
Robin Lee39087b12015-05-05 15:57:17 +0100380 intent.putExtra(EXTRA_URI, uri);
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700381 intent.putExtra(EXTRA_ALIAS, alias);
382 // the PendingIntent is used to get calling package name
383 intent.putExtra(EXTRA_SENDER, PendingIntent.getActivity(activity, 0, new Intent(), 0));
Brian Carlstromba1a6672011-05-24 21:54:37 -0700384 activity.startActivity(intent);
385 }
386
Brian Carlstrom93201f52011-06-09 15:05:35 -0700387 private static class AliasResponse extends IKeyChainAliasCallback.Stub {
Brian Carlstrom93201f52011-06-09 15:05:35 -0700388 private final KeyChainAliasCallback keyChainAliasResponse;
Fred Quintanaab8b84a2011-07-13 14:55:39 -0700389 private AliasResponse(KeyChainAliasCallback keyChainAliasResponse) {
Brian Carlstromba1a6672011-05-24 21:54:37 -0700390 this.keyChainAliasResponse = keyChainAliasResponse;
391 }
392 @Override public void alias(String alias) {
Fred Quintanaab8b84a2011-07-13 14:55:39 -0700393 keyChainAliasResponse.alias(alias);
Brian Carlstromba1a6672011-05-24 21:54:37 -0700394 }
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700395 }
396
397 /**
Brian Carlstromba1a6672011-05-24 21:54:37 -0700398 * Returns the {@code PrivateKey} for the requested alias, or null
Robin Lee3a435f02015-12-21 12:06:04 +0000399 * if there is no result.
Brian Carlstrom93201f52011-06-09 15:05:35 -0700400 *
Robin Lee59e3baa2015-06-30 10:48:06 -0700401 * <p> This method may block while waiting for a connection to another process, and must never
402 * be called from the main thread.
Robin Leeda236182016-08-12 12:46:28 +0100403 * <p> As {@link Activity} and {@link Service} contexts are short-lived and can be destroyed
404 * at any time from the main thread, it is safer to rely on a long-lived context such as one
405 * returned from {@link Context#getApplicationContext()}.
Robin Lee59e3baa2015-06-30 10:48:06 -0700406 *
407 * @param alias The alias of the desired private key, typically returned via
408 * {@link KeyChainAliasCallback#alias}.
Brian Carlstrom93201f52011-06-09 15:05:35 -0700409 * @throws KeyChainException if the alias was valid but there was some problem accessing it.
Robin Lee59e3baa2015-06-30 10:48:06 -0700410 * @throws IllegalStateException if called from the main thread.
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700411 */
Robin Lee59e3baa2015-06-30 10:48:06 -0700412 @Nullable @WorkerThread
Alex Klyubin54bb1592015-05-11 12:30:03 -0700413 public static PrivateKey getPrivateKey(@NonNull Context context, @NonNull String alias)
Brian Carlstrom93201f52011-06-09 15:05:35 -0700414 throws KeyChainException, InterruptedException {
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700415 if (alias == null) {
416 throw new NullPointerException("alias == null");
417 }
Shawn Willdendea66142016-11-16 06:01:06 -0700418 if (context == null) {
419 throw new NullPointerException("context == null");
420 }
Robin Lee28d68b12016-07-22 16:32:32 +0100421
422 final String keyId;
423 try (KeyChainConnection keyChainConnection = bind(context.getApplicationContext())) {
424 keyId = keyChainConnection.getService().requestPrivateKey(alias);
Brian Carlstrom93201f52011-06-09 15:05:35 -0700425 } catch (RemoteException e) {
426 throw new KeyChainException(e);
427 } catch (RuntimeException e) {
428 // only certain RuntimeExceptions can be propagated across the IKeyChainService call
429 throw new KeyChainException(e);
Robin Lee28d68b12016-07-22 16:32:32 +0100430 }
431
432 if (keyId == null) {
433 return null;
434 } else {
435 try {
436 return AndroidKeyStoreProvider.loadAndroidKeyStorePrivateKeyFromKeystore(
437 KeyStore.getInstance(), keyId, KeyStore.UID_SELF);
438 } catch (RuntimeException | UnrecoverableKeyException e) {
439 throw new KeyChainException(e);
440 }
Brian Carlstromba1a6672011-05-24 21:54:37 -0700441 }
442 }
443
444 /**
445 * Returns the {@code X509Certificate} chain for the requested
Rubin Xub4365912016-03-23 12:13:22 +0000446 * alias, or null if there is no result.
447 * <p>
448 * <strong>Note:</strong> If a certificate chain was explicitly specified when the alias was
449 * installed, this method will return that chain. If only the client certificate was specified
450 * at the installation time, this method will try to build a certificate chain using all
451 * available trust anchors (preinstalled and user-added).
Brian Carlstrom93201f52011-06-09 15:05:35 -0700452 *
Robin Lee59e3baa2015-06-30 10:48:06 -0700453 * <p> This method may block while waiting for a connection to another process, and must never
454 * be called from the main thread.
Robin Leeda236182016-08-12 12:46:28 +0100455 * <p> As {@link Activity} and {@link Service} contexts are short-lived and can be destroyed
456 * at any time from the main thread, it is safer to rely on a long-lived context such as one
457 * returned from {@link Context#getApplicationContext()}.
Robin Lee59e3baa2015-06-30 10:48:06 -0700458 *
Brian Carlstrom93201f52011-06-09 15:05:35 -0700459 * @param alias The alias of the desired certificate chain, typically
460 * returned via {@link KeyChainAliasCallback#alias}.
461 * @throws KeyChainException if the alias was valid but there was some problem accessing it.
Robin Lee59e3baa2015-06-30 10:48:06 -0700462 * @throws IllegalStateException if called from the main thread.
Brian Carlstromba1a6672011-05-24 21:54:37 -0700463 */
Robin Lee59e3baa2015-06-30 10:48:06 -0700464 @Nullable @WorkerThread
Alex Klyubin54bb1592015-05-11 12:30:03 -0700465 public static X509Certificate[] getCertificateChain(@NonNull Context context,
466 @NonNull String alias) throws KeyChainException, InterruptedException {
Brian Carlstromba1a6672011-05-24 21:54:37 -0700467 if (alias == null) {
468 throw new NullPointerException("alias == null");
469 }
Kenny Root0150e482013-02-13 15:22:50 -0800470
Robin Lee28d68b12016-07-22 16:32:32 +0100471 final byte[] certificateBytes;
472 final byte[] certChainBytes;
473 try (KeyChainConnection keyChainConnection = bind(context.getApplicationContext())) {
474 IKeyChainService keyChainService = keyChainConnection.getService();
475 certificateBytes = keyChainService.getCertificate(alias);
Kenny Root0150e482013-02-13 15:22:50 -0800476 if (certificateBytes == null) {
477 return null;
478 }
Robin Lee28d68b12016-07-22 16:32:32 +0100479 certChainBytes = keyChainService.getCaCertificates(alias);
480 } catch (RemoteException e) {
481 throw new KeyChainException(e);
482 } catch (RuntimeException e) {
483 // only certain RuntimeExceptions can be propagated across the IKeyChainService call
484 throw new KeyChainException(e);
485 }
486
487 try {
Rubin Xub4365912016-03-23 12:13:22 +0000488 X509Certificate leafCert = toCertificate(certificateBytes);
Rubin Xub4365912016-03-23 12:13:22 +0000489 // If the keypair is installed with a certificate chain by either
490 // DevicePolicyManager.installKeyPair or CertInstaller, return that chain.
491 if (certChainBytes != null && certChainBytes.length != 0) {
492 Collection<X509Certificate> chain = toCertificates(certChainBytes);
493 ArrayList<X509Certificate> fullChain = new ArrayList<>(chain.size() + 1);
494 fullChain.add(leafCert);
495 fullChain.addAll(chain);
496 return fullChain.toArray(new X509Certificate[fullChain.size()]);
497 } else {
498 // If there isn't a certificate chain, either due to a pre-existing keypair
499 // installed before N, or no chain is explicitly installed under the new logic,
500 // fall back to old behavior of constructing the chain from trusted credentials.
501 //
502 // This logic exists to maintain old behaviour for already installed keypair, at
503 // the cost of potentially returning extra certificate chain for new clients who
504 // explicitly installed only the client certificate without a chain. The latter
505 // case is actually no different from pre-N behaviour of getCertificateChain(),
506 // in that sense this change introduces no regression. Besides the returned chain
507 // is still valid so the consumer of the chain should have no problem verifying it.
508 TrustedCertificateStore store = new TrustedCertificateStore();
509 List<X509Certificate> chain = store.getCertificateChain(leafCert);
510 return chain.toArray(new X509Certificate[chain.size()]);
511 }
Robin Lee28d68b12016-07-22 16:32:32 +0100512 } catch (CertificateException | RuntimeException e) {
Kenny Rootcfba6a02013-05-06 15:00:58 -0700513 throw new KeyChainException(e);
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700514 }
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700515 }
516
Kenny Rootbf556ac2013-04-01 15:10:22 -0700517 /**
518 * Returns {@code true} if the current device's {@code KeyChain} supports a
519 * specific {@code PrivateKey} type indicated by {@code algorithm} (e.g.,
520 * "RSA").
521 */
Alex Klyubin4d5443f2015-05-06 15:43:52 -0700522 public static boolean isKeyAlgorithmSupported(
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700523 @NonNull @KeyProperties.KeyAlgorithmEnum String algorithm) {
Kenny Rootb91773b2013-09-05 13:03:16 -0700524 final String algUpper = algorithm.toUpperCase(Locale.US);
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700525 return KeyProperties.KEY_ALGORITHM_EC.equals(algUpper)
526 || KeyProperties.KEY_ALGORITHM_RSA.equals(algUpper);
Kenny Rootbf556ac2013-04-01 15:10:22 -0700527 }
528
529 /**
530 * Returns {@code true} if the current device's {@code KeyChain} binds any
531 * {@code PrivateKey} of the given {@code algorithm} to the device once
532 * imported or generated. This can be used to tell if there is special
533 * hardware support that can be used to bind keys to the device in a way
534 * that makes it non-exportable.
Alex Klyubin469cbf52015-06-04 12:36:27 -0700535 *
536 * @deprecated Whether the key is bound to the secure hardware is known only
537 * once the key has been imported. To find out, use:
538 * <pre>{@code
539 * PrivateKey key = ...; // private key from KeyChain
540 *
541 * KeyFactory keyFactory =
542 * KeyFactory.getInstance(key.getAlgorithm(), "AndroidKeyStore");
543 * KeyInfo keyInfo = keyFactory.getKeySpec(key, KeyInfo.class);
Neil Fuller71fbb812015-11-30 09:51:33 +0000544 * if (keyInfo.isInsideSecureHardware()) {
Alex Klyubin469cbf52015-06-04 12:36:27 -0700545 * // The key is bound to the secure hardware of this Android
Neil Fuller71fbb812015-11-30 09:51:33 +0000546 * }}</pre>
Kenny Rootbf556ac2013-04-01 15:10:22 -0700547 */
Alex Klyubin469cbf52015-06-04 12:36:27 -0700548 @Deprecated
Alex Klyubin4d5443f2015-05-06 15:43:52 -0700549 public static boolean isBoundKeyAlgorithm(
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700550 @NonNull @KeyProperties.KeyAlgorithmEnum String algorithm) {
Kenny Root5b7e90a2013-04-02 11:23:41 -0700551 if (!isKeyAlgorithmSupported(algorithm)) {
Kenny Rootbf556ac2013-04-01 15:10:22 -0700552 return false;
553 }
554
Kenny Rootb91773b2013-09-05 13:03:16 -0700555 return KeyStore.getInstance().isHardwareBacked(algorithm);
Kenny Rootbf556ac2013-04-01 15:10:22 -0700556 }
557
Zoltan Szatmary-Banf0ae1352014-08-18 10:48:33 +0100558 /** @hide */
Alex Klyubin54bb1592015-05-11 12:30:03 -0700559 @NonNull
560 public static X509Certificate toCertificate(@NonNull byte[] bytes) {
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700561 if (bytes == null) {
Brian Carlstrom8e9929c2011-05-17 00:40:28 -0700562 throw new IllegalArgumentException("bytes == null");
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700563 }
564 try {
565 CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
566 Certificate cert = certFactory.generateCertificate(new ByteArrayInputStream(bytes));
567 return (X509Certificate) cert;
568 } catch (CertificateException e) {
569 throw new AssertionError(e);
570 }
571 }
572
Rubin Xub4365912016-03-23 12:13:22 +0000573 /** @hide */
574 @NonNull
575 public static Collection<X509Certificate> toCertificates(@NonNull byte[] bytes) {
576 if (bytes == null) {
577 throw new IllegalArgumentException("bytes == null");
578 }
579 try {
580 CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
581 return (Collection<X509Certificate>) certFactory.generateCertificates(
582 new ByteArrayInputStream(bytes));
583 } catch (CertificateException e) {
584 throw new AssertionError(e);
585 }
586 }
587
Brian Carlstromd7524722011-05-17 16:20:36 -0700588 /**
589 * @hide for reuse by CertInstaller and Settings.
590 * @see KeyChain#bind
591 */
Robin Lee7f5c91c2017-02-08 21:27:02 +0000592 public static class KeyChainConnection implements Closeable {
Brian Carlstromd7524722011-05-17 16:20:36 -0700593 private final Context context;
594 private final ServiceConnection serviceConnection;
595 private final IKeyChainService service;
596 private KeyChainConnection(Context context,
597 ServiceConnection serviceConnection,
598 IKeyChainService service) {
599 this.context = context;
600 this.serviceConnection = serviceConnection;
601 this.service = service;
602 }
603 @Override public void close() {
604 context.unbindService(serviceConnection);
605 }
606 public IKeyChainService getService() {
607 return service;
608 }
609 }
610
611 /**
612 * @hide for reuse by CertInstaller and Settings.
613 *
614 * Caller should call unbindService on the result when finished.
615 */
Robin Lee59e3baa2015-06-30 10:48:06 -0700616 @WorkerThread
Alex Klyubin54bb1592015-05-11 12:30:03 -0700617 public static KeyChainConnection bind(@NonNull Context context) throws InterruptedException {
Robin Lee306fe082014-06-19 14:04:24 +0000618 return bindAsUser(context, Process.myUserHandle());
619 }
620
621 /**
622 * @hide
623 */
Robin Lee59e3baa2015-06-30 10:48:06 -0700624 @WorkerThread
Alex Klyubin54bb1592015-05-11 12:30:03 -0700625 public static KeyChainConnection bindAsUser(@NonNull Context context, UserHandle user)
Robin Lee306fe082014-06-19 14:04:24 +0000626 throws InterruptedException {
Brian Carlstromd7524722011-05-17 16:20:36 -0700627 if (context == null) {
628 throw new NullPointerException("context == null");
629 }
630 ensureNotOnMainThread(context);
631 final BlockingQueue<IKeyChainService> q = new LinkedBlockingQueue<IKeyChainService>(1);
632 ServiceConnection keyChainServiceConnection = new ServiceConnection() {
Fred Quintanaab8b84a2011-07-13 14:55:39 -0700633 volatile boolean mConnectedAtLeastOnce = false;
Brian Carlstromd7524722011-05-17 16:20:36 -0700634 @Override public void onServiceConnected(ComponentName name, IBinder service) {
Fred Quintanaab8b84a2011-07-13 14:55:39 -0700635 if (!mConnectedAtLeastOnce) {
636 mConnectedAtLeastOnce = true;
637 try {
Jeff Sharkey0a17db12016-11-04 11:23:46 -0600638 q.put(IKeyChainService.Stub.asInterface(Binder.allowBlocking(service)));
Fred Quintanaab8b84a2011-07-13 14:55:39 -0700639 } catch (InterruptedException e) {
640 // will never happen, since the queue starts with one available slot
641 }
Brian Carlstromd7524722011-05-17 16:20:36 -0700642 }
643 }
644 @Override public void onServiceDisconnected(ComponentName name) {}
645 };
Maggie Benthallda51e682013-08-08 22:35:44 -0400646 Intent intent = new Intent(IKeyChainService.class.getName());
647 ComponentName comp = intent.resolveSystemService(context.getPackageManager(), 0);
648 intent.setComponent(comp);
Robin Lee21bcbc52016-02-29 18:55:35 +0000649 if (comp == null || !context.bindServiceAsUser(
650 intent, keyChainServiceConnection, Context.BIND_AUTO_CREATE, user)) {
Brian Carlstromd7524722011-05-17 16:20:36 -0700651 throw new AssertionError("could not bind to KeyChainService");
652 }
653 return new KeyChainConnection(context, keyChainServiceConnection, q.take());
654 }
655
Alex Klyubin54bb1592015-05-11 12:30:03 -0700656 private static void ensureNotOnMainThread(@NonNull Context context) {
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700657 Looper looper = Looper.myLooper();
Brian Carlstrom8e9929c2011-05-17 00:40:28 -0700658 if (looper != null && looper == context.getMainLooper()) {
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700659 throw new IllegalStateException(
660 "calling this from your main thread can lead to deadlock");
661 }
662 }
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700663}