RecoveryController.java revision 93f38d7b3a5bda2bd9bcc7def67936370b40e306
1/* 2 * Copyright (C) 2017 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 17package android.security.keystore.recovery; 18 19import android.annotation.NonNull; 20import android.annotation.Nullable; 21import android.annotation.RequiresPermission; 22import android.annotation.SystemApi; 23import android.app.PendingIntent; 24import android.content.Context; 25import android.content.pm.PackageManager.NameNotFoundException; 26import android.os.RemoteException; 27import android.os.ServiceManager; 28import android.os.ServiceSpecificException; 29import android.security.KeyStore; 30import android.security.keystore.AndroidKeyStoreProvider; 31 32import com.android.internal.widget.ILockSettings; 33 34import java.security.Key; 35import java.security.UnrecoverableKeyException; 36import java.security.cert.CertPath; 37import java.security.cert.CertificateException; 38import java.security.cert.X509Certificate; 39import java.util.ArrayList; 40import java.util.List; 41import java.util.Map; 42 43/** 44 * Backs up cryptographic keys to remote secure hardware, encrypted with the user's lock screen. 45 * 46 * <p>A system app with the {@link android.Manifest#RECOVER_KEYSTORE} permission may generate or 47 * import recoverable keys using this class. To generate a key, the app must call 48 * {@link #generateKey(String)} with the desired alias for the key. This returns an AndroidKeyStore 49 * reference to a 256-bit {@link javax.crypto.SecretKey}, which can be used for AES/GCM/NoPadding. 50 * In order to get the same key again at a later time, the app can call {@link #getKey(String)} with 51 * the same alias. If a key is generated in this way the key's raw material is never directly 52 * exposed to the calling app. The system app may also import key material using 53 * {@link #importKey(String, byte[])}. The app may only generate and import keys for its own 54 * {@code uid}. 55 * 56 * <p>The same system app must also register a Recovery Agent to manage syncing recoverable keys to 57 * remote secure hardware. The Recovery Agent is a service that registers itself with the controller 58 * as follows: 59 * 60 * <ul> 61 * <li>Invokes {@link #initRecoveryService(String, byte[], byte[])} 62 * <ul> 63 * <li>The first argument is the alias of the root certificate used to verify trusted 64 * hardware modules. Each trusted hardware module must have a public key signed with this 65 * root of trust. Roots of trust must be shipped with the framework. The app can list all 66 * valid roots of trust by calling {@link #getRootCertificates()}. 67 * <li>The second argument is the UTF-8 bytes of the XML listing file. It lists the X509 68 * certificates containing the public keys of all available remote trusted hardware modules. 69 * Each of the X509 certificates can be validated against the chosen root of trust. 70 * <li>The third argument is the UTF-8 bytes of the XML signing file. The file contains a 71 * signature of the XML listing file. The signature can be validated against the chosen root 72 * of trust. 73 * </ul> 74 * <p>This will cause the controller to choose a random public key from the list. From then 75 * on the controller will attempt to sync the key chain with the trusted hardware module to whom 76 * that key belongs. 77 * <li>Invokes {@link #setServerParams(byte[])} with a byte string that identifies the device 78 * to a remote server. This server may act as the front-end to the trusted hardware modules. It 79 * is up to the Recovery Agent to decide how best to identify devices, but this could be, e.g., 80 * based on the <a href="https://developers.google.com/instance-id/">Instance ID</a> of the 81 * system app. 82 * <li>Invokes {@link #setRecoverySecretTypes(int[])} with a list of types of secret used to 83 * secure the recoverable key chain. For now only 84 * {@link KeyChainProtectionParams#TYPE_LOCKSCREEN} is supported. 85 * <li>Invokes {@link #setSnapshotCreatedPendingIntent(PendingIntent)} with a 86 * {@link PendingIntent} that is to be invoked whenever a new snapshot is created. Although the 87 * controller can create snapshots without the Recovery Agent registering this intent, it is a 88 * good idea to register the intent so that the Recovery Agent is able to sync this snapshot to 89 * the trusted hardware module as soon as it is available. 90 * </ul> 91 * 92 * <p>The trusted hardware module's public key MUST be generated on secure hardware with protections 93 * equivalent to those described in the 94 * <a href="https://developer.android.com/preview/features/security/ckv-whitepaper.html">Google 95 * Cloud Key Vault Service whitepaper</a>. The trusted hardware module itself must protect the key 96 * chain from brute-forcing using the methods also described in the whitepaper: i.e., it should 97 * limit the number of allowed attempts to enter the lock screen. If the number of attempts is 98 * exceeded the key material must no longer be recoverable. 99 * 100 * <p>A recoverable key chain snapshot is considered pending if any of the following conditions 101 * are met: 102 * 103 * <ul> 104 * <li>The system app mutates the key chain. i.e., generates, imports, or removes a key. 105 * <li>The user changes their lock screen. 106 * </ul> 107 * 108 * <p>Whenever the user unlocks their device, if a snapshot is pending, the Recovery Controller 109 * generates a new snapshot. It follows these steps to do so: 110 * 111 * <ul> 112 * <li>Generates a 256-bit AES key using {@link java.security.SecureRandom}. This is the 113 * Recovery Key. 114 * <li>Wraps the key material of all keys in the recoverable key chain with the Recovery Key. 115 * <li>Encrypts the Recovery Key with both the public key of the trusted hardware module and a 116 * symmetric key derived from the user's lock screen. 117 * </ul> 118 * 119 * <p>The controller then writes this snapshot to disk, and uses the {@link PendingIntent} that was 120 * set by the Recovery Agent during initialization to inform it that a new snapshot is available. 121 * The snapshot only contains keys for that Recovery Agent's {@code uid} - i.e., keys the agent's 122 * app itself generated. If multiple Recovery Agents exist on the device, each will be notified of 123 * their new snapshots, and each snapshots' keys will be only those belonging to the same 124 * {@code uid}. 125 * 126 * <p>The Recovery Agent retrieves its most recent snapshot by calling 127 * {@link #getKeyChainSnapshot()}. It syncs the snapshot to the remote server. The snapshot contains 128 * the public key used for encryption, which the server uses to forward the encrypted recovery key 129 * to the correct trusted hardware module. The snapshot also contains the server params, which are 130 * used to identify this device to the server. 131 * 132 * <p>The client uses the server params to identify a device whose key chain it wishes to restore. 133 * This may be on a different device to the device that originally synced the key chain. The client 134 * sends the server params identifying the previous device to the server. The server returns the 135 * X509 certificate identifying the trusted hardware module in which the encrypted Recovery Key is 136 * stored. It also returns some vault parameters identifying that particular Recovery Key to the 137 * trusted hardware module. And it also returns a vault challenge, which is used as part of the 138 * vault opening protocol to ensure the recovery claim is fresh. See the whitepaper for more 139 * details. 140 * 141 * <p>The key chain is recovered via a {@link RecoverySession}. A Recovery Agent creates one by 142 * invoking {@link #createRecoverySession()}. It then invokes 143 * {@link RecoverySession#start(String, CertPath, byte[], byte[], List)} with these arguments: 144 * 145 * <ul> 146 * <li>The alias of the root of trust used to verify the trusted hardware module. 147 * <li>The X509 certificate of the trusted hardware module. 148 * <li>The vault parameters used to identify the Recovery Key to the trusted hardware module. 149 * <li>The vault challenge, as issued by the trusted hardware module. 150 * <li>A list of secrets, corresponding to the secrets used to protect the key chain. At the 151 * moment this is a single {@link KeyChainProtectionParams} containing the lock screen of the 152 * device whose key chain is to be recovered. 153 * </ul> 154 * 155 * <p>This method returns a byte array containing the Recovery Claim, which can be issued to the 156 * remote trusted hardware module. It is encrypted with the trusted hardware module's public key 157 * (which has itself been certified with the root of trust). It also contains an ephemeral symmetric 158 * key generated for this recovery session, which the remote trusted hardware module uses to encrypt 159 * its responses. This is the Session Key. 160 * 161 * <p>If the lock screen provided is correct, the remote trusted hardware module decrypts one of the 162 * layers of lock-screen encryption from the Recovery Key. It then returns this key, encrypted with 163 * the Session Key to the Recovery Agent. As the Recovery Agent does not know the Session Key, it 164 * must then invoke {@link RecoverySession#recoverKeyChainSnapshot(byte[], List)} with the encrypted 165 * Recovery Key and the list of wrapped application keys. The controller then decrypts the layer of 166 * encryption provided by the Session Key, and uses the lock screen to decrypt the final layer of 167 * encryption. It then uses the Recovery Key to decrypt all of the wrapped application keys, and 168 * imports them into its own KeyStore. The Recovery Agent's app may then access these keys by 169 * calling {@link #getKey(String)}. Only this app's {@code uid} may access the keys that have been 170 * recovered. 171 * 172 * @hide 173 */ 174@SystemApi 175public class RecoveryController { 176 private static final String TAG = "RecoveryController"; 177 178 /** Key has been successfully synced. */ 179 public static final int RECOVERY_STATUS_SYNCED = 0; 180 /** Waiting for recovery agent to sync the key. */ 181 public static final int RECOVERY_STATUS_SYNC_IN_PROGRESS = 1; 182 /** Key cannot be synced. */ 183 public static final int RECOVERY_STATUS_PERMANENT_FAILURE = 3; 184 185 /** 186 * Failed because no snapshot is yet pending to be synced for the user. 187 * 188 * @hide 189 */ 190 public static final int ERROR_NO_SNAPSHOT_PENDING = 21; 191 192 /** 193 * Failed due to an error internal to the recovery service. This is unexpected and indicates 194 * either a problem with the logic in the service, or a problem with a dependency of the 195 * service (such as AndroidKeyStore). 196 * 197 * @hide 198 */ 199 public static final int ERROR_SERVICE_INTERNAL_ERROR = 22; 200 201 /** 202 * Failed because the user does not have a lock screen set. 203 * 204 * @hide 205 */ 206 public static final int ERROR_INSECURE_USER = 23; 207 208 /** 209 * Error thrown when attempting to use a recovery session that has since been closed. 210 * 211 * @hide 212 */ 213 public static final int ERROR_SESSION_EXPIRED = 24; 214 215 /** 216 * Failed because the format of the provided certificate is incorrect, e.g., cannot be decoded 217 * properly or misses necessary fields. 218 * 219 * <p>Note that this is different from {@link #ERROR_INVALID_CERTIFICATE}, which implies the 220 * certificate has a correct format but cannot be validated. 221 * 222 * @hide 223 */ 224 public static final int ERROR_BAD_CERTIFICATE_FORMAT = 25; 225 226 /** 227 * Error thrown if decryption failed. This might be because the tag is wrong, the key is wrong, 228 * the data has become corrupted, the data has been tampered with, etc. 229 * 230 * @hide 231 */ 232 public static final int ERROR_DECRYPTION_FAILED = 26; 233 234 /** 235 * Error thrown if the format of a given key is invalid. This might be because the key has a 236 * wrong length, invalid content, etc. 237 * 238 * @hide 239 */ 240 public static final int ERROR_INVALID_KEY_FORMAT = 27; 241 242 /** 243 * Failed because the provided certificate cannot be validated, e.g., is expired or has invalid 244 * signatures. 245 * 246 * <p>Note that this is different from {@link #ERROR_BAD_CERTIFICATE_FORMAT}, which denotes 247 * incorrect certificate formats, e.g., due to wrong encoding or structure. 248 * 249 * @hide 250 */ 251 public static final int ERROR_INVALID_CERTIFICATE = 28; 252 253 private final ILockSettings mBinder; 254 private final KeyStore mKeyStore; 255 256 private RecoveryController(ILockSettings binder, KeyStore keystore) { 257 mBinder = binder; 258 mKeyStore = keystore; 259 } 260 261 /** 262 * Internal method used by {@code RecoverySession}. 263 * 264 * @hide 265 */ 266 ILockSettings getBinder() { 267 return mBinder; 268 } 269 270 /** 271 * Gets a new instance of the class. 272 */ 273 @RequiresPermission(android.Manifest.permission.RECOVER_KEYSTORE) 274 @NonNull public static RecoveryController getInstance(@NonNull Context context) { 275 ILockSettings lockSettings = 276 ILockSettings.Stub.asInterface(ServiceManager.getService("lock_settings")); 277 return new RecoveryController(lockSettings, KeyStore.getInstance()); 278 } 279 280 /** 281 * @deprecated Use {@link #initRecoveryService(String, byte[], byte[])} instead. 282 */ 283 @Deprecated 284 @RequiresPermission(android.Manifest.permission.RECOVER_KEYSTORE) 285 public void initRecoveryService( 286 @NonNull String rootCertificateAlias, @NonNull byte[] signedPublicKeyList) 287 throws CertificateException, InternalRecoveryServiceException { 288 try { 289 mBinder.initRecoveryService(rootCertificateAlias, signedPublicKeyList); 290 } catch (RemoteException e) { 291 throw e.rethrowFromSystemServer(); 292 } catch (ServiceSpecificException e) { 293 if (e.errorCode == ERROR_BAD_CERTIFICATE_FORMAT 294 || e.errorCode == ERROR_INVALID_CERTIFICATE) { 295 throw new CertificateException(e.getMessage()); 296 } 297 throw wrapUnexpectedServiceSpecificException(e); 298 } 299 } 300 301 /** 302 * Initializes the recovery service for the calling application. The detailed steps should be: 303 * <ol> 304 * <li>Parse {@code signatureFile} to get relevant information. 305 * <li>Validate the signer's X509 certificate, contained in {@code signatureFile}, against 306 * the root certificate pre-installed in the OS and chosen by {@code 307 * rootCertificateAlias}. 308 * <li>Verify the public-key signature, contained in {@code signatureFile}, and verify it 309 * against the entire {@code certificateFile}. 310 * <li>Parse {@code certificateFile} to get relevant information. 311 * <li>Check the serial number, contained in {@code certificateFile}, and skip the following 312 * steps if the serial number is not larger than the one previously stored. 313 * <li>Randomly choose a X509 certificate from the endpoint X509 certificates, contained in 314 * {@code certificateFile}, and validate it against the root certificate pre-installed 315 * in the OS and chosen by {@code rootCertificateAlias}. 316 * <li>Store the chosen X509 certificate and the serial in local database for later use. 317 * </ol> 318 * 319 * @param rootCertificateAlias the alias of a root certificate pre-installed in the OS 320 * @param certificateFile the binary content of the XML file containing a list of recovery 321 * service X509 certificates, and other metadata including the serial number 322 * @param signatureFile the binary content of the XML file containing the public-key signature 323 * of the entire certificate file, and a signer's X509 certificate 324 * @throws CertificateException if the given certificate files cannot be parsed or validated 325 * @throws InternalRecoveryServiceException if an unexpected error occurred in the recovery 326 * service. 327 */ 328 @RequiresPermission(android.Manifest.permission.RECOVER_KEYSTORE) 329 public void initRecoveryService( 330 @NonNull String rootCertificateAlias, @NonNull byte[] certificateFile, 331 @NonNull byte[] signatureFile) 332 throws CertificateException, InternalRecoveryServiceException { 333 try { 334 mBinder.initRecoveryServiceWithSigFile( 335 rootCertificateAlias, certificateFile, signatureFile); 336 } catch (RemoteException e) { 337 throw e.rethrowFromSystemServer(); 338 } catch (ServiceSpecificException e) { 339 if (e.errorCode == ERROR_BAD_CERTIFICATE_FORMAT 340 || e.errorCode == ERROR_INVALID_CERTIFICATE) { 341 throw new CertificateException(e.getMessage()); 342 } 343 throw wrapUnexpectedServiceSpecificException(e); 344 } 345 } 346 347 /** 348 * @deprecated Use {@link #getKeyChainSnapshot()} 349 */ 350 @Deprecated 351 @RequiresPermission(android.Manifest.permission.RECOVER_KEYSTORE) 352 public @Nullable KeyChainSnapshot getRecoveryData() throws InternalRecoveryServiceException { 353 return getKeyChainSnapshot(); 354 } 355 356 /** 357 * Returns data necessary to store all recoverable keys. Key material is 358 * encrypted with user secret and recovery public key. 359 * 360 * @return Data necessary to recover keystore or {@code null} if snapshot is not available. 361 * @throws InternalRecoveryServiceException if an unexpected error occurred in the recovery 362 * service. 363 */ 364 @RequiresPermission(android.Manifest.permission.RECOVER_KEYSTORE) 365 public @Nullable KeyChainSnapshot getKeyChainSnapshot() 366 throws InternalRecoveryServiceException { 367 try { 368 return mBinder.getKeyChainSnapshot(); 369 } catch (RemoteException e) { 370 throw e.rethrowFromSystemServer(); 371 } catch (ServiceSpecificException e) { 372 if (e.errorCode == ERROR_NO_SNAPSHOT_PENDING) { 373 return null; 374 } 375 throw wrapUnexpectedServiceSpecificException(e); 376 } 377 } 378 379 /** 380 * Sets a listener which notifies recovery agent that new recovery snapshot is available. {@link 381 * #getKeyChainSnapshot} can be used to get the snapshot. Note that every recovery agent can 382 * have at most one registered listener at any time. 383 * 384 * @param intent triggered when new snapshot is available. Unregisters listener if the value is 385 * {@code null}. 386 * @throws InternalRecoveryServiceException if an unexpected error occurred in the recovery 387 * service. 388 */ 389 @RequiresPermission(android.Manifest.permission.RECOVER_KEYSTORE) 390 public void setSnapshotCreatedPendingIntent(@Nullable PendingIntent intent) 391 throws InternalRecoveryServiceException { 392 try { 393 mBinder.setSnapshotCreatedPendingIntent(intent); 394 } catch (RemoteException e) { 395 throw e.rethrowFromSystemServer(); 396 } catch (ServiceSpecificException e) { 397 throw wrapUnexpectedServiceSpecificException(e); 398 } 399 } 400 401 /** 402 * Server parameters used to generate new recovery key blobs. This value will be included in 403 * {@code KeyChainSnapshot.getEncryptedRecoveryKeyBlob()}. The same value must be included 404 * in vaultParams {@link RecoverySession#start(CertPath, byte[], byte[], List)}. 405 * 406 * @param serverParams included in recovery key blob. 407 * @see #getKeyChainSnapshot 408 * @throws InternalRecoveryServiceException if an unexpected error occurred in the recovery 409 * service. 410 */ 411 @RequiresPermission(android.Manifest.permission.RECOVER_KEYSTORE) 412 public void setServerParams(@NonNull byte[] serverParams) 413 throws InternalRecoveryServiceException { 414 try { 415 mBinder.setServerParams(serverParams); 416 } catch (RemoteException e) { 417 throw e.rethrowFromSystemServer(); 418 } catch (ServiceSpecificException e) { 419 throw wrapUnexpectedServiceSpecificException(e); 420 } 421 } 422 423 /** 424 * @deprecated Use {@link #getAliases()}. 425 */ 426 @Deprecated 427 @RequiresPermission(android.Manifest.permission.RECOVER_KEYSTORE) 428 public List<String> getAliases(@Nullable String packageName) 429 throws InternalRecoveryServiceException { 430 return getAliases(); 431 } 432 433 /** 434 * Returns a list of aliases of keys belonging to the application. 435 */ 436 @RequiresPermission(android.Manifest.permission.RECOVER_KEYSTORE) 437 public @NonNull List<String> getAliases() throws InternalRecoveryServiceException { 438 try { 439 Map<String, Integer> allStatuses = mBinder.getRecoveryStatus(); 440 return new ArrayList<>(allStatuses.keySet()); 441 } catch (RemoteException e) { 442 throw e.rethrowFromSystemServer(); 443 } catch (ServiceSpecificException e) { 444 throw wrapUnexpectedServiceSpecificException(e); 445 } 446 } 447 448 /** 449 * @deprecated Use {@link #setRecoveryStatus(String, int)} 450 */ 451 @Deprecated 452 @RequiresPermission(android.Manifest.permission.RECOVER_KEYSTORE) 453 public void setRecoveryStatus( 454 @NonNull String packageName, String alias, int status) 455 throws NameNotFoundException, InternalRecoveryServiceException { 456 setRecoveryStatus(alias, status); 457 } 458 459 /** 460 * Sets the recovery status for given key. It is used to notify the keystore that the key was 461 * successfully stored on the server or that there was an error. An application can check this 462 * value using {@link #getRecoveryStatus(String, String)}. 463 * 464 * @param alias The alias of the key whose status to set. 465 * @param status The status of the key. One of {@link #RECOVERY_STATUS_SYNCED}, 466 * {@link #RECOVERY_STATUS_SYNC_IN_PROGRESS} or {@link #RECOVERY_STATUS_PERMANENT_FAILURE}. 467 * @throws InternalRecoveryServiceException if an unexpected error occurred in the recovery 468 * service. 469 */ 470 @RequiresPermission(android.Manifest.permission.RECOVER_KEYSTORE) 471 public void setRecoveryStatus(@NonNull String alias, int status) 472 throws InternalRecoveryServiceException { 473 try { 474 mBinder.setRecoveryStatus(alias, status); 475 } catch (RemoteException e) { 476 throw e.rethrowFromSystemServer(); 477 } catch (ServiceSpecificException e) { 478 throw wrapUnexpectedServiceSpecificException(e); 479 } 480 } 481 482 /** 483 * @deprecated Use {@link #getRecoveryStatus(String)}. 484 */ 485 @Deprecated 486 @RequiresPermission(android.Manifest.permission.RECOVER_KEYSTORE) 487 public int getRecoveryStatus(String packageName, String alias) 488 throws InternalRecoveryServiceException { 489 return getRecoveryStatus(alias); 490 } 491 492 /** 493 * Returns the recovery status for the key with the given {@code alias}. 494 * 495 * <ul> 496 * <li>{@link #RECOVERY_STATUS_SYNCED} 497 * <li>{@link #RECOVERY_STATUS_SYNC_IN_PROGRESS} 498 * <li>{@link #RECOVERY_STATUS_PERMANENT_FAILURE} 499 * </ul> 500 * 501 * @see #setRecoveryStatus(String, int) 502 * @throws InternalRecoveryServiceException if an unexpected error occurred in the recovery 503 * service. 504 */ 505 @RequiresPermission(android.Manifest.permission.RECOVER_KEYSTORE) 506 public int getRecoveryStatus(@NonNull String alias) throws InternalRecoveryServiceException { 507 try { 508 Map<String, Integer> allStatuses = mBinder.getRecoveryStatus(); 509 Integer status = allStatuses.get(alias); 510 if (status == null) { 511 return RecoveryController.RECOVERY_STATUS_PERMANENT_FAILURE; 512 } else { 513 return status; 514 } 515 } catch (RemoteException e) { 516 throw e.rethrowFromSystemServer(); 517 } catch (ServiceSpecificException e) { 518 throw wrapUnexpectedServiceSpecificException(e); 519 } 520 } 521 522 /** 523 * Specifies a set of secret types used for end-to-end keystore encryption. Knowing all of them 524 * is necessary to recover data. 525 * 526 * @param secretTypes {@link KeyChainProtectionParams#TYPE_LOCKSCREEN} 527 * @throws InternalRecoveryServiceException if an unexpected error occurred in the recovery 528 * service. 529 */ 530 @RequiresPermission(android.Manifest.permission.RECOVER_KEYSTORE) 531 public void setRecoverySecretTypes( 532 @NonNull @KeyChainProtectionParams.UserSecretType int[] secretTypes) 533 throws InternalRecoveryServiceException { 534 try { 535 mBinder.setRecoverySecretTypes(secretTypes); 536 } catch (RemoteException e) { 537 throw e.rethrowFromSystemServer(); 538 } catch (ServiceSpecificException e) { 539 throw wrapUnexpectedServiceSpecificException(e); 540 } 541 } 542 543 /** 544 * Defines a set of secret types used for end-to-end keystore encryption. Knowing all of them is 545 * necessary to generate KeyChainSnapshot. 546 * 547 * @return list of recovery secret types 548 * @see KeyChainSnapshot 549 * @throws InternalRecoveryServiceException if an unexpected error occurred in the recovery 550 * service. 551 */ 552 @RequiresPermission(android.Manifest.permission.RECOVER_KEYSTORE) 553 public @NonNull @KeyChainProtectionParams.UserSecretType int[] getRecoverySecretTypes() 554 throws InternalRecoveryServiceException { 555 try { 556 return mBinder.getRecoverySecretTypes(); 557 } catch (RemoteException e) { 558 throw e.rethrowFromSystemServer(); 559 } catch (ServiceSpecificException e) { 560 throw wrapUnexpectedServiceSpecificException(e); 561 } 562 } 563 564 /** 565 * Deprecated. 566 * Generates a AES256/GCM/NoPADDING key called {@code alias} and loads it into the recoverable 567 * key store. Returns the raw material of the key. 568 * 569 * @param alias The key alias. 570 * @param account The account associated with the key 571 * @throws InternalRecoveryServiceException if an unexpected error occurred in the recovery 572 * service. 573 * @throws LockScreenRequiredException if the user has not set a lock screen. This is required 574 * to generate recoverable keys, as the snapshots are encrypted using a key derived from the 575 * lock screen. 576 */ 577 @RequiresPermission(android.Manifest.permission.RECOVER_KEYSTORE) 578 public byte[] generateAndStoreKey(@NonNull String alias, byte[] account) 579 throws InternalRecoveryServiceException, LockScreenRequiredException { 580 try { 581 return mBinder.generateAndStoreKey(alias); 582 } catch (RemoteException e) { 583 throw e.rethrowFromSystemServer(); 584 } catch (ServiceSpecificException e) { 585 if (e.errorCode == ERROR_INSECURE_USER) { 586 throw new LockScreenRequiredException(e.getMessage()); 587 } 588 throw wrapUnexpectedServiceSpecificException(e); 589 } 590 } 591 592 /** 593 * @deprecated Use {@link #generateKey(String)}. 594 */ 595 @Deprecated 596 @RequiresPermission(android.Manifest.permission.RECOVER_KEYSTORE) 597 public Key generateKey(@NonNull String alias, byte[] account) 598 throws InternalRecoveryServiceException, LockScreenRequiredException { 599 return generateKey(alias); 600 } 601 602 /** 603 * Generates a recoverable key with the given {@code alias}. 604 * 605 * @throws InternalRecoveryServiceException if an unexpected error occurred in the recovery 606 * service. 607 * @throws LockScreenRequiredException if the user does not have a lock screen set. A lock 608 * screen is required to generate recoverable keys. 609 */ 610 @RequiresPermission(android.Manifest.permission.RECOVER_KEYSTORE) 611 public @NonNull Key generateKey(@NonNull String alias) throws InternalRecoveryServiceException, 612 LockScreenRequiredException { 613 try { 614 String grantAlias = mBinder.generateKey(alias); 615 if (grantAlias == null) { 616 throw new InternalRecoveryServiceException("null grant alias"); 617 } 618 return getKeyFromGrant(grantAlias); 619 } catch (RemoteException e) { 620 throw e.rethrowFromSystemServer(); 621 } catch (UnrecoverableKeyException e) { 622 throw new InternalRecoveryServiceException("Failed to get key from keystore", e); 623 } catch (ServiceSpecificException e) { 624 if (e.errorCode == ERROR_INSECURE_USER) { 625 throw new LockScreenRequiredException(e.getMessage()); 626 } 627 throw wrapUnexpectedServiceSpecificException(e); 628 } 629 } 630 631 /** 632 * Imports a 256-bit recoverable AES key with the given {@code alias} and the raw bytes {@code 633 * keyBytes}. 634 * 635 * @throws InternalRecoveryServiceException if an unexpected error occurred in the recovery 636 * service. 637 * @throws LockScreenRequiredException if the user does not have a lock screen set. A lock 638 * screen is required to generate recoverable keys. 639 * 640 */ 641 @RequiresPermission(android.Manifest.permission.RECOVER_KEYSTORE) 642 public @NonNull Key importKey(@NonNull String alias, @NonNull byte[] keyBytes) 643 throws InternalRecoveryServiceException, LockScreenRequiredException { 644 try { 645 String grantAlias = mBinder.importKey(alias, keyBytes); 646 if (grantAlias == null) { 647 throw new InternalRecoveryServiceException("Null grant alias"); 648 } 649 return getKeyFromGrant(grantAlias); 650 } catch (RemoteException e) { 651 throw e.rethrowFromSystemServer(); 652 } catch (UnrecoverableKeyException e) { 653 throw new InternalRecoveryServiceException("Failed to get key from keystore", e); 654 } catch (ServiceSpecificException e) { 655 if (e.errorCode == ERROR_INSECURE_USER) { 656 throw new LockScreenRequiredException(e.getMessage()); 657 } 658 throw wrapUnexpectedServiceSpecificException(e); 659 } 660 } 661 662 /** 663 * Gets a key called {@code alias} from the recoverable key store. 664 * 665 * @param alias The key alias. 666 * @return The key. 667 * @throws InternalRecoveryServiceException if an unexpected error occurred in the recovery 668 * service. 669 * @throws UnrecoverableKeyException if key is permanently invalidated or not found. 670 */ 671 @RequiresPermission(android.Manifest.permission.RECOVER_KEYSTORE) 672 public @Nullable Key getKey(@NonNull String alias) 673 throws InternalRecoveryServiceException, UnrecoverableKeyException { 674 try { 675 String grantAlias = mBinder.getKey(alias); 676 if (grantAlias == null || "".equals(grantAlias)) { 677 return null; 678 } 679 return getKeyFromGrant(grantAlias); 680 } catch (RemoteException e) { 681 throw e.rethrowFromSystemServer(); 682 } catch (ServiceSpecificException e) { 683 throw wrapUnexpectedServiceSpecificException(e); 684 } 685 } 686 687 /** 688 * Returns the key with the given {@code grantAlias}. 689 */ 690 @NonNull Key getKeyFromGrant(@NonNull String grantAlias) throws UnrecoverableKeyException { 691 return AndroidKeyStoreProvider.loadAndroidKeyStoreKeyFromKeystore( 692 mKeyStore, 693 grantAlias, 694 KeyStore.UID_SELF); 695 } 696 697 /** 698 * Removes a key called {@code alias} from the recoverable key store. 699 * 700 * @param alias The key alias. 701 * @throws InternalRecoveryServiceException if an unexpected error occurred in the recovery 702 * service. 703 */ 704 @RequiresPermission(android.Manifest.permission.RECOVER_KEYSTORE) 705 public void removeKey(@NonNull String alias) throws InternalRecoveryServiceException { 706 try { 707 mBinder.removeKey(alias); 708 } catch (RemoteException e) { 709 throw e.rethrowFromSystemServer(); 710 } catch (ServiceSpecificException e) { 711 throw wrapUnexpectedServiceSpecificException(e); 712 } 713 } 714 715 /** 716 * Returns a new {@link RecoverySession}. 717 * 718 * <p>A recovery session is required to restore keys from a remote store. 719 */ 720 @RequiresPermission(android.Manifest.permission.RECOVER_KEYSTORE) 721 public @NonNull RecoverySession createRecoverySession() { 722 return RecoverySession.newInstance(this); 723 } 724 725 @RequiresPermission(android.Manifest.permission.RECOVER_KEYSTORE) 726 public @NonNull Map<String, X509Certificate> getRootCertificates() { 727 return TrustedRootCertificates.getRootCertificates(); 728 } 729 730 InternalRecoveryServiceException wrapUnexpectedServiceSpecificException( 731 ServiceSpecificException e) { 732 if (e.errorCode == ERROR_SERVICE_INTERNAL_ERROR) { 733 return new InternalRecoveryServiceException(e.getMessage()); 734 } 735 736 // Should never happen. If it does, it's a bug, and we need to update how the method that 737 // called this throws its exceptions. 738 return new InternalRecoveryServiceException("Unexpected error code for method: " 739 + e.errorCode, e); 740 } 741} 742