RecoveryController.java revision 50bc7e42d73c9ca8d77dcd538619c6d6eeaf6dea
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 {@code android.permission.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        throw new CertificateException("Deprecated initRecoveryService method called");
289    }
290
291    /**
292     * Initializes the recovery service for the calling application. The detailed steps should be:
293     * <ol>
294     *     <li>Parse {@code signatureFile} to get relevant information.
295     *     <li>Validate the signer's X509 certificate, contained in {@code signatureFile}, against
296     *         the root certificate pre-installed in the OS and chosen by {@code
297     *         rootCertificateAlias}.
298     *     <li>Verify the public-key signature, contained in {@code signatureFile}, and verify it
299     *         against the entire {@code certificateFile}.
300     *     <li>Parse {@code certificateFile} to get relevant information.
301     *     <li>Check the serial number, contained in {@code certificateFile}, and skip the following
302     *         steps if the serial number is not larger than the one previously stored.
303     *     <li>Randomly choose a X509 certificate from the endpoint X509 certificates, contained in
304     *         {@code certificateFile}, and validate it against the root certificate pre-installed
305     *         in the OS and chosen by {@code rootCertificateAlias}.
306     *     <li>Store the chosen X509 certificate and the serial in local database for later use.
307     * </ol>
308     *
309     * @param rootCertificateAlias the alias of a root certificate pre-installed in the OS
310     * @param certificateFile the binary content of the XML file containing a list of recovery
311     *     service X509 certificates, and other metadata including the serial number
312     * @param signatureFile the binary content of the XML file containing the public-key signature
313     *     of the entire certificate file, and a signer's X509 certificate
314     * @throws CertificateException if the given certificate files cannot be parsed or validated
315     * @throws InternalRecoveryServiceException if an unexpected error occurred in the recovery
316     *     service.
317     */
318    @RequiresPermission(android.Manifest.permission.RECOVER_KEYSTORE)
319    public void initRecoveryService(
320            @NonNull String rootCertificateAlias, @NonNull byte[] certificateFile,
321            @NonNull byte[] signatureFile)
322            throws CertificateException, InternalRecoveryServiceException {
323        try {
324            mBinder.initRecoveryServiceWithSigFile(
325                    rootCertificateAlias, certificateFile, signatureFile);
326        } catch (RemoteException e) {
327            throw e.rethrowFromSystemServer();
328        } catch (ServiceSpecificException e) {
329            if (e.errorCode == ERROR_BAD_CERTIFICATE_FORMAT
330                    || e.errorCode == ERROR_INVALID_CERTIFICATE) {
331                throw new CertificateException("Invalid certificate for recovery service", e);
332            }
333            throw wrapUnexpectedServiceSpecificException(e);
334        }
335    }
336
337    /**
338     * @deprecated Use {@link #getKeyChainSnapshot()}
339     */
340    @Deprecated
341    @RequiresPermission(android.Manifest.permission.RECOVER_KEYSTORE)
342    public @Nullable KeyChainSnapshot getRecoveryData() throws InternalRecoveryServiceException {
343        return getKeyChainSnapshot();
344    }
345
346    /**
347     * Returns data necessary to store all recoverable keys. Key material is
348     * encrypted with user secret and recovery public key.
349     *
350     * @return Data necessary to recover keystore or {@code null} if snapshot is not available.
351     * @throws InternalRecoveryServiceException if an unexpected error occurred in the recovery
352     *     service.
353     */
354    @RequiresPermission(android.Manifest.permission.RECOVER_KEYSTORE)
355    public @Nullable KeyChainSnapshot getKeyChainSnapshot()
356            throws InternalRecoveryServiceException {
357        try {
358            return mBinder.getKeyChainSnapshot();
359        } catch (RemoteException e) {
360            throw e.rethrowFromSystemServer();
361        } catch (ServiceSpecificException e) {
362            if (e.errorCode == ERROR_NO_SNAPSHOT_PENDING) {
363                return null;
364            }
365            throw wrapUnexpectedServiceSpecificException(e);
366        }
367    }
368
369    /**
370     * Sets a listener which notifies recovery agent that new recovery snapshot is available. {@link
371     * #getKeyChainSnapshot} can be used to get the snapshot. Note that every recovery agent can
372     * have at most one registered listener at any time.
373     *
374     * @param intent triggered when new snapshot is available. Unregisters listener if the value is
375     *     {@code null}.
376     * @throws InternalRecoveryServiceException if an unexpected error occurred in the recovery
377     *     service.
378     */
379    @RequiresPermission(android.Manifest.permission.RECOVER_KEYSTORE)
380    public void setSnapshotCreatedPendingIntent(@Nullable PendingIntent intent)
381            throws InternalRecoveryServiceException {
382        try {
383            mBinder.setSnapshotCreatedPendingIntent(intent);
384        } catch (RemoteException e) {
385            throw e.rethrowFromSystemServer();
386        } catch (ServiceSpecificException e) {
387            throw wrapUnexpectedServiceSpecificException(e);
388        }
389    }
390
391    /**
392     * Server parameters used to generate new recovery key blobs. This value will be included in
393     * {@code KeyChainSnapshot.getEncryptedRecoveryKeyBlob()}. The same value must be included
394     * in vaultParams {@link RecoverySession#start(CertPath, byte[], byte[], List)}.
395     *
396     * @param serverParams included in recovery key blob.
397     * @see #getKeyChainSnapshot
398     * @throws InternalRecoveryServiceException if an unexpected error occurred in the recovery
399     *     service.
400     */
401    @RequiresPermission(android.Manifest.permission.RECOVER_KEYSTORE)
402    public void setServerParams(@NonNull byte[] serverParams)
403            throws InternalRecoveryServiceException {
404        try {
405            mBinder.setServerParams(serverParams);
406        } catch (RemoteException e) {
407            throw e.rethrowFromSystemServer();
408        } catch (ServiceSpecificException e) {
409            throw wrapUnexpectedServiceSpecificException(e);
410        }
411    }
412
413    /**
414     * @deprecated Use {@link #getAliases()}.
415     */
416    @Deprecated
417    @RequiresPermission(android.Manifest.permission.RECOVER_KEYSTORE)
418    public List<String> getAliases(@Nullable String packageName)
419            throws InternalRecoveryServiceException {
420        return getAliases();
421    }
422
423    /**
424     * Returns a list of aliases of keys belonging to the application.
425     */
426    @RequiresPermission(android.Manifest.permission.RECOVER_KEYSTORE)
427    public @NonNull List<String> getAliases() throws InternalRecoveryServiceException {
428        try {
429            Map<String, Integer> allStatuses = mBinder.getRecoveryStatus();
430            return new ArrayList<>(allStatuses.keySet());
431        } catch (RemoteException e) {
432            throw e.rethrowFromSystemServer();
433        } catch (ServiceSpecificException e) {
434            throw wrapUnexpectedServiceSpecificException(e);
435        }
436    }
437
438    /**
439     * @deprecated Use {@link #setRecoveryStatus(String, int)}
440     */
441    @Deprecated
442    @RequiresPermission(android.Manifest.permission.RECOVER_KEYSTORE)
443    public void setRecoveryStatus(
444            @NonNull String packageName, String alias, int status)
445            throws NameNotFoundException, InternalRecoveryServiceException {
446        setRecoveryStatus(alias, status);
447    }
448
449    /**
450     * Sets the recovery status for given key. It is used to notify the keystore that the key was
451     * successfully stored on the server or that there was an error. An application can check this
452     * value using {@link #getRecoveryStatus(String, String)}.
453     *
454     * @param alias The alias of the key whose status to set.
455     * @param status The status of the key. One of {@link #RECOVERY_STATUS_SYNCED},
456     *     {@link #RECOVERY_STATUS_SYNC_IN_PROGRESS} or {@link #RECOVERY_STATUS_PERMANENT_FAILURE}.
457     * @throws InternalRecoveryServiceException if an unexpected error occurred in the recovery
458     *     service.
459     */
460    @RequiresPermission(android.Manifest.permission.RECOVER_KEYSTORE)
461    public void setRecoveryStatus(@NonNull String alias, int status)
462            throws InternalRecoveryServiceException {
463        try {
464            mBinder.setRecoveryStatus(alias, status);
465        } catch (RemoteException e) {
466            throw e.rethrowFromSystemServer();
467        } catch (ServiceSpecificException e) {
468            throw wrapUnexpectedServiceSpecificException(e);
469        }
470    }
471
472    /**
473     * @deprecated Use {@link #getRecoveryStatus(String)}.
474     */
475    @Deprecated
476    @RequiresPermission(android.Manifest.permission.RECOVER_KEYSTORE)
477    public int getRecoveryStatus(String packageName, String alias)
478            throws InternalRecoveryServiceException {
479        return getRecoveryStatus(alias);
480    }
481
482    /**
483     * Returns the recovery status for the key with the given {@code alias}.
484     *
485     * <ul>
486     *   <li>{@link #RECOVERY_STATUS_SYNCED}
487     *   <li>{@link #RECOVERY_STATUS_SYNC_IN_PROGRESS}
488     *   <li>{@link #RECOVERY_STATUS_PERMANENT_FAILURE}
489     * </ul>
490     *
491     * @see #setRecoveryStatus(String, int)
492     * @throws InternalRecoveryServiceException if an unexpected error occurred in the recovery
493     *     service.
494     */
495    @RequiresPermission(android.Manifest.permission.RECOVER_KEYSTORE)
496    public int getRecoveryStatus(@NonNull String alias) throws InternalRecoveryServiceException {
497        try {
498            Map<String, Integer> allStatuses = mBinder.getRecoveryStatus();
499            Integer status = allStatuses.get(alias);
500            if (status == null) {
501                return RecoveryController.RECOVERY_STATUS_PERMANENT_FAILURE;
502            } else {
503                return status;
504            }
505        } catch (RemoteException e) {
506            throw e.rethrowFromSystemServer();
507        } catch (ServiceSpecificException e) {
508            throw wrapUnexpectedServiceSpecificException(e);
509        }
510    }
511
512    /**
513     * Specifies a set of secret types used for end-to-end keystore encryption. Knowing all of them
514     * is necessary to recover data.
515     *
516     * @param secretTypes {@link KeyChainProtectionParams#TYPE_LOCKSCREEN}
517     * @throws InternalRecoveryServiceException if an unexpected error occurred in the recovery
518     *     service.
519     */
520    @RequiresPermission(android.Manifest.permission.RECOVER_KEYSTORE)
521    public void setRecoverySecretTypes(
522            @NonNull @KeyChainProtectionParams.UserSecretType int[] secretTypes)
523            throws InternalRecoveryServiceException {
524        try {
525            mBinder.setRecoverySecretTypes(secretTypes);
526        } catch (RemoteException e) {
527            throw e.rethrowFromSystemServer();
528        } catch (ServiceSpecificException e) {
529            throw wrapUnexpectedServiceSpecificException(e);
530        }
531    }
532
533    /**
534     * Defines a set of secret types used for end-to-end keystore encryption. Knowing all of them is
535     * necessary to generate KeyChainSnapshot.
536     *
537     * @return list of recovery secret types
538     * @see KeyChainSnapshot
539     * @throws InternalRecoveryServiceException if an unexpected error occurred in the recovery
540     *     service.
541     */
542    @RequiresPermission(android.Manifest.permission.RECOVER_KEYSTORE)
543    public @NonNull @KeyChainProtectionParams.UserSecretType int[] getRecoverySecretTypes()
544            throws InternalRecoveryServiceException {
545        try {
546            return mBinder.getRecoverySecretTypes();
547        } catch (RemoteException e) {
548            throw e.rethrowFromSystemServer();
549        } catch (ServiceSpecificException e) {
550            throw wrapUnexpectedServiceSpecificException(e);
551        }
552    }
553
554    /**
555     * Deprecated.
556     * Generates a AES256/GCM/NoPADDING key called {@code alias} and loads it into the recoverable
557     * key store. Returns the raw material of the key.
558     *
559     * @param alias The key alias.
560     * @param account The account associated with the key
561     * @throws InternalRecoveryServiceException if an unexpected error occurred in the recovery
562     *     service.
563     * @throws LockScreenRequiredException if the user has not set a lock screen. This is required
564     *     to generate recoverable keys, as the snapshots are encrypted using a key derived from the
565     *     lock screen.
566     */
567    @RequiresPermission(android.Manifest.permission.RECOVER_KEYSTORE)
568    public byte[] generateAndStoreKey(@NonNull String alias, byte[] account)
569            throws InternalRecoveryServiceException, LockScreenRequiredException {
570        throw new UnsupportedOperationException("Operation is not supported, use generateKey");
571    }
572
573    /**
574     * @deprecated Use {@link #generateKey(String)}.
575     */
576    @Deprecated
577    @RequiresPermission(android.Manifest.permission.RECOVER_KEYSTORE)
578    public Key generateKey(@NonNull String alias, byte[] account)
579            throws InternalRecoveryServiceException, LockScreenRequiredException {
580        return generateKey(alias);
581    }
582
583    /**
584     * Generates a recoverable key with the given {@code alias}.
585     *
586     * @throws InternalRecoveryServiceException if an unexpected error occurred in the recovery
587     *     service.
588     * @throws LockScreenRequiredException if the user does not have a lock screen set. A lock
589     *     screen is required to generate recoverable keys.
590     */
591    @RequiresPermission(android.Manifest.permission.RECOVER_KEYSTORE)
592    public @NonNull Key generateKey(@NonNull String alias) throws InternalRecoveryServiceException,
593            LockScreenRequiredException {
594        try {
595            String grantAlias = mBinder.generateKey(alias);
596            if (grantAlias == null) {
597                throw new InternalRecoveryServiceException("null grant alias");
598            }
599            return getKeyFromGrant(grantAlias);
600        } catch (RemoteException e) {
601            throw e.rethrowFromSystemServer();
602        } catch (UnrecoverableKeyException e) {
603            throw new InternalRecoveryServiceException("Failed to get key from keystore", e);
604        } catch (ServiceSpecificException e) {
605            if (e.errorCode == ERROR_INSECURE_USER) {
606                throw new LockScreenRequiredException(e.getMessage());
607            }
608            throw wrapUnexpectedServiceSpecificException(e);
609        }
610    }
611
612    /**
613     * Imports a 256-bit recoverable AES key with the given {@code alias} and the raw bytes {@code
614     * keyBytes}.
615     *
616     * @throws InternalRecoveryServiceException if an unexpected error occurred in the recovery
617     *     service.
618     * @throws LockScreenRequiredException if the user does not have a lock screen set. A lock
619     *     screen is required to generate recoverable keys.
620     *
621     */
622    @RequiresPermission(android.Manifest.permission.RECOVER_KEYSTORE)
623    public @NonNull Key importKey(@NonNull String alias, @NonNull byte[] keyBytes)
624            throws InternalRecoveryServiceException, LockScreenRequiredException {
625        try {
626            String grantAlias = mBinder.importKey(alias, keyBytes);
627            if (grantAlias == null) {
628                throw new InternalRecoveryServiceException("Null grant alias");
629            }
630            return getKeyFromGrant(grantAlias);
631        } catch (RemoteException e) {
632            throw e.rethrowFromSystemServer();
633        } catch (UnrecoverableKeyException e) {
634            throw new InternalRecoveryServiceException("Failed to get key from keystore", e);
635        } catch (ServiceSpecificException e) {
636            if (e.errorCode == ERROR_INSECURE_USER) {
637                throw new LockScreenRequiredException(e.getMessage());
638            }
639            throw wrapUnexpectedServiceSpecificException(e);
640        }
641    }
642
643    /**
644     * Gets a key called {@code alias} from the recoverable key store.
645     *
646     * @param alias The key alias.
647     * @return The key.
648     * @throws InternalRecoveryServiceException if an unexpected error occurred in the recovery
649     *     service.
650     * @throws UnrecoverableKeyException if key is permanently invalidated or not found.
651     */
652    @RequiresPermission(android.Manifest.permission.RECOVER_KEYSTORE)
653    public @Nullable Key getKey(@NonNull String alias)
654            throws InternalRecoveryServiceException, UnrecoverableKeyException {
655        try {
656            String grantAlias = mBinder.getKey(alias);
657            if (grantAlias == null || "".equals(grantAlias)) {
658                return null;
659            }
660            return getKeyFromGrant(grantAlias);
661        } catch (RemoteException e) {
662            throw e.rethrowFromSystemServer();
663        } catch (ServiceSpecificException e) {
664            throw wrapUnexpectedServiceSpecificException(e);
665        }
666    }
667
668    /**
669     * Returns the key with the given {@code grantAlias}.
670     */
671    @NonNull Key getKeyFromGrant(@NonNull String grantAlias) throws UnrecoverableKeyException {
672        return AndroidKeyStoreProvider.loadAndroidKeyStoreKeyFromKeystore(
673                mKeyStore,
674                grantAlias,
675                KeyStore.UID_SELF);
676    }
677
678    /**
679     * Removes a key called {@code alias} from the recoverable key store.
680     *
681     * @param alias The key alias.
682     * @throws InternalRecoveryServiceException if an unexpected error occurred in the recovery
683     *     service.
684     */
685    @RequiresPermission(android.Manifest.permission.RECOVER_KEYSTORE)
686    public void removeKey(@NonNull String alias) throws InternalRecoveryServiceException {
687        try {
688            mBinder.removeKey(alias);
689        } catch (RemoteException e) {
690            throw e.rethrowFromSystemServer();
691        } catch (ServiceSpecificException e) {
692            throw wrapUnexpectedServiceSpecificException(e);
693        }
694    }
695
696    /**
697     * Returns a new {@link RecoverySession}.
698     *
699     * <p>A recovery session is required to restore keys from a remote store.
700     */
701    @RequiresPermission(android.Manifest.permission.RECOVER_KEYSTORE)
702    public @NonNull RecoverySession createRecoverySession() {
703        return RecoverySession.newInstance(this);
704    }
705
706    @RequiresPermission(android.Manifest.permission.RECOVER_KEYSTORE)
707    public @NonNull Map<String, X509Certificate> getRootCertificates() {
708        return TrustedRootCertificates.getRootCertificates();
709    }
710
711    InternalRecoveryServiceException wrapUnexpectedServiceSpecificException(
712            ServiceSpecificException e) {
713        if (e.errorCode == ERROR_SERVICE_INTERNAL_ERROR) {
714            return new InternalRecoveryServiceException(e.getMessage());
715        }
716
717        // Should never happen. If it does, it's a bug, and we need to update how the method that
718        // called this throws its exceptions.
719        return new InternalRecoveryServiceException("Unexpected error code for method: "
720                + e.errorCode, e);
721    }
722}
723