KeySyncTask.java revision 122bfe1b7eed5fb772d40b901ed818095c62c2e9
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.recoverablekeystore.KeyStoreRecoveryMetadata.TYPE_LOCKSCREEN; 20 21import android.annotation.NonNull; 22import android.annotation.Nullable; 23import android.content.Context; 24import android.security.recoverablekeystore.KeyDerivationParameters; 25import android.security.recoverablekeystore.KeyEntryRecoveryData; 26import android.security.recoverablekeystore.KeyStoreRecoveryData; 27import android.security.recoverablekeystore.KeyStoreRecoveryMetadata; 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 Long deviceId = mRecoverableKeyStoreDb.getServerParameters(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 TRUSTED_HARDWARE_MAX_ATTEMPTS, 236 deviceId); 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 KeyStoreRecoveryMetadata metadata = new KeyStoreRecoveryMetadata( 254 /*userSecretType=*/ TYPE_LOCKSCREEN, 255 /*lockScreenUiFormat=*/ getUiFormat(mCredentialType, mCredential), 256 /*keyDerivationParameters=*/ KeyDerivationParameters.createSha256Parameters(salt), 257 /*secret=*/ new byte[0]); 258 ArrayList<KeyStoreRecoveryMetadata> metadataList = new ArrayList<>(); 259 metadataList.add(metadata); 260 261 int snapshotVersion = incrementSnapshotVersion(recoveryAgentUid); 262 263 // If application keys are not updated, snapshot will not be created on next unlock. 264 mRecoverableKeyStoreDb.setShouldCreateSnapshot(mUserId, recoveryAgentUid, false); 265 266 mRecoverySnapshotStorage.put(recoveryAgentUid, new KeyStoreRecoveryData( 267 snapshotVersion, 268 /*recoveryMetadata=*/ metadataList, 269 /*applicationKeyBlobs=*/ createApplicationKeyEntries(encryptedApplicationKeys), 270 /*encryptedRecoveryKeyblob=*/ encryptedRecoveryKey)); 271 272 mSnapshotListenersStorage.recoverySnapshotAvailable(recoveryAgentUid); 273 } 274 275 @VisibleForTesting 276 int incrementSnapshotVersion(int recoveryAgentUid) { 277 Long snapshotVersion = mRecoverableKeyStoreDb.getSnapshotVersion(mUserId, recoveryAgentUid); 278 snapshotVersion = snapshotVersion == null ? 1 : snapshotVersion + 1; 279 mRecoverableKeyStoreDb.setSnapshotVersion(mUserId, recoveryAgentUid, snapshotVersion); 280 281 return snapshotVersion.intValue(); 282 } 283 284 private long generateAndStoreCounterId(int recoveryAgentUid) { 285 long counter = new SecureRandom().nextLong(); 286 mRecoverableKeyStoreDb.setCounterId(mUserId, recoveryAgentUid, counter); 287 return counter; 288 } 289 290 /** 291 * Returns all of the recoverable keys for the user. 292 */ 293 private Map<String, SecretKey> getKeysToSync(int recoveryAgentUid) 294 throws InsecureUserException, KeyStoreException, UnrecoverableKeyException, 295 NoSuchAlgorithmException, NoSuchPaddingException, BadPlatformKeyException { 296 PlatformKeyManager platformKeyManager = mPlatformKeyManagerFactory.newInstance(); 297 PlatformDecryptionKey decryptKey = platformKeyManager.getDecryptKey(mUserId); 298 Map<String, WrappedKey> wrappedKeys = mRecoverableKeyStoreDb.getAllKeys( 299 mUserId, recoveryAgentUid, decryptKey.getGenerationId()); 300 return WrappedKey.unwrapKeys(decryptKey, wrappedKeys); 301 } 302 303 /** 304 * Returns {@code true} if a sync is pending. 305 * @param recoveryAgentUid uid of the recovery agent. 306 */ 307 private boolean shoudCreateSnapshot(int recoveryAgentUid) { 308 int[] types = mRecoverableKeyStoreDb.getRecoverySecretTypes(mUserId, recoveryAgentUid); 309 if (!ArrayUtils.contains(types, KeyStoreRecoveryMetadata.TYPE_LOCKSCREEN)) { 310 // Only lockscreen type is supported. 311 // We will need to pass extra argument to KeySyncTask to support custom pass phrase. 312 return false; 313 } 314 if (mCredentialUpdated) { 315 // Sync credential if at least one snapshot was created. 316 if (mRecoverableKeyStoreDb.getSnapshotVersion(mUserId, recoveryAgentUid) != null) { 317 mRecoverableKeyStoreDb.setShouldCreateSnapshot(mUserId, recoveryAgentUid, true); 318 return true; 319 } 320 } 321 322 return mRecoverableKeyStoreDb.getShouldCreateSnapshot(mUserId, recoveryAgentUid); 323 } 324 325 /** 326 * The UI best suited to entering the given lock screen. This is synced with the vault so the 327 * user can be shown the same UI when recovering the vault on another device. 328 * 329 * @return The format - either pattern, pin, or password. 330 */ 331 @VisibleForTesting 332 @KeyStoreRecoveryMetadata.LockScreenUiFormat static int getUiFormat( 333 int credentialType, String credential) { 334 if (credentialType == LockPatternUtils.CREDENTIAL_TYPE_PATTERN) { 335 return KeyStoreRecoveryMetadata.TYPE_PATTERN; 336 } else if (isPin(credential)) { 337 return KeyStoreRecoveryMetadata.TYPE_PIN; 338 } else { 339 return KeyStoreRecoveryMetadata.TYPE_PASSWORD; 340 } 341 } 342 343 /** 344 * Generates a salt to include with the lock screen hash. 345 * 346 * @return The salt. 347 */ 348 private byte[] generateSalt() { 349 byte[] salt = new byte[SALT_LENGTH_BYTES]; 350 new SecureRandom().nextBytes(salt); 351 return salt; 352 } 353 354 /** 355 * Returns {@code true} if {@code credential} looks like a pin. 356 */ 357 @VisibleForTesting 358 static boolean isPin(@Nullable String credential) { 359 if (credential == null) { 360 return false; 361 } 362 int length = credential.length(); 363 for (int i = 0; i < length; i++) { 364 if (!Character.isDigit(credential.charAt(i))) { 365 return false; 366 } 367 } 368 return true; 369 } 370 371 /** 372 * Hashes {@code credentials} with the given {@code salt}. 373 * 374 * @return The SHA-256 hash. 375 */ 376 @VisibleForTesting 377 static byte[] hashCredentials(byte[] salt, String credentials) { 378 byte[] credentialsBytes = credentials.getBytes(StandardCharsets.UTF_8); 379 ByteBuffer byteBuffer = ByteBuffer.allocate( 380 salt.length + credentialsBytes.length + LENGTH_PREFIX_BYTES * 2); 381 byteBuffer.order(ByteOrder.LITTLE_ENDIAN); 382 byteBuffer.putInt(salt.length); 383 byteBuffer.put(salt); 384 byteBuffer.putInt(credentialsBytes.length); 385 byteBuffer.put(credentialsBytes); 386 byte[] bytes = byteBuffer.array(); 387 388 try { 389 return MessageDigest.getInstance(LOCK_SCREEN_HASH_ALGORITHM).digest(bytes); 390 } catch (NoSuchAlgorithmException e) { 391 // Impossible, SHA-256 must be supported on Android. 392 throw new RuntimeException(e); 393 } 394 } 395 396 private static SecretKey generateRecoveryKey() throws NoSuchAlgorithmException { 397 KeyGenerator keyGenerator = KeyGenerator.getInstance(RECOVERY_KEY_ALGORITHM); 398 keyGenerator.init(RECOVERY_KEY_SIZE_BITS); 399 return keyGenerator.generateKey(); 400 } 401 402 private static List<KeyEntryRecoveryData> createApplicationKeyEntries( 403 Map<String, byte[]> encryptedApplicationKeys) { 404 ArrayList<KeyEntryRecoveryData> keyEntries = new ArrayList<>(); 405 for (String alias : encryptedApplicationKeys.keySet()) { 406 keyEntries.add( 407 new KeyEntryRecoveryData( 408 alias, 409 encryptedApplicationKeys.get(alias))); 410 } 411 return keyEntries; 412 } 413} 414