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