1 /* 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 */ 16 package android.security; 17 18 import android.annotation.NonNull; 19 import android.annotation.Nullable; 20 import android.annotation.WorkerThread; 21 import android.app.Activity; 22 import android.app.PendingIntent; 23 import android.app.Service; 24 import android.content.ComponentName; 25 import android.content.Context; 26 import android.content.Intent; 27 import android.content.ServiceConnection; 28 import android.net.Uri; 29 import android.os.IBinder; 30 import android.os.Looper; 31 import android.os.Process; 32 import android.os.RemoteException; 33 import android.os.UserHandle; 34 import android.security.keystore.AndroidKeyStoreProvider; 35 import android.security.keystore.KeyProperties; 36 37 import java.io.ByteArrayInputStream; 38 import java.io.Closeable; 39 import java.security.Principal; 40 import java.security.PrivateKey; 41 import java.security.UnrecoverableKeyException; 42 import java.security.cert.Certificate; 43 import java.security.cert.CertificateException; 44 import java.security.cert.CertificateFactory; 45 import java.security.cert.X509Certificate; 46 import java.util.ArrayList; 47 import java.util.Collection; 48 import java.util.List; 49 import java.util.Locale; 50 import java.util.concurrent.BlockingQueue; 51 import java.util.concurrent.LinkedBlockingQueue; 52 53 import com.android.org.conscrypt.TrustedCertificateStore; 54 55 /** 56 * The {@code KeyChain} class provides access to private keys and 57 * their corresponding certificate chains in credential storage. 58 * 59 * <p>Applications accessing the {@code KeyChain} normally go through 60 * these steps: 61 * 62 * <ol> 63 * 64 * <li>Receive a callback from an {@link javax.net.ssl.X509KeyManager 65 * X509KeyManager} that a private key is requested. 66 * 67 * <li>Call {@link #choosePrivateKeyAlias 68 * choosePrivateKeyAlias} to allow the user to select from a 69 * list of currently available private keys and corresponding 70 * certificate chains. The chosen alias will be returned by the 71 * callback {@link KeyChainAliasCallback#alias}, or null if no private 72 * key is available or the user cancels the request. 73 * 74 * <li>Call {@link #getPrivateKey} and {@link #getCertificateChain} to 75 * retrieve the credentials to return to the corresponding {@link 76 * javax.net.ssl.X509KeyManager} callbacks. 77 * 78 * </ol> 79 * 80 * <p>An application may remember the value of a selected alias to 81 * avoid prompting the user with {@link #choosePrivateKeyAlias 82 * choosePrivateKeyAlias} on subsequent connections. If the alias is 83 * no longer valid, null will be returned on lookups using that value 84 * 85 * <p>An application can request the installation of private keys and 86 * certificates via the {@code Intent} provided by {@link 87 * #createInstallIntent}. Private keys installed via this {@code 88 * Intent} will be accessible via {@link #choosePrivateKeyAlias} while 89 * Certificate Authority (CA) certificates will be trusted by all 90 * applications through the default {@code X509TrustManager}. 91 */ 92 // TODO reference intent for credential installation when public 93 public final class KeyChain { 94 95 /** 96 * @hide Also used by KeyChainService implementation 97 */ 98 public static final String ACCOUNT_TYPE = "com.android.keychain"; 99 100 /** 101 * Package name for KeyChain chooser. 102 */ 103 private static final String KEYCHAIN_PACKAGE = "com.android.keychain"; 104 105 /** 106 * Action to bring up the KeyChainActivity 107 */ 108 private static final String ACTION_CHOOSER = "com.android.keychain.CHOOSER"; 109 110 /** 111 * Package name for the Certificate Installer. 112 */ 113 private static final String CERT_INSTALLER_PACKAGE = "com.android.certinstaller"; 114 115 /** 116 * Extra for use with {@link #ACTION_CHOOSER} 117 * @hide Also used by KeyChainActivity implementation 118 */ 119 public static final String EXTRA_RESPONSE = "response"; 120 121 /** 122 * Extra for use with {@link #ACTION_CHOOSER} 123 * @hide Also used by KeyChainActivity implementation 124 */ 125 public static final String EXTRA_URI = "uri"; 126 127 /** 128 * Extra for use with {@link #ACTION_CHOOSER} 129 * @hide Also used by KeyChainActivity implementation 130 */ 131 public static final String EXTRA_ALIAS = "alias"; 132 133 /** 134 * Extra for use with {@link #ACTION_CHOOSER} 135 * @hide Also used by KeyChainActivity implementation 136 */ 137 public static final String EXTRA_SENDER = "sender"; 138 139 /** 140 * Action to bring up the CertInstaller. 141 */ 142 private static final String ACTION_INSTALL = "android.credentials.INSTALL"; 143 144 /** 145 * Optional extra to specify a {@code String} credential name on 146 * the {@code Intent} returned by {@link #createInstallIntent}. 147 */ 148 // Compatible with old com.android.certinstaller.CredentialHelper.CERT_NAME_KEY 149 public static final String EXTRA_NAME = "name"; 150 151 /** 152 * Optional extra to specify an X.509 certificate to install on 153 * the {@code Intent} returned by {@link #createInstallIntent}. 154 * The extra value should be a PEM or ASN.1 DER encoded {@code 155 * byte[]}. An {@link X509Certificate} can be converted to DER 156 * encoded bytes with {@link X509Certificate#getEncoded}. 157 * 158 * <p>{@link #EXTRA_NAME} may be used to provide a default alias 159 * name for the installed certificate. 160 */ 161 // Compatible with old android.security.Credentials.CERTIFICATE 162 public static final String EXTRA_CERTIFICATE = "CERT"; 163 164 /** 165 * Optional extra for use with the {@code Intent} returned by 166 * {@link #createInstallIntent} to specify a PKCS#12 key store to 167 * install. The extra value should be a {@code byte[]}. The bytes 168 * may come from an external source or be generated with {@link 169 * java.security.KeyStore#store} on a "PKCS12" instance. 170 * 171 * <p>The user will be prompted for the password to load the key store. 172 * 173 * <p>The key store will be scanned for {@link 174 * java.security.KeyStore.PrivateKeyEntry} entries and both the 175 * private key and associated certificate chain will be installed. 176 * 177 * <p>{@link #EXTRA_NAME} may be used to provide a default alias 178 * name for the installed credentials. 179 */ 180 // Compatible with old android.security.Credentials.PKCS12 181 public static final String EXTRA_PKCS12 = "PKCS12"; 182 183 184 /** 185 * 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> 195 */ 196 public static final String ACTION_STORAGE_CHANGED = "android.security.STORAGE_CHANGED"; 197 198 /** 199 * Returns an {@code Intent} that can be used for credential 200 * installation. The intent may be used without any extras, in 201 * which case the user will be able to install credentials from 202 * their own source. 203 * 204 * <p>Alternatively, {@link #EXTRA_CERTIFICATE} or {@link 205 * #EXTRA_PKCS12} maybe used to specify the bytes of an X.509 206 * certificate or a PKCS#12 key store for installation. These 207 * extras may be combined with {@link #EXTRA_NAME} to provide a 208 * default alias name for credentials being installed. 209 * 210 * <p>When used with {@link Activity#startActivityForResult}, 211 * {@link Activity#RESULT_OK} will be returned if a credential was 212 * successfully installed, otherwise {@link 213 * Activity#RESULT_CANCELED} will be returned. 214 */ 215 @NonNull 216 public static Intent createInstallIntent() { 217 Intent intent = new Intent(ACTION_INSTALL); 218 intent.setClassName(CERT_INSTALLER_PACKAGE, 219 "com.android.certinstaller.CertInstallerMain"); 220 return intent; 221 } 222 223 /** 224 * Launches an {@code Activity} for the user to select the alias 225 * for a private key and certificate pair for authentication. The 226 * selected alias or null will be returned via the 227 * KeyChainAliasCallback callback. 228 * 229 * <p>The device or profile owner can intercept this before the activity 230 * is shown, to pick a specific private key alias. 231 * 232 * <p>{@code keyTypes} and {@code issuers} may be used to 233 * highlight suggested choices to the user, although to cope with 234 * sometimes erroneous values provided by servers, the user may be 235 * able to override these suggestions. 236 * 237 * <p>{@code host} and {@code port} may be used to give the user 238 * more context about the server requesting the credentials. 239 * 240 * <p>{@code alias} allows the chooser to preselect an existing 241 * alias which will still be subject to user confirmation. 242 * 243 * @param activity The {@link Activity} context to use for 244 * launching the new sub-Activity to prompt the user to select 245 * a private key; used only to call startActivity(); must not 246 * be null. 247 * @param response Callback to invoke when the request completes; 248 * must not be null 249 * @param keyTypes The acceptable types of asymmetric keys such as 250 * "RSA" or "DSA", or a null array. 251 * @param issuers The acceptable certificate issuers for the 252 * certificate matching the private key, or null. 253 * @param host The host name of the server requesting the 254 * certificate, or null if unavailable. 255 * @param port The port number of the server requesting the 256 * certificate, or -1 if unavailable. 257 * @param alias The alias to preselect if available, or null if 258 * unavailable. 259 */ 260 public static void choosePrivateKeyAlias(@NonNull Activity activity, 261 @NonNull KeyChainAliasCallback response, 262 @KeyProperties.KeyAlgorithmEnum String[] keyTypes, Principal[] issuers, 263 @Nullable String host, int port, @Nullable String alias) { 264 Uri uri = null; 265 if (host != null) { 266 uri = new Uri.Builder() 267 .authority(host + (port != -1 ? ":" + port : "")) 268 .build(); 269 } 270 choosePrivateKeyAlias(activity, response, keyTypes, issuers, uri, alias); 271 } 272 273 /** 274 * Launches an {@code Activity} for the user to select the alias 275 * for a private key and certificate pair for authentication. The 276 * selected alias or null will be returned via the 277 * KeyChainAliasCallback callback. 278 * 279 * <p>The device or profile owner can intercept this before the activity 280 * is shown, to pick a specific private key alias.</p> 281 * 282 * <p>{@code keyTypes} and {@code issuers} may be used to 283 * highlight suggested choices to the user, although to cope with 284 * sometimes erroneous values provided by servers, the user may be 285 * able to override these suggestions. 286 * 287 * <p>{@code host} and {@code port} may be used to give the user 288 * more context about the server requesting the credentials. 289 * 290 * <p>{@code alias} allows the chooser to preselect an existing 291 * alias which will still be subject to user confirmation. 292 * 293 * @param activity The {@link Activity} context to use for 294 * launching the new sub-Activity to prompt the user to select 295 * a private key; used only to call startActivity(); must not 296 * be null. 297 * @param response Callback to invoke when the request completes; 298 * must not be null 299 * @param keyTypes The acceptable types of asymmetric keys such as 300 * "EC" or "RSA", or a null array. 301 * @param issuers The acceptable certificate issuers for the 302 * certificate matching the private key, or null. 303 * @param uri The full URI the server is requesting the certificate 304 * for, or null if unavailable. 305 * @param alias The alias to preselect if available, or null if 306 * unavailable. 307 */ 308 public static void choosePrivateKeyAlias(@NonNull Activity activity, 309 @NonNull KeyChainAliasCallback response, 310 @KeyProperties.KeyAlgorithmEnum String[] keyTypes, Principal[] issuers, 311 @Nullable Uri uri, @Nullable String alias) { 312 /* 313 * TODO currently keyTypes, issuers are unused. They are meant 314 * to follow the semantics and purpose of X509KeyManager 315 * method arguments. 316 * 317 * keyTypes would allow the list to be filtered and typically 318 * will be set correctly by the server. In practice today, 319 * most all users will want only RSA or EC, and usually 320 * only a small number of certs will be available. 321 * 322 * issuers is typically not useful. Some servers historically 323 * will send the entire list of public CAs known to the 324 * server. Others will send none. If this is used, if there 325 * are no matches after applying the constraint, it should be 326 * ignored. 327 */ 328 if (activity == null) { 329 throw new NullPointerException("activity == null"); 330 } 331 if (response == null) { 332 throw new NullPointerException("response == null"); 333 } 334 Intent intent = new Intent(ACTION_CHOOSER); 335 intent.setPackage(KEYCHAIN_PACKAGE); 336 intent.putExtra(EXTRA_RESPONSE, new AliasResponse(response)); 337 intent.putExtra(EXTRA_URI, uri); 338 intent.putExtra(EXTRA_ALIAS, alias); 339 // the PendingIntent is used to get calling package name 340 intent.putExtra(EXTRA_SENDER, PendingIntent.getActivity(activity, 0, new Intent(), 0)); 341 activity.startActivity(intent); 342 } 343 344 private static class AliasResponse extends IKeyChainAliasCallback.Stub { 345 private final KeyChainAliasCallback keyChainAliasResponse; 346 private AliasResponse(KeyChainAliasCallback keyChainAliasResponse) { 347 this.keyChainAliasResponse = keyChainAliasResponse; 348 } 349 @Override public void alias(String alias) { 350 keyChainAliasResponse.alias(alias); 351 } 352 } 353 354 /** 355 * Returns the {@code PrivateKey} for the requested alias, or null 356 * if there is no result. 357 * 358 * <p> This method may block while waiting for a connection to another process, and must never 359 * be called from the main thread. 360 * <p> As {@link Activity} and {@link Service} contexts are short-lived and can be destroyed 361 * at any time from the main thread, it is safer to rely on a long-lived context such as one 362 * returned from {@link Context#getApplicationContext()}. 363 * 364 * @param alias The alias of the desired private key, typically returned via 365 * {@link KeyChainAliasCallback#alias}. 366 * @throws KeyChainException if the alias was valid but there was some problem accessing it. 367 * @throws IllegalStateException if called from the main thread. 368 */ 369 @Nullable @WorkerThread 370 public static PrivateKey getPrivateKey(@NonNull Context context, @NonNull String alias) 371 throws KeyChainException, InterruptedException { 372 if (alias == null) { 373 throw new NullPointerException("alias == null"); 374 } 375 KeyChainConnection keyChainConnection = bind(context.getApplicationContext()); 376 try { 377 final IKeyChainService keyChainService = keyChainConnection.getService(); 378 final String keyId = keyChainService.requestPrivateKey(alias); 379 if (keyId == null) { 380 return null; 381 } 382 return AndroidKeyStoreProvider.loadAndroidKeyStorePrivateKeyFromKeystore( 383 KeyStore.getInstance(), keyId, KeyStore.UID_SELF); 384 } catch (RemoteException e) { 385 throw new KeyChainException(e); 386 } catch (RuntimeException e) { 387 // only certain RuntimeExceptions can be propagated across the IKeyChainService call 388 throw new KeyChainException(e); 389 } catch (UnrecoverableKeyException e) { 390 throw new KeyChainException(e); 391 } finally { 392 keyChainConnection.close(); 393 } 394 } 395 396 /** 397 * Returns the {@code X509Certificate} chain for the requested 398 * alias, or null if there is no result. 399 * <p> 400 * <strong>Note:</strong> If a certificate chain was explicitly specified when the alias was 401 * installed, this method will return that chain. If only the client certificate was specified 402 * at the installation time, this method will try to build a certificate chain using all 403 * available trust anchors (preinstalled and user-added). 404 * 405 * <p> This method may block while waiting for a connection to another process, and must never 406 * be called from the main thread. 407 * <p> As {@link Activity} and {@link Service} contexts are short-lived and can be destroyed 408 * at any time from the main thread, it is safer to rely on a long-lived context such as one 409 * returned from {@link Context#getApplicationContext()}. 410 * 411 * @param alias The alias of the desired certificate chain, typically 412 * returned via {@link KeyChainAliasCallback#alias}. 413 * @throws KeyChainException if the alias was valid but there was some problem accessing it. 414 * @throws IllegalStateException if called from the main thread. 415 */ 416 @Nullable @WorkerThread 417 public static X509Certificate[] getCertificateChain(@NonNull Context context, 418 @NonNull String alias) throws KeyChainException, InterruptedException { 419 if (alias == null) { 420 throw new NullPointerException("alias == null"); 421 } 422 KeyChainConnection keyChainConnection = bind(context.getApplicationContext()); 423 try { 424 IKeyChainService keyChainService = keyChainConnection.getService(); 425 426 final byte[] certificateBytes = keyChainService.getCertificate(alias); 427 if (certificateBytes == null) { 428 return null; 429 } 430 X509Certificate leafCert = toCertificate(certificateBytes); 431 final byte[] certChainBytes = keyChainService.getCaCertificates(alias); 432 // If the keypair is installed with a certificate chain by either 433 // DevicePolicyManager.installKeyPair or CertInstaller, return that chain. 434 if (certChainBytes != null && certChainBytes.length != 0) { 435 Collection<X509Certificate> chain = toCertificates(certChainBytes); 436 ArrayList<X509Certificate> fullChain = new ArrayList<>(chain.size() + 1); 437 fullChain.add(leafCert); 438 fullChain.addAll(chain); 439 return fullChain.toArray(new X509Certificate[fullChain.size()]); 440 } else { 441 // If there isn't a certificate chain, either due to a pre-existing keypair 442 // installed before N, or no chain is explicitly installed under the new logic, 443 // fall back to old behavior of constructing the chain from trusted credentials. 444 // 445 // This logic exists to maintain old behaviour for already installed keypair, at 446 // the cost of potentially returning extra certificate chain for new clients who 447 // explicitly installed only the client certificate without a chain. The latter 448 // case is actually no different from pre-N behaviour of getCertificateChain(), 449 // in that sense this change introduces no regression. Besides the returned chain 450 // is still valid so the consumer of the chain should have no problem verifying it. 451 TrustedCertificateStore store = new TrustedCertificateStore(); 452 List<X509Certificate> chain = store.getCertificateChain(leafCert); 453 return chain.toArray(new X509Certificate[chain.size()]); 454 } 455 } catch (CertificateException e) { 456 throw new KeyChainException(e); 457 } catch (RemoteException e) { 458 throw new KeyChainException(e); 459 } catch (RuntimeException e) { 460 // only certain RuntimeExceptions can be propagated across the IKeyChainService call 461 throw new KeyChainException(e); 462 } finally { 463 keyChainConnection.close(); 464 } 465 } 466 467 /** 468 * Returns {@code true} if the current device's {@code KeyChain} supports a 469 * specific {@code PrivateKey} type indicated by {@code algorithm} (e.g., 470 * "RSA"). 471 */ 472 public static boolean isKeyAlgorithmSupported( 473 @NonNull @KeyProperties.KeyAlgorithmEnum String algorithm) { 474 final String algUpper = algorithm.toUpperCase(Locale.US); 475 return KeyProperties.KEY_ALGORITHM_EC.equals(algUpper) 476 || KeyProperties.KEY_ALGORITHM_RSA.equals(algUpper); 477 } 478 479 /** 480 * Returns {@code true} if the current device's {@code KeyChain} binds any 481 * {@code PrivateKey} of the given {@code algorithm} to the device once 482 * imported or generated. This can be used to tell if there is special 483 * hardware support that can be used to bind keys to the device in a way 484 * that makes it non-exportable. 485 * 486 * @deprecated Whether the key is bound to the secure hardware is known only 487 * once the key has been imported. To find out, use: 488 * <pre>{@code 489 * PrivateKey key = ...; // private key from KeyChain 490 * 491 * KeyFactory keyFactory = 492 * KeyFactory.getInstance(key.getAlgorithm(), "AndroidKeyStore"); 493 * KeyInfo keyInfo = keyFactory.getKeySpec(key, KeyInfo.class); 494 * if (keyInfo.isInsideSecureHardware()) { 495 * // The key is bound to the secure hardware of this Android 496 * }}</pre> 497 */ 498 @Deprecated 499 public static boolean isBoundKeyAlgorithm( 500 @NonNull @KeyProperties.KeyAlgorithmEnum String algorithm) { 501 if (!isKeyAlgorithmSupported(algorithm)) { 502 return false; 503 } 504 505 return KeyStore.getInstance().isHardwareBacked(algorithm); 506 } 507 508 /** @hide */ 509 @NonNull 510 public static X509Certificate toCertificate(@NonNull byte[] bytes) { 511 if (bytes == null) { 512 throw new IllegalArgumentException("bytes == null"); 513 } 514 try { 515 CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); 516 Certificate cert = certFactory.generateCertificate(new ByteArrayInputStream(bytes)); 517 return (X509Certificate) cert; 518 } catch (CertificateException e) { 519 throw new AssertionError(e); 520 } 521 } 522 523 /** @hide */ 524 @NonNull 525 public static Collection<X509Certificate> toCertificates(@NonNull byte[] bytes) { 526 if (bytes == null) { 527 throw new IllegalArgumentException("bytes == null"); 528 } 529 try { 530 CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); 531 return (Collection<X509Certificate>) certFactory.generateCertificates( 532 new ByteArrayInputStream(bytes)); 533 } catch (CertificateException e) { 534 throw new AssertionError(e); 535 } 536 } 537 538 /** 539 * @hide for reuse by CertInstaller and Settings. 540 * @see KeyChain#bind 541 */ 542 public final static class KeyChainConnection implements Closeable { 543 private final Context context; 544 private final ServiceConnection serviceConnection; 545 private final IKeyChainService service; 546 private KeyChainConnection(Context context, 547 ServiceConnection serviceConnection, 548 IKeyChainService service) { 549 this.context = context; 550 this.serviceConnection = serviceConnection; 551 this.service = service; 552 } 553 @Override public void close() { 554 context.unbindService(serviceConnection); 555 } 556 public IKeyChainService getService() { 557 return service; 558 } 559 } 560 561 /** 562 * @hide for reuse by CertInstaller and Settings. 563 * 564 * Caller should call unbindService on the result when finished. 565 */ 566 @WorkerThread 567 public static KeyChainConnection bind(@NonNull Context context) throws InterruptedException { 568 return bindAsUser(context, Process.myUserHandle()); 569 } 570 571 /** 572 * @hide 573 */ 574 @WorkerThread 575 public static KeyChainConnection bindAsUser(@NonNull Context context, UserHandle user) 576 throws InterruptedException { 577 if (context == null) { 578 throw new NullPointerException("context == null"); 579 } 580 ensureNotOnMainThread(context); 581 final BlockingQueue<IKeyChainService> q = new LinkedBlockingQueue<IKeyChainService>(1); 582 ServiceConnection keyChainServiceConnection = new ServiceConnection() { 583 volatile boolean mConnectedAtLeastOnce = false; 584 @Override public void onServiceConnected(ComponentName name, IBinder service) { 585 if (!mConnectedAtLeastOnce) { 586 mConnectedAtLeastOnce = true; 587 try { 588 q.put(IKeyChainService.Stub.asInterface(service)); 589 } catch (InterruptedException e) { 590 // will never happen, since the queue starts with one available slot 591 } 592 } 593 } 594 @Override public void onServiceDisconnected(ComponentName name) {} 595 }; 596 Intent intent = new Intent(IKeyChainService.class.getName()); 597 ComponentName comp = intent.resolveSystemService(context.getPackageManager(), 0); 598 intent.setComponent(comp); 599 if (comp == null || !context.bindServiceAsUser( 600 intent, keyChainServiceConnection, Context.BIND_AUTO_CREATE, user)) { 601 throw new AssertionError("could not bind to KeyChainService"); 602 } 603 return new KeyChainConnection(context, keyChainServiceConnection, q.take()); 604 } 605 606 private static void ensureNotOnMainThread(@NonNull Context context) { 607 Looper looper = Looper.myLooper(); 608 if (looper != null && looper == context.getMainLooper()) { 609 throw new IllegalStateException( 610 "calling this from your main thread can lead to deadlock"); 611 } 612 } 613 } 614