blob: 4fc789249c5c23cf6830a3a1e77392ee78054c1a [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;
Chad Brubaker721afae2016-07-08 11:06:09 -070029import android.os.Build;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070030import android.os.IBinder;
31import android.os.Looper;
Robin Lee306fe082014-06-19 14:04:24 +000032import android.os.Process;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070033import android.os.RemoteException;
Robin Lee306fe082014-06-19 14:04:24 +000034import android.os.UserHandle;
Alex Klyubin4a0ff7c2015-06-09 13:25:20 -070035import android.security.keystore.AndroidKeyStoreProvider;
Alex Klyubin3f8d4d82015-05-13 09:15:00 -070036import android.security.keystore.KeyProperties;
37
Brian Carlstromb9a07c12011-04-11 09:03:51 -070038import java.io.ByteArrayInputStream;
Brian Carlstromd7524722011-05-17 16:20:36 -070039import java.io.Closeable;
Brian Carlstrom93201f52011-06-09 15:05:35 -070040import java.security.Principal;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070041import java.security.PrivateKey;
Alex Klyubin4a0ff7c2015-06-09 13:25:20 -070042import java.security.UnrecoverableKeyException;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070043import java.security.cert.Certificate;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070044import java.security.cert.CertificateException;
45import java.security.cert.CertificateFactory;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070046import java.security.cert.X509Certificate;
Rubin Xub4365912016-03-23 12:13:22 +000047import java.util.ArrayList;
48import java.util.Collection;
Brian Carlstromdb93b782011-07-01 00:12:17 -070049import java.util.List;
Kenny Rootb91773b2013-09-05 13:03:16 -070050import java.util.Locale;
Brian Carlstrom8e9929c2011-05-17 00:40:28 -070051import java.util.concurrent.BlockingQueue;
52import java.util.concurrent.LinkedBlockingQueue;
Kenny Root5423e682011-11-14 08:43:13 -080053
Kenny Root12e75222013-04-23 22:34:24 -070054import com.android.org.conscrypt.TrustedCertificateStore;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070055
56/**
Brian Carlstrom93201f52011-06-09 15:05:35 -070057 * The {@code KeyChain} class provides access to private keys and
58 * their corresponding certificate chains in credential storage.
59 *
60 * <p>Applications accessing the {@code KeyChain} normally go through
61 * these steps:
62 *
63 * <ol>
64 *
65 * <li>Receive a callback from an {@link javax.net.ssl.X509KeyManager
66 * X509KeyManager} that a private key is requested.
67 *
68 * <li>Call {@link #choosePrivateKeyAlias
69 * choosePrivateKeyAlias} to allow the user to select from a
70 * list of currently available private keys and corresponding
71 * certificate chains. The chosen alias will be returned by the
72 * callback {@link KeyChainAliasCallback#alias}, or null if no private
73 * key is available or the user cancels the request.
74 *
75 * <li>Call {@link #getPrivateKey} and {@link #getCertificateChain} to
76 * retrieve the credentials to return to the corresponding {@link
77 * javax.net.ssl.X509KeyManager} callbacks.
78 *
79 * </ol>
80 *
81 * <p>An application may remember the value of a selected alias to
82 * avoid prompting the user with {@link #choosePrivateKeyAlias
83 * choosePrivateKeyAlias} on subsequent connections. If the alias is
84 * no longer valid, null will be returned on lookups using that value
Brian Carlstromca43c452011-06-29 18:53:17 -070085 *
86 * <p>An application can request the installation of private keys and
87 * certificates via the {@code Intent} provided by {@link
88 * #createInstallIntent}. Private keys installed via this {@code
89 * Intent} will be accessible via {@link #choosePrivateKeyAlias} while
90 * Certificate Authority (CA) certificates will be trusted by all
91 * applications through the default {@code X509TrustManager}.
Brian Carlstromb9a07c12011-04-11 09:03:51 -070092 */
Brian Carlstrom93201f52011-06-09 15:05:35 -070093// TODO reference intent for credential installation when public
Brian Carlstromb9a07c12011-04-11 09:03:51 -070094public final class KeyChain {
95
Brian Carlstromb9a07c12011-04-11 09:03:51 -070096 /**
97 * @hide Also used by KeyChainService implementation
98 */
99 public static final String ACCOUNT_TYPE = "com.android.keychain";
100
101 /**
Kenny Roota3659062014-03-17 16:21:53 -0700102 * Package name for KeyChain chooser.
103 */
104 private static final String KEYCHAIN_PACKAGE = "com.android.keychain";
105
106 /**
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700107 * Action to bring up the KeyChainActivity
108 */
109 private static final String ACTION_CHOOSER = "com.android.keychain.CHOOSER";
110
111 /**
Kenny Root1a88d832014-02-07 09:12:48 -0800112 * Package name for the Certificate Installer.
113 */
114 private static final String CERT_INSTALLER_PACKAGE = "com.android.certinstaller";
115
116 /**
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700117 * Extra for use with {@link #ACTION_CHOOSER}
Brian Carlstromba1a6672011-05-24 21:54:37 -0700118 * @hide Also used by KeyChainActivity implementation
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700119 */
Brian Carlstromba1a6672011-05-24 21:54:37 -0700120 public static final String EXTRA_RESPONSE = "response";
121
122 /**
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700123 * Extra for use with {@link #ACTION_CHOOSER}
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700124 * @hide Also used by KeyChainActivity implementation
125 */
Robin Lee39087b12015-05-05 15:57:17 +0100126 public static final String EXTRA_URI = "uri";
Robin Lee3798ed52015-02-03 17:55:31 +0000127
128 /**
129 * Extra for use with {@link #ACTION_CHOOSER}
130 * @hide Also used by KeyChainActivity implementation
131 */
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700132 public static final String EXTRA_ALIAS = "alias";
133
134 /**
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700135 * Extra for use with {@link #ACTION_CHOOSER}
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700136 * @hide Also used by KeyChainActivity implementation
137 */
138 public static final String EXTRA_SENDER = "sender";
139
140 /**
Selim Gurun93ba4fe2012-02-14 11:48:49 -0800141 * Action to bring up the CertInstaller.
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700142 */
143 private static final String ACTION_INSTALL = "android.credentials.INSTALL";
144
145 /**
146 * Optional extra to specify a {@code String} credential name on
147 * the {@code Intent} returned by {@link #createInstallIntent}.
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700148 */
149 // Compatible with old com.android.certinstaller.CredentialHelper.CERT_NAME_KEY
150 public static final String EXTRA_NAME = "name";
151
152 /**
153 * Optional extra to specify an X.509 certificate to install on
154 * the {@code Intent} returned by {@link #createInstallIntent}.
155 * The extra value should be a PEM or ASN.1 DER encoded {@code
156 * byte[]}. An {@link X509Certificate} can be converted to DER
157 * encoded bytes with {@link X509Certificate#getEncoded}.
158 *
159 * <p>{@link #EXTRA_NAME} may be used to provide a default alias
160 * name for the installed certificate.
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700161 */
162 // Compatible with old android.security.Credentials.CERTIFICATE
163 public static final String EXTRA_CERTIFICATE = "CERT";
164
165 /**
166 * Optional extra for use with the {@code Intent} returned by
167 * {@link #createInstallIntent} to specify a PKCS#12 key store to
168 * install. The extra value should be a {@code byte[]}. The bytes
169 * may come from an external source or be generated with {@link
Brian Carlstromca43c452011-06-29 18:53:17 -0700170 * java.security.KeyStore#store} on a "PKCS12" instance.
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700171 *
172 * <p>The user will be prompted for the password to load the key store.
173 *
174 * <p>The key store will be scanned for {@link
175 * java.security.KeyStore.PrivateKeyEntry} entries and both the
176 * private key and associated certificate chain will be installed.
177 *
178 * <p>{@link #EXTRA_NAME} may be used to provide a default alias
179 * name for the installed credentials.
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700180 */
181 // Compatible with old android.security.Credentials.PKCS12
182 public static final String EXTRA_PKCS12 = "PKCS12";
183
Selim Gurun93ba4fe2012-02-14 11:48:49 -0800184 /**
Selim Gurun93ba4fe2012-02-14 11:48:49 -0800185 * Broadcast Action: Indicates the trusted storage has changed. Sent when
186 * one of this happens:
187 *
188 * <ul>
189 * <li>a new CA is added,
190 * <li>an existing CA is removed or disabled,
191 * <li>a disabled CA is enabled,
192 * <li>trusted storage is reset (all user certs are cleared),
193 * <li>when permission to access a private key is changed.
194 * </ul>
Chad Brubaker4de59ef2016-05-02 13:17:31 -0700195 *
Chad Brubakerdbf01c12016-07-25 14:54:39 -0700196 * @deprecated Use {@link #ACTION_KEYCHAIN_CHANGED}, {@link #ACTION_TRUST_STORE_CHANGED} or
Chad Brubaker721afae2016-07-08 11:06:09 -0700197 * {@link #ACTION_KEY_ACCESS_CHANGED}. Apps that target a version higher than
198 * {@link Build.VERSION_CODES#N_MR1} will not receive this broadcast.
Selim Gurun93ba4fe2012-02-14 11:48:49 -0800199 */
200 public static final String ACTION_STORAGE_CHANGED = "android.security.STORAGE_CHANGED";
201
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700202 /**
Chad Brubaker4de59ef2016-05-02 13:17:31 -0700203 * Broadcast Action: Indicates the contents of the keychain has changed. Sent when a KeyChain
204 * entry is added, modified or removed.
205 */
206 public static final String ACTION_KEYCHAIN_CHANGED = "android.security.action.KEYCHAIN_CHANGED";
207
208 /**
209 * Broadcast Action: Indicates the contents of the trusted certificate store has changed. Sent
210 * when one the following occurs:
211 *
212 * <ul>
213 * <li>A pre-installed CA is disabled or re-enabled</li>
214 * <li>A CA is added or removed from the trust store</li>
215 * </ul>
216 */
217 public static final String ACTION_TRUST_STORE_CHANGED =
218 "android.security.action.TRUST_STORE_CHANGED";
219
220 /**
221 * Broadcast Action: Indicates that the access permissions for a private key have changed.
222 *
223 */
224 public static final String ACTION_KEY_ACCESS_CHANGED =
225 "android.security.action.KEY_ACCESS_CHANGED";
226
227 /**
228 * Used as a String extra field in {@link #ACTION_KEY_ACCESS_CHANGED} to supply the alias of
229 * the key.
230 */
231 public static final String EXTRA_KEY_ALIAS = "android.security.extra.KEY_ALIAS";
232
233 /**
234 * Used as a boolean extra field in {@link #ACTION_KEY_ACCESS_CHANGED} to supply if the key is
235 * accessible to the application.
236 */
237 public static final String EXTRA_KEY_ACCESSIBLE = "android.security.extra.KEY_ACCESSIBLE";
238
239 /**
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700240 * Returns an {@code Intent} that can be used for credential
241 * installation. The intent may be used without any extras, in
242 * which case the user will be able to install credentials from
243 * their own source.
244 *
245 * <p>Alternatively, {@link #EXTRA_CERTIFICATE} or {@link
246 * #EXTRA_PKCS12} maybe used to specify the bytes of an X.509
247 * certificate or a PKCS#12 key store for installation. These
Brian Carlstromca43c452011-06-29 18:53:17 -0700248 * extras may be combined with {@link #EXTRA_NAME} to provide a
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700249 * default alias name for credentials being installed.
250 *
251 * <p>When used with {@link Activity#startActivityForResult},
252 * {@link Activity#RESULT_OK} will be returned if a credential was
253 * successfully installed, otherwise {@link
254 * Activity#RESULT_CANCELED} will be returned.
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700255 */
Alex Klyubin54bb1592015-05-11 12:30:03 -0700256 @NonNull
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700257 public static Intent createInstallIntent() {
258 Intent intent = new Intent(ACTION_INSTALL);
Kenny Root1a88d832014-02-07 09:12:48 -0800259 intent.setClassName(CERT_INSTALLER_PACKAGE,
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700260 "com.android.certinstaller.CertInstallerMain");
261 return intent;
262 }
263
264 /**
Brian Carlstromba1a6672011-05-24 21:54:37 -0700265 * Launches an {@code Activity} for the user to select the alias
266 * for a private key and certificate pair for authentication. The
267 * selected alias or null will be returned via the
Brian Carlstrom93201f52011-06-09 15:05:35 -0700268 * KeyChainAliasCallback callback.
269 *
Robin Lee3798ed52015-02-03 17:55:31 +0000270 * <p>The device or profile owner can intercept this before the activity
271 * is shown, to pick a specific private key alias.
272 *
273 * <p>{@code keyTypes} and {@code issuers} may be used to
274 * highlight suggested choices to the user, although to cope with
275 * sometimes erroneous values provided by servers, the user may be
276 * able to override these suggestions.
277 *
278 * <p>{@code host} and {@code port} may be used to give the user
279 * more context about the server requesting the credentials.
280 *
281 * <p>{@code alias} allows the chooser to preselect an existing
282 * alias which will still be subject to user confirmation.
283 *
284 * @param activity The {@link Activity} context to use for
285 * launching the new sub-Activity to prompt the user to select
286 * a private key; used only to call startActivity(); must not
287 * be null.
288 * @param response Callback to invoke when the request completes;
289 * must not be null
290 * @param keyTypes The acceptable types of asymmetric keys such as
291 * "RSA" or "DSA", or a null array.
292 * @param issuers The acceptable certificate issuers for the
293 * certificate matching the private key, or null.
294 * @param host The host name of the server requesting the
295 * certificate, or null if unavailable.
296 * @param port The port number of the server requesting the
297 * certificate, or -1 if unavailable.
298 * @param alias The alias to preselect if available, or null if
299 * unavailable.
300 */
Alex Klyubin54bb1592015-05-11 12:30:03 -0700301 public static void choosePrivateKeyAlias(@NonNull Activity activity,
302 @NonNull KeyChainAliasCallback response,
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700303 @KeyProperties.KeyAlgorithmEnum String[] keyTypes, Principal[] issuers,
Alex Klyubin54bb1592015-05-11 12:30:03 -0700304 @Nullable String host, int port, @Nullable String alias) {
Robin Lee39087b12015-05-05 15:57:17 +0100305 Uri uri = null;
306 if (host != null) {
307 uri = new Uri.Builder()
308 .authority(host + (port != -1 ? ":" + port : ""))
309 .build();
310 }
311 choosePrivateKeyAlias(activity, response, keyTypes, issuers, uri, alias);
Robin Lee3798ed52015-02-03 17:55:31 +0000312 }
313
314 /**
315 * Launches an {@code Activity} for the user to select the alias
316 * for a private key and certificate pair for authentication. The
317 * selected alias or null will be returned via the
318 * KeyChainAliasCallback callback.
319 *
320 * <p>The device or profile owner can intercept this before the activity
321 * is shown, to pick a specific private key alias.</p>
322 *
Brian Carlstrom93201f52011-06-09 15:05:35 -0700323 * <p>{@code keyTypes} and {@code issuers} may be used to
324 * highlight suggested choices to the user, although to cope with
325 * sometimes erroneous values provided by servers, the user may be
326 * able to override these suggestions.
327 *
328 * <p>{@code host} and {@code port} may be used to give the user
329 * more context about the server requesting the credentials.
330 *
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700331 * <p>{@code alias} allows the chooser to preselect an existing
332 * alias which will still be subject to user confirmation.
333 *
Brian Carlstrom93201f52011-06-09 15:05:35 -0700334 * @param activity The {@link Activity} context to use for
335 * launching the new sub-Activity to prompt the user to select
336 * a private key; used only to call startActivity(); must not
337 * be null.
338 * @param response Callback to invoke when the request completes;
339 * must not be null
340 * @param keyTypes The acceptable types of asymmetric keys such as
Alex Klyubincd2329d2015-01-14 16:45:51 -0800341 * "EC" or "RSA", or a null array.
Brian Carlstrom93201f52011-06-09 15:05:35 -0700342 * @param issuers The acceptable certificate issuers for the
343 * certificate matching the private key, or null.
Robin Lee39087b12015-05-05 15:57:17 +0100344 * @param uri The full URI the server is requesting the certificate
Robin Lee3798ed52015-02-03 17:55:31 +0000345 * for, or null if unavailable.
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700346 * @param alias The alias to preselect if available, or null if
347 * unavailable.
Brian Carlstromba1a6672011-05-24 21:54:37 -0700348 */
Alex Klyubin54bb1592015-05-11 12:30:03 -0700349 public static void choosePrivateKeyAlias(@NonNull Activity activity,
350 @NonNull KeyChainAliasCallback response,
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700351 @KeyProperties.KeyAlgorithmEnum String[] keyTypes, Principal[] issuers,
Robin Lee39087b12015-05-05 15:57:17 +0100352 @Nullable Uri uri, @Nullable String alias) {
Brian Carlstrom93201f52011-06-09 15:05:35 -0700353 /*
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700354 * TODO currently keyTypes, issuers are unused. They are meant
355 * to follow the semantics and purpose of X509KeyManager
356 * method arguments.
Brian Carlstrom93201f52011-06-09 15:05:35 -0700357 *
358 * keyTypes would allow the list to be filtered and typically
359 * will be set correctly by the server. In practice today,
Alex Klyubincd2329d2015-01-14 16:45:51 -0800360 * most all users will want only RSA or EC, and usually
Brian Carlstrom93201f52011-06-09 15:05:35 -0700361 * only a small number of certs will be available.
362 *
363 * issuers is typically not useful. Some servers historically
364 * will send the entire list of public CAs known to the
365 * server. Others will send none. If this is used, if there
366 * are no matches after applying the constraint, it should be
367 * ignored.
Brian Carlstrom93201f52011-06-09 15:05:35 -0700368 */
Brian Carlstromba1a6672011-05-24 21:54:37 -0700369 if (activity == null) {
370 throw new NullPointerException("activity == null");
371 }
372 if (response == null) {
373 throw new NullPointerException("response == null");
374 }
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700375 Intent intent = new Intent(ACTION_CHOOSER);
Kenny Roota3659062014-03-17 16:21:53 -0700376 intent.setPackage(KEYCHAIN_PACKAGE);
Fred Quintanaab8b84a2011-07-13 14:55:39 -0700377 intent.putExtra(EXTRA_RESPONSE, new AliasResponse(response));
Robin Lee39087b12015-05-05 15:57:17 +0100378 intent.putExtra(EXTRA_URI, uri);
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700379 intent.putExtra(EXTRA_ALIAS, alias);
380 // the PendingIntent is used to get calling package name
381 intent.putExtra(EXTRA_SENDER, PendingIntent.getActivity(activity, 0, new Intent(), 0));
Brian Carlstromba1a6672011-05-24 21:54:37 -0700382 activity.startActivity(intent);
383 }
384
Brian Carlstrom93201f52011-06-09 15:05:35 -0700385 private static class AliasResponse extends IKeyChainAliasCallback.Stub {
Brian Carlstrom93201f52011-06-09 15:05:35 -0700386 private final KeyChainAliasCallback keyChainAliasResponse;
Fred Quintanaab8b84a2011-07-13 14:55:39 -0700387 private AliasResponse(KeyChainAliasCallback keyChainAliasResponse) {
Brian Carlstromba1a6672011-05-24 21:54:37 -0700388 this.keyChainAliasResponse = keyChainAliasResponse;
389 }
390 @Override public void alias(String alias) {
Fred Quintanaab8b84a2011-07-13 14:55:39 -0700391 keyChainAliasResponse.alias(alias);
Brian Carlstromba1a6672011-05-24 21:54:37 -0700392 }
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700393 }
394
395 /**
Brian Carlstromba1a6672011-05-24 21:54:37 -0700396 * Returns the {@code PrivateKey} for the requested alias, or null
Robin Lee3a435f02015-12-21 12:06:04 +0000397 * if there is no result.
Brian Carlstrom93201f52011-06-09 15:05:35 -0700398 *
Robin Lee59e3baa2015-06-30 10:48:06 -0700399 * <p> This method may block while waiting for a connection to another process, and must never
400 * be called from the main thread.
Robin Leeda236182016-08-12 12:46:28 +0100401 * <p> As {@link Activity} and {@link Service} contexts are short-lived and can be destroyed
402 * at any time from the main thread, it is safer to rely on a long-lived context such as one
403 * returned from {@link Context#getApplicationContext()}.
Robin Lee59e3baa2015-06-30 10:48:06 -0700404 *
405 * @param alias The alias of the desired private key, typically returned via
406 * {@link KeyChainAliasCallback#alias}.
Brian Carlstrom93201f52011-06-09 15:05:35 -0700407 * @throws KeyChainException if the alias was valid but there was some problem accessing it.
Robin Lee59e3baa2015-06-30 10:48:06 -0700408 * @throws IllegalStateException if called from the main thread.
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700409 */
Robin Lee59e3baa2015-06-30 10:48:06 -0700410 @Nullable @WorkerThread
Alex Klyubin54bb1592015-05-11 12:30:03 -0700411 public static PrivateKey getPrivateKey(@NonNull Context context, @NonNull String alias)
Brian Carlstrom93201f52011-06-09 15:05:35 -0700412 throws KeyChainException, InterruptedException {
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700413 if (alias == null) {
414 throw new NullPointerException("alias == null");
415 }
Robin Lee28d68b12016-07-22 16:32:32 +0100416
417 final String keyId;
418 try (KeyChainConnection keyChainConnection = bind(context.getApplicationContext())) {
419 keyId = keyChainConnection.getService().requestPrivateKey(alias);
Brian Carlstrom93201f52011-06-09 15:05:35 -0700420 } catch (RemoteException e) {
421 throw new KeyChainException(e);
422 } catch (RuntimeException e) {
423 // only certain RuntimeExceptions can be propagated across the IKeyChainService call
424 throw new KeyChainException(e);
Robin Lee28d68b12016-07-22 16:32:32 +0100425 }
426
427 if (keyId == null) {
428 return null;
429 } else {
430 try {
431 return AndroidKeyStoreProvider.loadAndroidKeyStorePrivateKeyFromKeystore(
432 KeyStore.getInstance(), keyId, KeyStore.UID_SELF);
433 } catch (RuntimeException | UnrecoverableKeyException e) {
434 throw new KeyChainException(e);
435 }
Brian Carlstromba1a6672011-05-24 21:54:37 -0700436 }
437 }
438
439 /**
440 * Returns the {@code X509Certificate} chain for the requested
Rubin Xub4365912016-03-23 12:13:22 +0000441 * alias, or null if there is no result.
442 * <p>
443 * <strong>Note:</strong> If a certificate chain was explicitly specified when the alias was
444 * installed, this method will return that chain. If only the client certificate was specified
445 * at the installation time, this method will try to build a certificate chain using all
446 * available trust anchors (preinstalled and user-added).
Brian Carlstrom93201f52011-06-09 15:05:35 -0700447 *
Robin Lee59e3baa2015-06-30 10:48:06 -0700448 * <p> This method may block while waiting for a connection to another process, and must never
449 * be called from the main thread.
Robin Leeda236182016-08-12 12:46:28 +0100450 * <p> As {@link Activity} and {@link Service} contexts are short-lived and can be destroyed
451 * at any time from the main thread, it is safer to rely on a long-lived context such as one
452 * returned from {@link Context#getApplicationContext()}.
Robin Lee59e3baa2015-06-30 10:48:06 -0700453 *
Brian Carlstrom93201f52011-06-09 15:05:35 -0700454 * @param alias The alias of the desired certificate chain, typically
455 * returned via {@link KeyChainAliasCallback#alias}.
456 * @throws KeyChainException if the alias was valid but there was some problem accessing it.
Robin Lee59e3baa2015-06-30 10:48:06 -0700457 * @throws IllegalStateException if called from the main thread.
Brian Carlstromba1a6672011-05-24 21:54:37 -0700458 */
Robin Lee59e3baa2015-06-30 10:48:06 -0700459 @Nullable @WorkerThread
Alex Klyubin54bb1592015-05-11 12:30:03 -0700460 public static X509Certificate[] getCertificateChain(@NonNull Context context,
461 @NonNull String alias) throws KeyChainException, InterruptedException {
Brian Carlstromba1a6672011-05-24 21:54:37 -0700462 if (alias == null) {
463 throw new NullPointerException("alias == null");
464 }
Kenny Root0150e482013-02-13 15:22:50 -0800465
Robin Lee28d68b12016-07-22 16:32:32 +0100466 final byte[] certificateBytes;
467 final byte[] certChainBytes;
468 try (KeyChainConnection keyChainConnection = bind(context.getApplicationContext())) {
469 IKeyChainService keyChainService = keyChainConnection.getService();
470 certificateBytes = keyChainService.getCertificate(alias);
Kenny Root0150e482013-02-13 15:22:50 -0800471 if (certificateBytes == null) {
472 return null;
473 }
Robin Lee28d68b12016-07-22 16:32:32 +0100474 certChainBytes = keyChainService.getCaCertificates(alias);
475 } catch (RemoteException e) {
476 throw new KeyChainException(e);
477 } catch (RuntimeException e) {
478 // only certain RuntimeExceptions can be propagated across the IKeyChainService call
479 throw new KeyChainException(e);
480 }
481
482 try {
Rubin Xub4365912016-03-23 12:13:22 +0000483 X509Certificate leafCert = toCertificate(certificateBytes);
Rubin Xub4365912016-03-23 12:13:22 +0000484 // If the keypair is installed with a certificate chain by either
485 // DevicePolicyManager.installKeyPair or CertInstaller, return that chain.
486 if (certChainBytes != null && certChainBytes.length != 0) {
487 Collection<X509Certificate> chain = toCertificates(certChainBytes);
488 ArrayList<X509Certificate> fullChain = new ArrayList<>(chain.size() + 1);
489 fullChain.add(leafCert);
490 fullChain.addAll(chain);
491 return fullChain.toArray(new X509Certificate[fullChain.size()]);
492 } else {
493 // If there isn't a certificate chain, either due to a pre-existing keypair
494 // installed before N, or no chain is explicitly installed under the new logic,
495 // fall back to old behavior of constructing the chain from trusted credentials.
496 //
497 // This logic exists to maintain old behaviour for already installed keypair, at
498 // the cost of potentially returning extra certificate chain for new clients who
499 // explicitly installed only the client certificate without a chain. The latter
500 // case is actually no different from pre-N behaviour of getCertificateChain(),
501 // in that sense this change introduces no regression. Besides the returned chain
502 // is still valid so the consumer of the chain should have no problem verifying it.
503 TrustedCertificateStore store = new TrustedCertificateStore();
504 List<X509Certificate> chain = store.getCertificateChain(leafCert);
505 return chain.toArray(new X509Certificate[chain.size()]);
506 }
Robin Lee28d68b12016-07-22 16:32:32 +0100507 } catch (CertificateException | RuntimeException e) {
Kenny Rootcfba6a02013-05-06 15:00:58 -0700508 throw new KeyChainException(e);
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700509 }
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700510 }
511
Kenny Rootbf556ac2013-04-01 15:10:22 -0700512 /**
513 * Returns {@code true} if the current device's {@code KeyChain} supports a
514 * specific {@code PrivateKey} type indicated by {@code algorithm} (e.g.,
515 * "RSA").
516 */
Alex Klyubin4d5443f2015-05-06 15:43:52 -0700517 public static boolean isKeyAlgorithmSupported(
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700518 @NonNull @KeyProperties.KeyAlgorithmEnum String algorithm) {
Kenny Rootb91773b2013-09-05 13:03:16 -0700519 final String algUpper = algorithm.toUpperCase(Locale.US);
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700520 return KeyProperties.KEY_ALGORITHM_EC.equals(algUpper)
521 || KeyProperties.KEY_ALGORITHM_RSA.equals(algUpper);
Kenny Rootbf556ac2013-04-01 15:10:22 -0700522 }
523
524 /**
525 * Returns {@code true} if the current device's {@code KeyChain} binds any
526 * {@code PrivateKey} of the given {@code algorithm} to the device once
527 * imported or generated. This can be used to tell if there is special
528 * hardware support that can be used to bind keys to the device in a way
529 * that makes it non-exportable.
Alex Klyubin469cbf52015-06-04 12:36:27 -0700530 *
531 * @deprecated Whether the key is bound to the secure hardware is known only
532 * once the key has been imported. To find out, use:
533 * <pre>{@code
534 * PrivateKey key = ...; // private key from KeyChain
535 *
536 * KeyFactory keyFactory =
537 * KeyFactory.getInstance(key.getAlgorithm(), "AndroidKeyStore");
538 * KeyInfo keyInfo = keyFactory.getKeySpec(key, KeyInfo.class);
Neil Fuller71fbb812015-11-30 09:51:33 +0000539 * if (keyInfo.isInsideSecureHardware()) {
Alex Klyubin469cbf52015-06-04 12:36:27 -0700540 * // The key is bound to the secure hardware of this Android
Neil Fuller71fbb812015-11-30 09:51:33 +0000541 * }}</pre>
Kenny Rootbf556ac2013-04-01 15:10:22 -0700542 */
Alex Klyubin469cbf52015-06-04 12:36:27 -0700543 @Deprecated
Alex Klyubin4d5443f2015-05-06 15:43:52 -0700544 public static boolean isBoundKeyAlgorithm(
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700545 @NonNull @KeyProperties.KeyAlgorithmEnum String algorithm) {
Kenny Root5b7e90a2013-04-02 11:23:41 -0700546 if (!isKeyAlgorithmSupported(algorithm)) {
Kenny Rootbf556ac2013-04-01 15:10:22 -0700547 return false;
548 }
549
Kenny Rootb91773b2013-09-05 13:03:16 -0700550 return KeyStore.getInstance().isHardwareBacked(algorithm);
Kenny Rootbf556ac2013-04-01 15:10:22 -0700551 }
552
Zoltan Szatmary-Banf0ae1352014-08-18 10:48:33 +0100553 /** @hide */
Alex Klyubin54bb1592015-05-11 12:30:03 -0700554 @NonNull
555 public static X509Certificate toCertificate(@NonNull byte[] bytes) {
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700556 if (bytes == null) {
Brian Carlstrom8e9929c2011-05-17 00:40:28 -0700557 throw new IllegalArgumentException("bytes == null");
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700558 }
559 try {
560 CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
561 Certificate cert = certFactory.generateCertificate(new ByteArrayInputStream(bytes));
562 return (X509Certificate) cert;
563 } catch (CertificateException e) {
564 throw new AssertionError(e);
565 }
566 }
567
Rubin Xub4365912016-03-23 12:13:22 +0000568 /** @hide */
569 @NonNull
570 public static Collection<X509Certificate> toCertificates(@NonNull byte[] bytes) {
571 if (bytes == null) {
572 throw new IllegalArgumentException("bytes == null");
573 }
574 try {
575 CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
576 return (Collection<X509Certificate>) certFactory.generateCertificates(
577 new ByteArrayInputStream(bytes));
578 } catch (CertificateException e) {
579 throw new AssertionError(e);
580 }
581 }
582
Brian Carlstromd7524722011-05-17 16:20:36 -0700583 /**
584 * @hide for reuse by CertInstaller and Settings.
585 * @see KeyChain#bind
586 */
587 public final static class KeyChainConnection implements Closeable {
588 private final Context context;
589 private final ServiceConnection serviceConnection;
590 private final IKeyChainService service;
591 private KeyChainConnection(Context context,
592 ServiceConnection serviceConnection,
593 IKeyChainService service) {
594 this.context = context;
595 this.serviceConnection = serviceConnection;
596 this.service = service;
597 }
598 @Override public void close() {
599 context.unbindService(serviceConnection);
600 }
601 public IKeyChainService getService() {
602 return service;
603 }
604 }
605
606 /**
607 * @hide for reuse by CertInstaller and Settings.
608 *
609 * Caller should call unbindService on the result when finished.
610 */
Robin Lee59e3baa2015-06-30 10:48:06 -0700611 @WorkerThread
Alex Klyubin54bb1592015-05-11 12:30:03 -0700612 public static KeyChainConnection bind(@NonNull Context context) throws InterruptedException {
Robin Lee306fe082014-06-19 14:04:24 +0000613 return bindAsUser(context, Process.myUserHandle());
614 }
615
616 /**
617 * @hide
618 */
Robin Lee59e3baa2015-06-30 10:48:06 -0700619 @WorkerThread
Alex Klyubin54bb1592015-05-11 12:30:03 -0700620 public static KeyChainConnection bindAsUser(@NonNull Context context, UserHandle user)
Robin Lee306fe082014-06-19 14:04:24 +0000621 throws InterruptedException {
Brian Carlstromd7524722011-05-17 16:20:36 -0700622 if (context == null) {
623 throw new NullPointerException("context == null");
624 }
625 ensureNotOnMainThread(context);
626 final BlockingQueue<IKeyChainService> q = new LinkedBlockingQueue<IKeyChainService>(1);
627 ServiceConnection keyChainServiceConnection = new ServiceConnection() {
Fred Quintanaab8b84a2011-07-13 14:55:39 -0700628 volatile boolean mConnectedAtLeastOnce = false;
Brian Carlstromd7524722011-05-17 16:20:36 -0700629 @Override public void onServiceConnected(ComponentName name, IBinder service) {
Fred Quintanaab8b84a2011-07-13 14:55:39 -0700630 if (!mConnectedAtLeastOnce) {
631 mConnectedAtLeastOnce = true;
632 try {
633 q.put(IKeyChainService.Stub.asInterface(service));
634 } catch (InterruptedException e) {
635 // will never happen, since the queue starts with one available slot
636 }
Brian Carlstromd7524722011-05-17 16:20:36 -0700637 }
638 }
639 @Override public void onServiceDisconnected(ComponentName name) {}
640 };
Maggie Benthallda51e682013-08-08 22:35:44 -0400641 Intent intent = new Intent(IKeyChainService.class.getName());
642 ComponentName comp = intent.resolveSystemService(context.getPackageManager(), 0);
643 intent.setComponent(comp);
Robin Lee21bcbc52016-02-29 18:55:35 +0000644 if (comp == null || !context.bindServiceAsUser(
645 intent, keyChainServiceConnection, Context.BIND_AUTO_CREATE, user)) {
Brian Carlstromd7524722011-05-17 16:20:36 -0700646 throw new AssertionError("could not bind to KeyChainService");
647 }
648 return new KeyChainConnection(context, keyChainServiceConnection, q.take());
649 }
650
Alex Klyubin54bb1592015-05-11 12:30:03 -0700651 private static void ensureNotOnMainThread(@NonNull Context context) {
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700652 Looper looper = Looper.myLooper();
Brian Carlstrom8e9929c2011-05-17 00:40:28 -0700653 if (looper != null && looper == context.getMainLooper()) {
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700654 throw new IllegalStateException(
655 "calling this from your main thread can lead to deadlock");
656 }
657 }
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700658}