blob: ea804d0abea3bd92c89c05efda9a89d7156e57d3 [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;
Jeff Sharkey0f3f60b2017-04-24 18:06:20 -060020import android.annotation.SdkConstant;
Robin Lee59e3baa2015-06-30 10:48:06 -070021import android.annotation.WorkerThread;
Jeff Sharkey0f3f60b2017-04-24 18:06:20 -060022import android.annotation.SdkConstant.SdkConstantType;
Brian Carlstromba1a6672011-05-24 21:54:37 -070023import android.app.Activity;
Brian Carlstrom67c30df2011-06-24 02:13:23 -070024import android.app.PendingIntent;
Robin Leeda236182016-08-12 12:46:28 +010025import android.app.Service;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070026import android.content.ComponentName;
27import android.content.Context;
28import android.content.Intent;
29import android.content.ServiceConnection;
Robin Lee39087b12015-05-05 15:57:17 +010030import android.net.Uri;
Jeff Sharkey0a17db12016-11-04 11:23:46 -060031import android.os.Binder;
Chad Brubaker721afae2016-07-08 11:06:09 -070032import android.os.Build;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070033import android.os.IBinder;
34import android.os.Looper;
Robin Lee306fe082014-06-19 14:04:24 +000035import android.os.Process;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070036import android.os.RemoteException;
Robin Lee306fe082014-06-19 14:04:24 +000037import android.os.UserHandle;
Alex Klyubin4a0ff7c2015-06-09 13:25:20 -070038import android.security.keystore.AndroidKeyStoreProvider;
Alex Klyubin3f8d4d82015-05-13 09:15:00 -070039import android.security.keystore.KeyProperties;
40
Brian Carlstromb9a07c12011-04-11 09:03:51 -070041import java.io.ByteArrayInputStream;
Brian Carlstromd7524722011-05-17 16:20:36 -070042import java.io.Closeable;
Brian Carlstrom93201f52011-06-09 15:05:35 -070043import java.security.Principal;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070044import java.security.PrivateKey;
Alex Klyubin4a0ff7c2015-06-09 13:25:20 -070045import java.security.UnrecoverableKeyException;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070046import java.security.cert.Certificate;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070047import java.security.cert.CertificateException;
48import java.security.cert.CertificateFactory;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070049import java.security.cert.X509Certificate;
Rubin Xub4365912016-03-23 12:13:22 +000050import java.util.ArrayList;
51import java.util.Collection;
Brian Carlstromdb93b782011-07-01 00:12:17 -070052import java.util.List;
Kenny Rootb91773b2013-09-05 13:03:16 -070053import java.util.Locale;
Brian Carlstrom8e9929c2011-05-17 00:40:28 -070054import java.util.concurrent.BlockingQueue;
55import java.util.concurrent.LinkedBlockingQueue;
Kenny Root5423e682011-11-14 08:43:13 -080056
Kenny Root12e75222013-04-23 22:34:24 -070057import com.android.org.conscrypt.TrustedCertificateStore;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070058
59/**
Brian Carlstrom93201f52011-06-09 15:05:35 -070060 * The {@code KeyChain} class provides access to private keys and
61 * their corresponding certificate chains in credential storage.
62 *
63 * <p>Applications accessing the {@code KeyChain} normally go through
64 * these steps:
65 *
66 * <ol>
67 *
68 * <li>Receive a callback from an {@link javax.net.ssl.X509KeyManager
69 * X509KeyManager} that a private key is requested.
70 *
71 * <li>Call {@link #choosePrivateKeyAlias
72 * choosePrivateKeyAlias} to allow the user to select from a
73 * list of currently available private keys and corresponding
74 * certificate chains. The chosen alias will be returned by the
75 * callback {@link KeyChainAliasCallback#alias}, or null if no private
76 * key is available or the user cancels the request.
77 *
78 * <li>Call {@link #getPrivateKey} and {@link #getCertificateChain} to
79 * retrieve the credentials to return to the corresponding {@link
80 * javax.net.ssl.X509KeyManager} callbacks.
81 *
82 * </ol>
83 *
84 * <p>An application may remember the value of a selected alias to
85 * avoid prompting the user with {@link #choosePrivateKeyAlias
86 * choosePrivateKeyAlias} on subsequent connections. If the alias is
87 * no longer valid, null will be returned on lookups using that value
Brian Carlstromca43c452011-06-29 18:53:17 -070088 *
89 * <p>An application can request the installation of private keys and
90 * certificates via the {@code Intent} provided by {@link
91 * #createInstallIntent}. Private keys installed via this {@code
92 * Intent} will be accessible via {@link #choosePrivateKeyAlias} while
93 * Certificate Authority (CA) certificates will be trusted by all
94 * applications through the default {@code X509TrustManager}.
Brian Carlstromb9a07c12011-04-11 09:03:51 -070095 */
Brian Carlstrom93201f52011-06-09 15:05:35 -070096// TODO reference intent for credential installation when public
Brian Carlstromb9a07c12011-04-11 09:03:51 -070097public final class KeyChain {
98
Brian Carlstromb9a07c12011-04-11 09:03:51 -070099 /**
100 * @hide Also used by KeyChainService implementation
101 */
102 public static final String ACCOUNT_TYPE = "com.android.keychain";
103
104 /**
Kenny Roota3659062014-03-17 16:21:53 -0700105 * Package name for KeyChain chooser.
106 */
107 private static final String KEYCHAIN_PACKAGE = "com.android.keychain";
108
109 /**
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700110 * Action to bring up the KeyChainActivity
111 */
112 private static final String ACTION_CHOOSER = "com.android.keychain.CHOOSER";
113
114 /**
Kenny Root1a88d832014-02-07 09:12:48 -0800115 * Package name for the Certificate Installer.
116 */
117 private static final String CERT_INSTALLER_PACKAGE = "com.android.certinstaller";
118
119 /**
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700120 * Extra for use with {@link #ACTION_CHOOSER}
Brian Carlstromba1a6672011-05-24 21:54:37 -0700121 * @hide Also used by KeyChainActivity implementation
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700122 */
Brian Carlstromba1a6672011-05-24 21:54:37 -0700123 public static final String EXTRA_RESPONSE = "response";
124
125 /**
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700126 * Extra for use with {@link #ACTION_CHOOSER}
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700127 * @hide Also used by KeyChainActivity implementation
128 */
Robin Lee39087b12015-05-05 15:57:17 +0100129 public static final String EXTRA_URI = "uri";
Robin Lee3798ed52015-02-03 17:55:31 +0000130
131 /**
132 * Extra for use with {@link #ACTION_CHOOSER}
133 * @hide Also used by KeyChainActivity implementation
134 */
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700135 public static final String EXTRA_ALIAS = "alias";
136
137 /**
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700138 * Extra for use with {@link #ACTION_CHOOSER}
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700139 * @hide Also used by KeyChainActivity implementation
140 */
141 public static final String EXTRA_SENDER = "sender";
142
143 /**
Selim Gurun93ba4fe2012-02-14 11:48:49 -0800144 * Action to bring up the CertInstaller.
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700145 */
146 private static final String ACTION_INSTALL = "android.credentials.INSTALL";
147
148 /**
149 * Optional extra to specify a {@code String} credential name on
150 * the {@code Intent} returned by {@link #createInstallIntent}.
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700151 */
152 // Compatible with old com.android.certinstaller.CredentialHelper.CERT_NAME_KEY
153 public static final String EXTRA_NAME = "name";
154
155 /**
156 * Optional extra to specify an X.509 certificate to install on
157 * the {@code Intent} returned by {@link #createInstallIntent}.
158 * The extra value should be a PEM or ASN.1 DER encoded {@code
159 * byte[]}. An {@link X509Certificate} can be converted to DER
160 * encoded bytes with {@link X509Certificate#getEncoded}.
161 *
162 * <p>{@link #EXTRA_NAME} may be used to provide a default alias
163 * name for the installed certificate.
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700164 */
165 // Compatible with old android.security.Credentials.CERTIFICATE
166 public static final String EXTRA_CERTIFICATE = "CERT";
167
168 /**
169 * Optional extra for use with the {@code Intent} returned by
170 * {@link #createInstallIntent} to specify a PKCS#12 key store to
171 * install. The extra value should be a {@code byte[]}. The bytes
172 * may come from an external source or be generated with {@link
Brian Carlstromca43c452011-06-29 18:53:17 -0700173 * java.security.KeyStore#store} on a "PKCS12" instance.
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700174 *
175 * <p>The user will be prompted for the password to load the key store.
176 *
177 * <p>The key store will be scanned for {@link
178 * java.security.KeyStore.PrivateKeyEntry} entries and both the
179 * private key and associated certificate chain will be installed.
180 *
181 * <p>{@link #EXTRA_NAME} may be used to provide a default alias
182 * name for the installed credentials.
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700183 */
184 // Compatible with old android.security.Credentials.PKCS12
185 public static final String EXTRA_PKCS12 = "PKCS12";
186
Selim Gurun93ba4fe2012-02-14 11:48:49 -0800187 /**
Selim Gurun93ba4fe2012-02-14 11:48:49 -0800188 * Broadcast Action: Indicates the trusted storage has changed. Sent when
189 * one of this happens:
190 *
191 * <ul>
192 * <li>a new CA is added,
193 * <li>an existing CA is removed or disabled,
194 * <li>a disabled CA is enabled,
195 * <li>trusted storage is reset (all user certs are cleared),
196 * <li>when permission to access a private key is changed.
197 * </ul>
Chad Brubaker4de59ef2016-05-02 13:17:31 -0700198 *
Chad Brubakerdbf01c12016-07-25 14:54:39 -0700199 * @deprecated Use {@link #ACTION_KEYCHAIN_CHANGED}, {@link #ACTION_TRUST_STORE_CHANGED} or
Chad Brubaker721afae2016-07-08 11:06:09 -0700200 * {@link #ACTION_KEY_ACCESS_CHANGED}. Apps that target a version higher than
Chad Brubaker8b651bf2017-03-23 09:26:09 -0700201 * {@link Build.VERSION_CODES#N_MR1} will only receive this broadcast if they register for it
202 * at runtime.
Selim Gurun93ba4fe2012-02-14 11:48:49 -0800203 */
Jeff Sharkey0f3f60b2017-04-24 18:06:20 -0600204 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Selim Gurun93ba4fe2012-02-14 11:48:49 -0800205 public static final String ACTION_STORAGE_CHANGED = "android.security.STORAGE_CHANGED";
206
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700207 /**
Chad Brubaker4de59ef2016-05-02 13:17:31 -0700208 * Broadcast Action: Indicates the contents of the keychain has changed. Sent when a KeyChain
209 * entry is added, modified or removed.
210 */
Jeff Sharkey0f3f60b2017-04-24 18:06:20 -0600211 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Chad Brubaker4de59ef2016-05-02 13:17:31 -0700212 public static final String ACTION_KEYCHAIN_CHANGED = "android.security.action.KEYCHAIN_CHANGED";
213
214 /**
215 * Broadcast Action: Indicates the contents of the trusted certificate store has changed. Sent
216 * when one the following occurs:
217 *
218 * <ul>
219 * <li>A pre-installed CA is disabled or re-enabled</li>
220 * <li>A CA is added or removed from the trust store</li>
221 * </ul>
222 */
Jeff Sharkey0f3f60b2017-04-24 18:06:20 -0600223 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Chad Brubaker4de59ef2016-05-02 13:17:31 -0700224 public static final String ACTION_TRUST_STORE_CHANGED =
225 "android.security.action.TRUST_STORE_CHANGED";
226
227 /**
228 * Broadcast Action: Indicates that the access permissions for a private key have changed.
229 *
230 */
Jeff Sharkey0f3f60b2017-04-24 18:06:20 -0600231 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Chad Brubaker4de59ef2016-05-02 13:17:31 -0700232 public static final String ACTION_KEY_ACCESS_CHANGED =
233 "android.security.action.KEY_ACCESS_CHANGED";
234
235 /**
236 * Used as a String extra field in {@link #ACTION_KEY_ACCESS_CHANGED} to supply the alias of
237 * the key.
238 */
239 public static final String EXTRA_KEY_ALIAS = "android.security.extra.KEY_ALIAS";
240
241 /**
242 * Used as a boolean extra field in {@link #ACTION_KEY_ACCESS_CHANGED} to supply if the key is
243 * accessible to the application.
244 */
245 public static final String EXTRA_KEY_ACCESSIBLE = "android.security.extra.KEY_ACCESSIBLE";
246
247 /**
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700248 * Returns an {@code Intent} that can be used for credential
249 * installation. The intent may be used without any extras, in
250 * which case the user will be able to install credentials from
251 * their own source.
252 *
253 * <p>Alternatively, {@link #EXTRA_CERTIFICATE} or {@link
254 * #EXTRA_PKCS12} maybe used to specify the bytes of an X.509
255 * certificate or a PKCS#12 key store for installation. These
Brian Carlstromca43c452011-06-29 18:53:17 -0700256 * extras may be combined with {@link #EXTRA_NAME} to provide a
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700257 * default alias name for credentials being installed.
258 *
259 * <p>When used with {@link Activity#startActivityForResult},
260 * {@link Activity#RESULT_OK} will be returned if a credential was
261 * successfully installed, otherwise {@link
262 * Activity#RESULT_CANCELED} will be returned.
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700263 */
Alex Klyubin54bb1592015-05-11 12:30:03 -0700264 @NonNull
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700265 public static Intent createInstallIntent() {
266 Intent intent = new Intent(ACTION_INSTALL);
Kenny Root1a88d832014-02-07 09:12:48 -0800267 intent.setClassName(CERT_INSTALLER_PACKAGE,
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700268 "com.android.certinstaller.CertInstallerMain");
269 return intent;
270 }
271
272 /**
Brian Carlstromba1a6672011-05-24 21:54:37 -0700273 * Launches an {@code Activity} for the user to select the alias
274 * for a private key and certificate pair for authentication. The
275 * selected alias or null will be returned via the
Brian Carlstrom93201f52011-06-09 15:05:35 -0700276 * KeyChainAliasCallback callback.
277 *
Robin Lee3798ed52015-02-03 17:55:31 +0000278 * <p>The device or profile owner can intercept this before the activity
279 * is shown, to pick a specific private key alias.
280 *
281 * <p>{@code keyTypes} and {@code issuers} may be used to
282 * highlight suggested choices to the user, although to cope with
283 * sometimes erroneous values provided by servers, the user may be
284 * able to override these suggestions.
285 *
286 * <p>{@code host} and {@code port} may be used to give the user
287 * more context about the server requesting the credentials.
288 *
289 * <p>{@code alias} allows the chooser to preselect an existing
290 * alias which will still be subject to user confirmation.
291 *
292 * @param activity The {@link Activity} context to use for
293 * launching the new sub-Activity to prompt the user to select
294 * a private key; used only to call startActivity(); must not
295 * be null.
296 * @param response Callback to invoke when the request completes;
297 * must not be null
298 * @param keyTypes The acceptable types of asymmetric keys such as
299 * "RSA" or "DSA", or a null array.
300 * @param issuers The acceptable certificate issuers for the
301 * certificate matching the private key, or null.
302 * @param host The host name of the server requesting the
303 * certificate, or null if unavailable.
304 * @param port The port number of the server requesting the
305 * certificate, or -1 if unavailable.
306 * @param alias The alias to preselect if available, or null if
307 * unavailable.
308 */
Alex Klyubin54bb1592015-05-11 12:30:03 -0700309 public static void choosePrivateKeyAlias(@NonNull Activity activity,
310 @NonNull KeyChainAliasCallback response,
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700311 @KeyProperties.KeyAlgorithmEnum String[] keyTypes, Principal[] issuers,
Alex Klyubin54bb1592015-05-11 12:30:03 -0700312 @Nullable String host, int port, @Nullable String alias) {
Robin Lee39087b12015-05-05 15:57:17 +0100313 Uri uri = null;
314 if (host != null) {
315 uri = new Uri.Builder()
316 .authority(host + (port != -1 ? ":" + port : ""))
317 .build();
318 }
319 choosePrivateKeyAlias(activity, response, keyTypes, issuers, uri, alias);
Robin Lee3798ed52015-02-03 17:55:31 +0000320 }
321
322 /**
323 * Launches an {@code Activity} for the user to select the alias
324 * for a private key and certificate pair for authentication. The
325 * selected alias or null will be returned via the
326 * KeyChainAliasCallback callback.
327 *
328 * <p>The device or profile owner can intercept this before the activity
329 * is shown, to pick a specific private key alias.</p>
330 *
Brian Carlstrom93201f52011-06-09 15:05:35 -0700331 * <p>{@code keyTypes} and {@code issuers} may be used to
332 * highlight suggested choices to the user, although to cope with
333 * sometimes erroneous values provided by servers, the user may be
334 * able to override these suggestions.
335 *
336 * <p>{@code host} and {@code port} may be used to give the user
337 * more context about the server requesting the credentials.
338 *
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700339 * <p>{@code alias} allows the chooser to preselect an existing
340 * alias which will still be subject to user confirmation.
341 *
Brian Carlstrom93201f52011-06-09 15:05:35 -0700342 * @param activity The {@link Activity} context to use for
343 * launching the new sub-Activity to prompt the user to select
344 * a private key; used only to call startActivity(); must not
345 * be null.
346 * @param response Callback to invoke when the request completes;
347 * must not be null
348 * @param keyTypes The acceptable types of asymmetric keys such as
Alex Klyubincd2329d2015-01-14 16:45:51 -0800349 * "EC" or "RSA", or a null array.
Brian Carlstrom93201f52011-06-09 15:05:35 -0700350 * @param issuers The acceptable certificate issuers for the
351 * certificate matching the private key, or null.
Robin Lee39087b12015-05-05 15:57:17 +0100352 * @param uri The full URI the server is requesting the certificate
Robin Lee3798ed52015-02-03 17:55:31 +0000353 * for, or null if unavailable.
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700354 * @param alias The alias to preselect if available, or null if
355 * unavailable.
Brian Carlstromba1a6672011-05-24 21:54:37 -0700356 */
Alex Klyubin54bb1592015-05-11 12:30:03 -0700357 public static void choosePrivateKeyAlias(@NonNull Activity activity,
358 @NonNull KeyChainAliasCallback response,
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700359 @KeyProperties.KeyAlgorithmEnum String[] keyTypes, Principal[] issuers,
Robin Lee39087b12015-05-05 15:57:17 +0100360 @Nullable Uri uri, @Nullable String alias) {
Brian Carlstrom93201f52011-06-09 15:05:35 -0700361 /*
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700362 * TODO currently keyTypes, issuers are unused. They are meant
363 * to follow the semantics and purpose of X509KeyManager
364 * method arguments.
Brian Carlstrom93201f52011-06-09 15:05:35 -0700365 *
366 * keyTypes would allow the list to be filtered and typically
367 * will be set correctly by the server. In practice today,
Alex Klyubincd2329d2015-01-14 16:45:51 -0800368 * most all users will want only RSA or EC, and usually
Brian Carlstrom93201f52011-06-09 15:05:35 -0700369 * only a small number of certs will be available.
370 *
371 * issuers is typically not useful. Some servers historically
372 * will send the entire list of public CAs known to the
373 * server. Others will send none. If this is used, if there
374 * are no matches after applying the constraint, it should be
375 * ignored.
Brian Carlstrom93201f52011-06-09 15:05:35 -0700376 */
Brian Carlstromba1a6672011-05-24 21:54:37 -0700377 if (activity == null) {
378 throw new NullPointerException("activity == null");
379 }
380 if (response == null) {
381 throw new NullPointerException("response == null");
382 }
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700383 Intent intent = new Intent(ACTION_CHOOSER);
Kenny Roota3659062014-03-17 16:21:53 -0700384 intent.setPackage(KEYCHAIN_PACKAGE);
Fred Quintanaab8b84a2011-07-13 14:55:39 -0700385 intent.putExtra(EXTRA_RESPONSE, new AliasResponse(response));
Robin Lee39087b12015-05-05 15:57:17 +0100386 intent.putExtra(EXTRA_URI, uri);
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700387 intent.putExtra(EXTRA_ALIAS, alias);
388 // the PendingIntent is used to get calling package name
389 intent.putExtra(EXTRA_SENDER, PendingIntent.getActivity(activity, 0, new Intent(), 0));
Brian Carlstromba1a6672011-05-24 21:54:37 -0700390 activity.startActivity(intent);
391 }
392
Brian Carlstrom93201f52011-06-09 15:05:35 -0700393 private static class AliasResponse extends IKeyChainAliasCallback.Stub {
Brian Carlstrom93201f52011-06-09 15:05:35 -0700394 private final KeyChainAliasCallback keyChainAliasResponse;
Fred Quintanaab8b84a2011-07-13 14:55:39 -0700395 private AliasResponse(KeyChainAliasCallback keyChainAliasResponse) {
Brian Carlstromba1a6672011-05-24 21:54:37 -0700396 this.keyChainAliasResponse = keyChainAliasResponse;
397 }
398 @Override public void alias(String alias) {
Fred Quintanaab8b84a2011-07-13 14:55:39 -0700399 keyChainAliasResponse.alias(alias);
Brian Carlstromba1a6672011-05-24 21:54:37 -0700400 }
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700401 }
402
403 /**
Brian Carlstromba1a6672011-05-24 21:54:37 -0700404 * Returns the {@code PrivateKey} for the requested alias, or null
Robin Lee3a435f02015-12-21 12:06:04 +0000405 * if there is no result.
Brian Carlstrom93201f52011-06-09 15:05:35 -0700406 *
Robin Lee59e3baa2015-06-30 10:48:06 -0700407 * <p> This method may block while waiting for a connection to another process, and must never
408 * be called from the main thread.
Robin Leeda236182016-08-12 12:46:28 +0100409 * <p> As {@link Activity} and {@link Service} contexts are short-lived and can be destroyed
410 * at any time from the main thread, it is safer to rely on a long-lived context such as one
411 * returned from {@link Context#getApplicationContext()}.
Robin Lee59e3baa2015-06-30 10:48:06 -0700412 *
413 * @param alias The alias of the desired private key, typically returned via
414 * {@link KeyChainAliasCallback#alias}.
Brian Carlstrom93201f52011-06-09 15:05:35 -0700415 * @throws KeyChainException if the alias was valid but there was some problem accessing it.
Robin Lee59e3baa2015-06-30 10:48:06 -0700416 * @throws IllegalStateException if called from the main thread.
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700417 */
Robin Lee59e3baa2015-06-30 10:48:06 -0700418 @Nullable @WorkerThread
Alex Klyubin54bb1592015-05-11 12:30:03 -0700419 public static PrivateKey getPrivateKey(@NonNull Context context, @NonNull String alias)
Brian Carlstrom93201f52011-06-09 15:05:35 -0700420 throws KeyChainException, InterruptedException {
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700421 if (alias == null) {
422 throw new NullPointerException("alias == null");
423 }
Shawn Willdendea66142016-11-16 06:01:06 -0700424 if (context == null) {
425 throw new NullPointerException("context == null");
426 }
Robin Lee28d68b12016-07-22 16:32:32 +0100427
428 final String keyId;
429 try (KeyChainConnection keyChainConnection = bind(context.getApplicationContext())) {
430 keyId = keyChainConnection.getService().requestPrivateKey(alias);
Brian Carlstrom93201f52011-06-09 15:05:35 -0700431 } catch (RemoteException e) {
432 throw new KeyChainException(e);
433 } catch (RuntimeException e) {
434 // only certain RuntimeExceptions can be propagated across the IKeyChainService call
435 throw new KeyChainException(e);
Robin Lee28d68b12016-07-22 16:32:32 +0100436 }
437
438 if (keyId == null) {
439 return null;
440 } else {
441 try {
442 return AndroidKeyStoreProvider.loadAndroidKeyStorePrivateKeyFromKeystore(
443 KeyStore.getInstance(), keyId, KeyStore.UID_SELF);
444 } catch (RuntimeException | UnrecoverableKeyException e) {
445 throw new KeyChainException(e);
446 }
Brian Carlstromba1a6672011-05-24 21:54:37 -0700447 }
448 }
449
450 /**
451 * Returns the {@code X509Certificate} chain for the requested
Rubin Xub4365912016-03-23 12:13:22 +0000452 * alias, or null if there is no result.
453 * <p>
454 * <strong>Note:</strong> If a certificate chain was explicitly specified when the alias was
455 * installed, this method will return that chain. If only the client certificate was specified
456 * at the installation time, this method will try to build a certificate chain using all
457 * available trust anchors (preinstalled and user-added).
Brian Carlstrom93201f52011-06-09 15:05:35 -0700458 *
Robin Lee59e3baa2015-06-30 10:48:06 -0700459 * <p> This method may block while waiting for a connection to another process, and must never
460 * be called from the main thread.
Robin Leeda236182016-08-12 12:46:28 +0100461 * <p> As {@link Activity} and {@link Service} contexts are short-lived and can be destroyed
462 * at any time from the main thread, it is safer to rely on a long-lived context such as one
463 * returned from {@link Context#getApplicationContext()}.
Robin Lee59e3baa2015-06-30 10:48:06 -0700464 *
Brian Carlstrom93201f52011-06-09 15:05:35 -0700465 * @param alias The alias of the desired certificate chain, typically
466 * returned via {@link KeyChainAliasCallback#alias}.
467 * @throws KeyChainException if the alias was valid but there was some problem accessing it.
Robin Lee59e3baa2015-06-30 10:48:06 -0700468 * @throws IllegalStateException if called from the main thread.
Brian Carlstromba1a6672011-05-24 21:54:37 -0700469 */
Robin Lee59e3baa2015-06-30 10:48:06 -0700470 @Nullable @WorkerThread
Alex Klyubin54bb1592015-05-11 12:30:03 -0700471 public static X509Certificate[] getCertificateChain(@NonNull Context context,
472 @NonNull String alias) throws KeyChainException, InterruptedException {
Brian Carlstromba1a6672011-05-24 21:54:37 -0700473 if (alias == null) {
474 throw new NullPointerException("alias == null");
475 }
Kenny Root0150e482013-02-13 15:22:50 -0800476
Robin Lee28d68b12016-07-22 16:32:32 +0100477 final byte[] certificateBytes;
478 final byte[] certChainBytes;
479 try (KeyChainConnection keyChainConnection = bind(context.getApplicationContext())) {
480 IKeyChainService keyChainService = keyChainConnection.getService();
481 certificateBytes = keyChainService.getCertificate(alias);
Kenny Root0150e482013-02-13 15:22:50 -0800482 if (certificateBytes == null) {
483 return null;
484 }
Robin Lee28d68b12016-07-22 16:32:32 +0100485 certChainBytes = keyChainService.getCaCertificates(alias);
486 } catch (RemoteException e) {
487 throw new KeyChainException(e);
488 } catch (RuntimeException e) {
489 // only certain RuntimeExceptions can be propagated across the IKeyChainService call
490 throw new KeyChainException(e);
491 }
492
493 try {
Rubin Xub4365912016-03-23 12:13:22 +0000494 X509Certificate leafCert = toCertificate(certificateBytes);
Rubin Xub4365912016-03-23 12:13:22 +0000495 // If the keypair is installed with a certificate chain by either
496 // DevicePolicyManager.installKeyPair or CertInstaller, return that chain.
497 if (certChainBytes != null && certChainBytes.length != 0) {
498 Collection<X509Certificate> chain = toCertificates(certChainBytes);
499 ArrayList<X509Certificate> fullChain = new ArrayList<>(chain.size() + 1);
500 fullChain.add(leafCert);
501 fullChain.addAll(chain);
502 return fullChain.toArray(new X509Certificate[fullChain.size()]);
503 } else {
504 // If there isn't a certificate chain, either due to a pre-existing keypair
505 // installed before N, or no chain is explicitly installed under the new logic,
506 // fall back to old behavior of constructing the chain from trusted credentials.
507 //
508 // This logic exists to maintain old behaviour for already installed keypair, at
509 // the cost of potentially returning extra certificate chain for new clients who
510 // explicitly installed only the client certificate without a chain. The latter
511 // case is actually no different from pre-N behaviour of getCertificateChain(),
512 // in that sense this change introduces no regression. Besides the returned chain
513 // is still valid so the consumer of the chain should have no problem verifying it.
514 TrustedCertificateStore store = new TrustedCertificateStore();
515 List<X509Certificate> chain = store.getCertificateChain(leafCert);
516 return chain.toArray(new X509Certificate[chain.size()]);
517 }
Robin Lee28d68b12016-07-22 16:32:32 +0100518 } catch (CertificateException | RuntimeException e) {
Kenny Rootcfba6a02013-05-06 15:00:58 -0700519 throw new KeyChainException(e);
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700520 }
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700521 }
522
Kenny Rootbf556ac2013-04-01 15:10:22 -0700523 /**
524 * Returns {@code true} if the current device's {@code KeyChain} supports a
525 * specific {@code PrivateKey} type indicated by {@code algorithm} (e.g.,
526 * "RSA").
527 */
Alex Klyubin4d5443f2015-05-06 15:43:52 -0700528 public static boolean isKeyAlgorithmSupported(
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700529 @NonNull @KeyProperties.KeyAlgorithmEnum String algorithm) {
Kenny Rootb91773b2013-09-05 13:03:16 -0700530 final String algUpper = algorithm.toUpperCase(Locale.US);
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700531 return KeyProperties.KEY_ALGORITHM_EC.equals(algUpper)
532 || KeyProperties.KEY_ALGORITHM_RSA.equals(algUpper);
Kenny Rootbf556ac2013-04-01 15:10:22 -0700533 }
534
535 /**
536 * Returns {@code true} if the current device's {@code KeyChain} binds any
537 * {@code PrivateKey} of the given {@code algorithm} to the device once
538 * imported or generated. This can be used to tell if there is special
539 * hardware support that can be used to bind keys to the device in a way
540 * that makes it non-exportable.
Alex Klyubin469cbf52015-06-04 12:36:27 -0700541 *
542 * @deprecated Whether the key is bound to the secure hardware is known only
543 * once the key has been imported. To find out, use:
544 * <pre>{@code
545 * PrivateKey key = ...; // private key from KeyChain
546 *
547 * KeyFactory keyFactory =
548 * KeyFactory.getInstance(key.getAlgorithm(), "AndroidKeyStore");
549 * KeyInfo keyInfo = keyFactory.getKeySpec(key, KeyInfo.class);
Neil Fuller71fbb812015-11-30 09:51:33 +0000550 * if (keyInfo.isInsideSecureHardware()) {
Alex Klyubin469cbf52015-06-04 12:36:27 -0700551 * // The key is bound to the secure hardware of this Android
Neil Fuller71fbb812015-11-30 09:51:33 +0000552 * }}</pre>
Kenny Rootbf556ac2013-04-01 15:10:22 -0700553 */
Alex Klyubin469cbf52015-06-04 12:36:27 -0700554 @Deprecated
Alex Klyubin4d5443f2015-05-06 15:43:52 -0700555 public static boolean isBoundKeyAlgorithm(
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700556 @NonNull @KeyProperties.KeyAlgorithmEnum String algorithm) {
Kenny Root5b7e90a2013-04-02 11:23:41 -0700557 if (!isKeyAlgorithmSupported(algorithm)) {
Kenny Rootbf556ac2013-04-01 15:10:22 -0700558 return false;
559 }
560
Kenny Rootb91773b2013-09-05 13:03:16 -0700561 return KeyStore.getInstance().isHardwareBacked(algorithm);
Kenny Rootbf556ac2013-04-01 15:10:22 -0700562 }
563
Zoltan Szatmary-Banf0ae1352014-08-18 10:48:33 +0100564 /** @hide */
Alex Klyubin54bb1592015-05-11 12:30:03 -0700565 @NonNull
566 public static X509Certificate toCertificate(@NonNull byte[] bytes) {
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700567 if (bytes == null) {
Brian Carlstrom8e9929c2011-05-17 00:40:28 -0700568 throw new IllegalArgumentException("bytes == null");
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700569 }
570 try {
571 CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
572 Certificate cert = certFactory.generateCertificate(new ByteArrayInputStream(bytes));
573 return (X509Certificate) cert;
574 } catch (CertificateException e) {
575 throw new AssertionError(e);
576 }
577 }
578
Rubin Xub4365912016-03-23 12:13:22 +0000579 /** @hide */
580 @NonNull
581 public static Collection<X509Certificate> toCertificates(@NonNull byte[] bytes) {
582 if (bytes == null) {
583 throw new IllegalArgumentException("bytes == null");
584 }
585 try {
586 CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
587 return (Collection<X509Certificate>) certFactory.generateCertificates(
588 new ByteArrayInputStream(bytes));
589 } catch (CertificateException e) {
590 throw new AssertionError(e);
591 }
592 }
593
Brian Carlstromd7524722011-05-17 16:20:36 -0700594 /**
595 * @hide for reuse by CertInstaller and Settings.
596 * @see KeyChain#bind
597 */
Robin Lee7f5c91c2017-02-08 21:27:02 +0000598 public static class KeyChainConnection implements Closeable {
Brian Carlstromd7524722011-05-17 16:20:36 -0700599 private final Context context;
600 private final ServiceConnection serviceConnection;
601 private final IKeyChainService service;
602 private KeyChainConnection(Context context,
603 ServiceConnection serviceConnection,
604 IKeyChainService service) {
605 this.context = context;
606 this.serviceConnection = serviceConnection;
607 this.service = service;
608 }
609 @Override public void close() {
610 context.unbindService(serviceConnection);
611 }
612 public IKeyChainService getService() {
613 return service;
614 }
615 }
616
617 /**
618 * @hide for reuse by CertInstaller and Settings.
619 *
620 * Caller should call unbindService on the result when finished.
621 */
Robin Lee59e3baa2015-06-30 10:48:06 -0700622 @WorkerThread
Alex Klyubin54bb1592015-05-11 12:30:03 -0700623 public static KeyChainConnection bind(@NonNull Context context) throws InterruptedException {
Robin Lee306fe082014-06-19 14:04:24 +0000624 return bindAsUser(context, Process.myUserHandle());
625 }
626
627 /**
628 * @hide
629 */
Robin Lee59e3baa2015-06-30 10:48:06 -0700630 @WorkerThread
Alex Klyubin54bb1592015-05-11 12:30:03 -0700631 public static KeyChainConnection bindAsUser(@NonNull Context context, UserHandle user)
Robin Lee306fe082014-06-19 14:04:24 +0000632 throws InterruptedException {
Brian Carlstromd7524722011-05-17 16:20:36 -0700633 if (context == null) {
634 throw new NullPointerException("context == null");
635 }
636 ensureNotOnMainThread(context);
637 final BlockingQueue<IKeyChainService> q = new LinkedBlockingQueue<IKeyChainService>(1);
638 ServiceConnection keyChainServiceConnection = new ServiceConnection() {
Fred Quintanaab8b84a2011-07-13 14:55:39 -0700639 volatile boolean mConnectedAtLeastOnce = false;
Brian Carlstromd7524722011-05-17 16:20:36 -0700640 @Override public void onServiceConnected(ComponentName name, IBinder service) {
Fred Quintanaab8b84a2011-07-13 14:55:39 -0700641 if (!mConnectedAtLeastOnce) {
642 mConnectedAtLeastOnce = true;
643 try {
Jeff Sharkey0a17db12016-11-04 11:23:46 -0600644 q.put(IKeyChainService.Stub.asInterface(Binder.allowBlocking(service)));
Fred Quintanaab8b84a2011-07-13 14:55:39 -0700645 } catch (InterruptedException e) {
646 // will never happen, since the queue starts with one available slot
647 }
Brian Carlstromd7524722011-05-17 16:20:36 -0700648 }
649 }
650 @Override public void onServiceDisconnected(ComponentName name) {}
651 };
Maggie Benthallda51e682013-08-08 22:35:44 -0400652 Intent intent = new Intent(IKeyChainService.class.getName());
653 ComponentName comp = intent.resolveSystemService(context.getPackageManager(), 0);
654 intent.setComponent(comp);
Robin Lee21bcbc52016-02-29 18:55:35 +0000655 if (comp == null || !context.bindServiceAsUser(
656 intent, keyChainServiceConnection, Context.BIND_AUTO_CREATE, user)) {
Brian Carlstromd7524722011-05-17 16:20:36 -0700657 throw new AssertionError("could not bind to KeyChainService");
658 }
659 return new KeyChainConnection(context, keyChainServiceConnection, q.take());
660 }
661
Alex Klyubin54bb1592015-05-11 12:30:03 -0700662 private static void ensureNotOnMainThread(@NonNull Context context) {
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700663 Looper looper = Looper.myLooper();
Brian Carlstrom8e9929c2011-05-17 00:40:28 -0700664 if (looper != null && looper == context.getMainLooper()) {
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700665 throw new IllegalStateException(
666 "calling this from your main thread can lead to deadlock");
667 }
668 }
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700669}