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