KeySyncTask.java revision 7d8c78a2c88a4898a63b918ab8b974aecd7b165b
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 com.android.server.locksettings.recoverablekeystore;
18
19import static android.security.keystore.RecoveryMetadata.TYPE_LOCKSCREEN;
20
21import android.annotation.NonNull;
22import android.annotation.Nullable;
23import android.content.Context;
24import android.security.keystore.KeyDerivationParams;
25import android.security.keystore.EntryRecoveryData;
26import android.security.keystore.RecoveryData;
27import android.security.keystore.RecoveryMetadata;
28import android.util.Log;
29
30import com.android.internal.annotations.VisibleForTesting;
31import com.android.internal.util.ArrayUtils;
32import com.android.internal.widget.LockPatternUtils;
33import com.android.server.locksettings.recoverablekeystore.storage.RecoverableKeyStoreDb;
34import com.android.server.locksettings.recoverablekeystore.storage.RecoverySnapshotStorage;
35
36import java.nio.ByteBuffer;
37import java.nio.ByteOrder;
38import java.nio.charset.StandardCharsets;
39import java.security.GeneralSecurityException;
40import java.security.InvalidKeyException;
41import java.security.KeyStoreException;
42import java.security.MessageDigest;
43import java.security.NoSuchAlgorithmException;
44import java.security.PublicKey;
45import java.security.SecureRandom;
46import java.security.UnrecoverableKeyException;
47import java.util.ArrayList;
48import java.util.List;
49import java.util.Map;
50
51import javax.crypto.KeyGenerator;
52import javax.crypto.NoSuchPaddingException;
53import javax.crypto.SecretKey;
54
55/**
56 * Task to sync application keys to a remote vault service.
57 *
58 * @hide
59 */
60public class KeySyncTask implements Runnable {
61    private static final String TAG = "KeySyncTask";
62
63    private static final String RECOVERY_KEY_ALGORITHM = "AES";
64    private static final int RECOVERY_KEY_SIZE_BITS = 256;
65    private static final int SALT_LENGTH_BYTES = 16;
66    private static final int LENGTH_PREFIX_BYTES = Integer.BYTES;
67    private static final String LOCK_SCREEN_HASH_ALGORITHM = "SHA-256";
68    private static final int TRUSTED_HARDWARE_MAX_ATTEMPTS = 10;
69
70    private final RecoverableKeyStoreDb mRecoverableKeyStoreDb;
71    private final int mUserId;
72    private final int mCredentialType;
73    private final String mCredential;
74    private final boolean mCredentialUpdated;
75    private final PlatformKeyManager.Factory mPlatformKeyManagerFactory;
76    private final RecoverySnapshotStorage mRecoverySnapshotStorage;
77    private final RecoverySnapshotListenersStorage mSnapshotListenersStorage;
78
79    public static KeySyncTask newInstance(
80            Context context,
81            RecoverableKeyStoreDb recoverableKeyStoreDb,
82            RecoverySnapshotStorage snapshotStorage,
83            RecoverySnapshotListenersStorage recoverySnapshotListenersStorage,
84            int userId,
85            int credentialType,
86            String credential,
87            boolean credentialUpdated
88    ) throws NoSuchAlgorithmException, KeyStoreException, InsecureUserException {
89        return new KeySyncTask(
90                recoverableKeyStoreDb,
91                snapshotStorage,
92                recoverySnapshotListenersStorage,
93                userId,
94                credentialType,
95                credential,
96                credentialUpdated,
97                () -> PlatformKeyManager.getInstance(context, recoverableKeyStoreDb));
98    }
99
100    /**
101     * A new task.
102     *
103     * @param recoverableKeyStoreDb Database where the keys are stored.
104     * @param userId The uid of the user whose profile has been unlocked.
105     * @param credentialType The type of credential as defined in {@code LockPatternUtils}
106     * @param credential The credential, encoded as a {@link String}.
107     * @param credentialUpdated signals weather credentials were updated.
108     * @param platformKeyManagerFactory Instantiates a {@link PlatformKeyManager} for the user.
109     *     This is a factory to enable unit testing, as otherwise it would be impossible to test
110     *     without a screen unlock occurring!
111     */
112    @VisibleForTesting
113    KeySyncTask(
114            RecoverableKeyStoreDb recoverableKeyStoreDb,
115            RecoverySnapshotStorage snapshotStorage,
116            RecoverySnapshotListenersStorage recoverySnapshotListenersStorage,
117            int userId,
118            int credentialType,
119            String credential,
120            boolean credentialUpdated,
121            PlatformKeyManager.Factory platformKeyManagerFactory) {
122        mSnapshotListenersStorage = recoverySnapshotListenersStorage;
123        mRecoverableKeyStoreDb = recoverableKeyStoreDb;
124        mUserId = userId;
125        mCredentialType = credentialType;
126        mCredential = credential;
127        mCredentialUpdated = credentialUpdated;
128        mPlatformKeyManagerFactory = platformKeyManagerFactory;
129        mRecoverySnapshotStorage = snapshotStorage;
130    }
131
132    @Override
133    public void run() {
134        try {
135            // Only one task is active If user unlocks phone many times in a short time interval.
136            synchronized(KeySyncTask.class) {
137                syncKeys();
138            }
139        } catch (Exception e) {
140            Log.e(TAG, "Unexpected exception thrown during KeySyncTask", e);
141        }
142    }
143
144    private void syncKeys() {
145        if (mCredentialType == LockPatternUtils.CREDENTIAL_TYPE_NONE) {
146            // Application keys for the user will not be available for sync.
147            Log.w(TAG, "Credentials are not set for user " + mUserId);
148            return;
149        }
150
151        List<Integer> recoveryAgents = mRecoverableKeyStoreDb.getRecoveryAgents(mUserId);
152        for (int uid : recoveryAgents) {
153            syncKeysForAgent(uid);
154        }
155        if (recoveryAgents.isEmpty()) {
156            Log.w(TAG, "No recovery agent initialized for user " + mUserId);
157        }
158    }
159
160    private void syncKeysForAgent(int recoveryAgentUid) {
161        if (!shoudCreateSnapshot(recoveryAgentUid)) {
162            Log.d(TAG, "Key sync not needed.");
163            return;
164        }
165
166        if (!mSnapshotListenersStorage.hasListener(recoveryAgentUid)) {
167            Log.w(TAG, "No pending intent registered for recovery agent " + recoveryAgentUid);
168            return;
169        }
170
171        PublicKey publicKey = mRecoverableKeyStoreDb.getRecoveryServicePublicKey(mUserId,
172                recoveryAgentUid);
173        if (publicKey == null) {
174            Log.w(TAG, "Not initialized for KeySync: no public key set. Cancelling task.");
175            return;
176        }
177
178        byte[] deviceId = mRecoverableKeyStoreDb.getServerParams(mUserId, recoveryAgentUid);
179        if (deviceId == null) {
180            Log.w(TAG, "No device ID set for user " + mUserId);
181            return;
182        }
183
184        byte[] salt = generateSalt();
185        byte[] localLskfHash = hashCredentials(salt, mCredential);
186
187        Map<String, SecretKey> rawKeys;
188        try {
189            rawKeys = getKeysToSync(recoveryAgentUid);
190        } catch (GeneralSecurityException e) {
191            Log.e(TAG, "Failed to load recoverable keys for sync", e);
192            return;
193        } catch (InsecureUserException e) {
194            Log.wtf(TAG, "A screen unlock triggered the key sync flow, so user must have "
195                    + "lock screen. This should be impossible.", e);
196            return;
197        } catch (BadPlatformKeyException e) {
198            Log.wtf(TAG, "Loaded keys for same generation ID as platform key, so "
199                    + "BadPlatformKeyException should be impossible.", e);
200            return;
201        }
202
203        SecretKey recoveryKey;
204        try {
205            recoveryKey = generateRecoveryKey();
206        } catch (NoSuchAlgorithmException e) {
207            Log.wtf("AES should never be unavailable", e);
208            return;
209        }
210
211        Map<String, byte[]> encryptedApplicationKeys;
212        try {
213            encryptedApplicationKeys = KeySyncUtils.encryptKeysWithRecoveryKey(
214                    recoveryKey, rawKeys);
215        } catch (InvalidKeyException | NoSuchAlgorithmException e) {
216            Log.wtf(TAG,
217                    "Should be impossible: could not encrypt application keys with random key",
218                    e);
219            return;
220        }
221
222        Long counterId;
223        // counter id is generated exactly once for each credentials value.
224        if (mCredentialUpdated) {
225            counterId = generateAndStoreCounterId(recoveryAgentUid);
226        } else {
227            counterId = mRecoverableKeyStoreDb.getCounterId(mUserId, recoveryAgentUid);
228            if (counterId == null) {
229                counterId = generateAndStoreCounterId(recoveryAgentUid);
230            }
231        }
232        byte[] vaultParams = KeySyncUtils.packVaultParams(
233                publicKey,
234                counterId,
235                deviceId,
236                TRUSTED_HARDWARE_MAX_ATTEMPTS);
237
238        byte[] encryptedRecoveryKey;
239        try {
240            encryptedRecoveryKey = KeySyncUtils.thmEncryptRecoveryKey(
241                    publicKey,
242                    localLskfHash,
243                    vaultParams,
244                    recoveryKey);
245        } catch (NoSuchAlgorithmException e) {
246            Log.wtf(TAG, "SecureBox encrypt algorithms unavailable", e);
247            return;
248        } catch (InvalidKeyException e) {
249            Log.e(TAG,"Could not encrypt with recovery key", e);
250            return;
251        }
252        // TODO: store raw data in RecoveryServiceMetadataEntry and generate Parcelables later
253        // TODO: use Builder.
254        RecoveryMetadata metadata = new RecoveryMetadata(
255                /*userSecretType=*/ TYPE_LOCKSCREEN,
256                /*lockScreenUiFormat=*/ getUiFormat(mCredentialType, mCredential),
257                /*keyDerivationParams=*/ KeyDerivationParams.createSha256Params(salt),
258                /*secret=*/ new byte[0]);
259        ArrayList<RecoveryMetadata> metadataList = new ArrayList<>();
260        metadataList.add(metadata);
261
262        int snapshotVersion = incrementSnapshotVersion(recoveryAgentUid);
263
264        // If application keys are not updated, snapshot will not be created on next unlock.
265        mRecoverableKeyStoreDb.setShouldCreateSnapshot(mUserId, recoveryAgentUid, false);
266
267        // TODO: use Builder.
268        mRecoverySnapshotStorage.put(recoveryAgentUid, new RecoveryData(
269                snapshotVersion,
270                /*recoveryMetadata=*/ metadataList,
271                /*applicationKeyBlobs=*/ createApplicationKeyEntries(encryptedApplicationKeys),
272                /*encryptedRecoveryKeyblob=*/ encryptedRecoveryKey));
273
274        mSnapshotListenersStorage.recoverySnapshotAvailable(recoveryAgentUid);
275    }
276
277    @VisibleForTesting
278    int incrementSnapshotVersion(int recoveryAgentUid) {
279        Long snapshotVersion = mRecoverableKeyStoreDb.getSnapshotVersion(mUserId, recoveryAgentUid);
280        snapshotVersion = snapshotVersion == null ? 1 : snapshotVersion + 1;
281        mRecoverableKeyStoreDb.setSnapshotVersion(mUserId, recoveryAgentUid, snapshotVersion);
282
283        return snapshotVersion.intValue();
284    }
285
286    private long generateAndStoreCounterId(int recoveryAgentUid) {
287        long counter = new SecureRandom().nextLong();
288        mRecoverableKeyStoreDb.setCounterId(mUserId, recoveryAgentUid, counter);
289        return counter;
290    }
291
292    /**
293     * Returns all of the recoverable keys for the user.
294     */
295    private Map<String, SecretKey> getKeysToSync(int recoveryAgentUid)
296            throws InsecureUserException, KeyStoreException, UnrecoverableKeyException,
297            NoSuchAlgorithmException, NoSuchPaddingException, BadPlatformKeyException {
298        PlatformKeyManager platformKeyManager = mPlatformKeyManagerFactory.newInstance();
299        PlatformDecryptionKey decryptKey = platformKeyManager.getDecryptKey(mUserId);
300        Map<String, WrappedKey> wrappedKeys = mRecoverableKeyStoreDb.getAllKeys(
301                mUserId, recoveryAgentUid, decryptKey.getGenerationId());
302        return WrappedKey.unwrapKeys(decryptKey, wrappedKeys);
303    }
304
305    /**
306     * Returns {@code true} if a sync is pending.
307     * @param recoveryAgentUid uid of the recovery agent.
308     */
309    private boolean shoudCreateSnapshot(int recoveryAgentUid) {
310        int[] types = mRecoverableKeyStoreDb.getRecoverySecretTypes(mUserId, recoveryAgentUid);
311        if (!ArrayUtils.contains(types, RecoveryMetadata.TYPE_LOCKSCREEN)) {
312            // Only lockscreen type is supported.
313            // We will need to pass extra argument to KeySyncTask to support custom pass phrase.
314            return false;
315        }
316        if (mCredentialUpdated) {
317            // Sync credential if at least one snapshot was created.
318            if (mRecoverableKeyStoreDb.getSnapshotVersion(mUserId, recoveryAgentUid) != null) {
319                mRecoverableKeyStoreDb.setShouldCreateSnapshot(mUserId, recoveryAgentUid, true);
320                return true;
321            }
322        }
323
324        return mRecoverableKeyStoreDb.getShouldCreateSnapshot(mUserId, recoveryAgentUid);
325    }
326
327    /**
328     * The UI best suited to entering the given lock screen. This is synced with the vault so the
329     * user can be shown the same UI when recovering the vault on another device.
330     *
331     * @return The format - either pattern, pin, or password.
332     */
333    @VisibleForTesting
334    @RecoveryMetadata.LockScreenUiFormat static int getUiFormat(
335            int credentialType, String credential) {
336        if (credentialType == LockPatternUtils.CREDENTIAL_TYPE_PATTERN) {
337            return RecoveryMetadata.TYPE_PATTERN;
338        } else if (isPin(credential)) {
339            return RecoveryMetadata.TYPE_PIN;
340        } else {
341            return RecoveryMetadata.TYPE_PASSWORD;
342        }
343    }
344
345    /**
346     * Generates a salt to include with the lock screen hash.
347     *
348     * @return The salt.
349     */
350    private byte[] generateSalt() {
351        byte[] salt = new byte[SALT_LENGTH_BYTES];
352        new SecureRandom().nextBytes(salt);
353        return salt;
354    }
355
356    /**
357     * Returns {@code true} if {@code credential} looks like a pin.
358     */
359    @VisibleForTesting
360    static boolean isPin(@Nullable String credential) {
361        if (credential == null) {
362            return false;
363        }
364        int length = credential.length();
365        for (int i = 0; i < length; i++) {
366            if (!Character.isDigit(credential.charAt(i))) {
367                return false;
368            }
369        }
370        return true;
371    }
372
373    /**
374     * Hashes {@code credentials} with the given {@code salt}.
375     *
376     * @return The SHA-256 hash.
377     */
378    @VisibleForTesting
379    static byte[] hashCredentials(byte[] salt, String credentials) {
380        byte[] credentialsBytes = credentials.getBytes(StandardCharsets.UTF_8);
381        ByteBuffer byteBuffer = ByteBuffer.allocate(
382                salt.length + credentialsBytes.length + LENGTH_PREFIX_BYTES * 2);
383        byteBuffer.order(ByteOrder.LITTLE_ENDIAN);
384        byteBuffer.putInt(salt.length);
385        byteBuffer.put(salt);
386        byteBuffer.putInt(credentialsBytes.length);
387        byteBuffer.put(credentialsBytes);
388        byte[] bytes = byteBuffer.array();
389
390        try {
391            return MessageDigest.getInstance(LOCK_SCREEN_HASH_ALGORITHM).digest(bytes);
392        } catch (NoSuchAlgorithmException e) {
393            // Impossible, SHA-256 must be supported on Android.
394            throw new RuntimeException(e);
395        }
396    }
397
398    private static SecretKey generateRecoveryKey() throws NoSuchAlgorithmException {
399        KeyGenerator keyGenerator = KeyGenerator.getInstance(RECOVERY_KEY_ALGORITHM);
400        keyGenerator.init(RECOVERY_KEY_SIZE_BITS);
401        return keyGenerator.generateKey();
402    }
403
404    private static List<EntryRecoveryData> createApplicationKeyEntries(
405            Map<String, byte[]> encryptedApplicationKeys) {
406        ArrayList<EntryRecoveryData> keyEntries = new ArrayList<>();
407        for (String alias : encryptedApplicationKeys.keySet()) {
408            keyEntries.add(
409                    new EntryRecoveryData(
410                            alias,
411                            encryptedApplicationKeys.get(alias)));
412        }
413        return keyEntries;
414    }
415}
416