KeySyncTask.java revision 6e16724fb66e4bd14274768174379aa88c34464f
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.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 mPlatformKeyManager; 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 platformKeyManager platform key manager 109 */ 110 @VisibleForTesting 111 KeySyncTask( 112 RecoverableKeyStoreDb recoverableKeyStoreDb, 113 RecoverySnapshotStorage snapshotStorage, 114 RecoverySnapshotListenersStorage recoverySnapshotListenersStorage, 115 int userId, 116 int credentialType, 117 String credential, 118 boolean credentialUpdated, 119 PlatformKeyManager platformKeyManager) { 120 mSnapshotListenersStorage = recoverySnapshotListenersStorage; 121 mRecoverableKeyStoreDb = recoverableKeyStoreDb; 122 mUserId = userId; 123 mCredentialType = credentialType; 124 mCredential = credential; 125 mCredentialUpdated = credentialUpdated; 126 mPlatformKeyManager = platformKeyManager; 127 mRecoverySnapshotStorage = snapshotStorage; 128 } 129 130 @Override 131 public void run() { 132 try { 133 // Only one task is active If user unlocks phone many times in a short time interval. 134 synchronized(KeySyncTask.class) { 135 syncKeys(); 136 } 137 } catch (Exception e) { 138 Log.e(TAG, "Unexpected exception thrown during KeySyncTask", e); 139 } 140 } 141 142 private void syncKeys() { 143 if (mCredentialType == LockPatternUtils.CREDENTIAL_TYPE_NONE) { 144 // Application keys for the user will not be available for sync. 145 Log.w(TAG, "Credentials are not set for user " + mUserId); 146 int generation = mPlatformKeyManager.getGenerationId(mUserId); 147 mPlatformKeyManager.invalidatePlatformKey(mUserId, generation); 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[] vaultHandle = mRecoverableKeyStoreDb.getServerParams(mUserId, recoveryAgentUid); 179 if (vaultHandle == 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 233 // TODO: make sure the same counter id is used during recovery and remove temporary fix. 234 counterId = 1L; 235 236 byte[] vaultParams = KeySyncUtils.packVaultParams( 237 publicKey, 238 counterId, 239 TRUSTED_HARDWARE_MAX_ATTEMPTS, 240 vaultHandle); 241 242 byte[] encryptedRecoveryKey; 243 try { 244 encryptedRecoveryKey = KeySyncUtils.thmEncryptRecoveryKey( 245 publicKey, 246 localLskfHash, 247 vaultParams, 248 recoveryKey); 249 } catch (NoSuchAlgorithmException e) { 250 Log.wtf(TAG, "SecureBox encrypt algorithms unavailable", e); 251 return; 252 } catch (InvalidKeyException e) { 253 Log.e(TAG,"Could not encrypt with recovery key", e); 254 return; 255 } 256 // TODO: store raw data in RecoveryServiceMetadataEntry and generate Parcelables later 257 // TODO: use Builder. 258 KeyChainProtectionParams metadata = new KeyChainProtectionParams( 259 /*userSecretType=*/ TYPE_LOCKSCREEN, 260 /*lockScreenUiFormat=*/ getUiFormat(mCredentialType, mCredential), 261 /*keyDerivationParams=*/ KeyDerivationParams.createSha256Params(salt), 262 /*secret=*/ new byte[0]); 263 ArrayList<KeyChainProtectionParams> metadataList = new ArrayList<>(); 264 metadataList.add(metadata); 265 266 int snapshotVersion = incrementSnapshotVersion(recoveryAgentUid); 267 268 // If application keys are not updated, snapshot will not be created on next unlock. 269 mRecoverableKeyStoreDb.setShouldCreateSnapshot(mUserId, recoveryAgentUid, false); 270 271 mRecoverySnapshotStorage.put(recoveryAgentUid, new KeyChainSnapshot.Builder() 272 .setSnapshotVersion(snapshotVersion) 273 .setMaxAttempts(TRUSTED_HARDWARE_MAX_ATTEMPTS) 274 .setCounterId(counterId) 275 .setTrustedHardwarePublicKey(SecureBox.encodePublicKey(publicKey)) 276 .setServerParams(vaultHandle) 277 .setKeyChainProtectionParams(metadataList) 278 .setWrappedApplicationKeys(createApplicationKeyEntries(encryptedApplicationKeys)) 279 .setEncryptedRecoveryKeyBlob(encryptedRecoveryKey) 280 .build()); 281 282 mSnapshotListenersStorage.recoverySnapshotAvailable(recoveryAgentUid); 283 } 284 285 @VisibleForTesting 286 int incrementSnapshotVersion(int recoveryAgentUid) { 287 Long snapshotVersion = mRecoverableKeyStoreDb.getSnapshotVersion(mUserId, recoveryAgentUid); 288 snapshotVersion = snapshotVersion == null ? 1 : snapshotVersion + 1; 289 mRecoverableKeyStoreDb.setSnapshotVersion(mUserId, recoveryAgentUid, snapshotVersion); 290 291 return snapshotVersion.intValue(); 292 } 293 294 private long generateAndStoreCounterId(int recoveryAgentUid) { 295 long counter = new SecureRandom().nextLong(); 296 mRecoverableKeyStoreDb.setCounterId(mUserId, recoveryAgentUid, counter); 297 return counter; 298 } 299 300 /** 301 * Returns all of the recoverable keys for the user. 302 */ 303 private Map<String, SecretKey> getKeysToSync(int recoveryAgentUid) 304 throws InsecureUserException, KeyStoreException, UnrecoverableKeyException, 305 NoSuchAlgorithmException, NoSuchPaddingException, BadPlatformKeyException, 306 InvalidKeyException, InvalidAlgorithmParameterException { 307 PlatformDecryptionKey decryptKey = mPlatformKeyManager.getDecryptKey(mUserId);; 308 Map<String, WrappedKey> wrappedKeys = mRecoverableKeyStoreDb.getAllKeys( 309 mUserId, recoveryAgentUid, decryptKey.getGenerationId()); 310 return WrappedKey.unwrapKeys(decryptKey, wrappedKeys); 311 } 312 313 /** 314 * Returns {@code true} if a sync is pending. 315 * @param recoveryAgentUid uid of the recovery agent. 316 */ 317 private boolean shoudCreateSnapshot(int recoveryAgentUid) { 318 int[] types = mRecoverableKeyStoreDb.getRecoverySecretTypes(mUserId, recoveryAgentUid); 319 if (!ArrayUtils.contains(types, KeyChainProtectionParams.TYPE_LOCKSCREEN)) { 320 // Only lockscreen type is supported. 321 // We will need to pass extra argument to KeySyncTask to support custom pass phrase. 322 return false; 323 } 324 if (mCredentialUpdated) { 325 // Sync credential if at least one snapshot was created. 326 if (mRecoverableKeyStoreDb.getSnapshotVersion(mUserId, recoveryAgentUid) != null) { 327 mRecoverableKeyStoreDb.setShouldCreateSnapshot(mUserId, recoveryAgentUid, true); 328 return true; 329 } 330 } 331 332 return mRecoverableKeyStoreDb.getShouldCreateSnapshot(mUserId, recoveryAgentUid); 333 } 334 335 /** 336 * The UI best suited to entering the given lock screen. This is synced with the vault so the 337 * user can be shown the same UI when recovering the vault on another device. 338 * 339 * @return The format - either pattern, pin, or password. 340 */ 341 @VisibleForTesting 342 @KeyChainProtectionParams.LockScreenUiFormat static int getUiFormat( 343 int credentialType, String credential) { 344 if (credentialType == LockPatternUtils.CREDENTIAL_TYPE_PATTERN) { 345 return KeyChainProtectionParams.UI_FORMAT_PATTERN; 346 } else if (isPin(credential)) { 347 return KeyChainProtectionParams.UI_FORMAT_PIN; 348 } else { 349 return KeyChainProtectionParams.UI_FORMAT_PASSWORD; 350 } 351 } 352 353 /** 354 * Generates a salt to include with the lock screen hash. 355 * 356 * @return The salt. 357 */ 358 private byte[] generateSalt() { 359 byte[] salt = new byte[SALT_LENGTH_BYTES]; 360 new SecureRandom().nextBytes(salt); 361 return salt; 362 } 363 364 /** 365 * Returns {@code true} if {@code credential} looks like a pin. 366 */ 367 @VisibleForTesting 368 static boolean isPin(@Nullable String credential) { 369 if (credential == null) { 370 return false; 371 } 372 int length = credential.length(); 373 for (int i = 0; i < length; i++) { 374 if (!Character.isDigit(credential.charAt(i))) { 375 return false; 376 } 377 } 378 return true; 379 } 380 381 /** 382 * Hashes {@code credentials} with the given {@code salt}. 383 * 384 * @return The SHA-256 hash. 385 */ 386 @VisibleForTesting 387 static byte[] hashCredentials(byte[] salt, String credentials) { 388 byte[] credentialsBytes = credentials.getBytes(StandardCharsets.UTF_8); 389 ByteBuffer byteBuffer = ByteBuffer.allocate( 390 salt.length + credentialsBytes.length + LENGTH_PREFIX_BYTES * 2); 391 byteBuffer.order(ByteOrder.LITTLE_ENDIAN); 392 byteBuffer.putInt(salt.length); 393 byteBuffer.put(salt); 394 byteBuffer.putInt(credentialsBytes.length); 395 byteBuffer.put(credentialsBytes); 396 byte[] bytes = byteBuffer.array(); 397 398 try { 399 return MessageDigest.getInstance(LOCK_SCREEN_HASH_ALGORITHM).digest(bytes); 400 } catch (NoSuchAlgorithmException e) { 401 // Impossible, SHA-256 must be supported on Android. 402 throw new RuntimeException(e); 403 } 404 } 405 406 private static SecretKey generateRecoveryKey() throws NoSuchAlgorithmException { 407 KeyGenerator keyGenerator = KeyGenerator.getInstance(RECOVERY_KEY_ALGORITHM); 408 keyGenerator.init(RECOVERY_KEY_SIZE_BITS); 409 return keyGenerator.generateKey(); 410 } 411 412 private static List<WrappedApplicationKey> createApplicationKeyEntries( 413 Map<String, byte[]> encryptedApplicationKeys) { 414 ArrayList<WrappedApplicationKey> keyEntries = new ArrayList<>(); 415 for (String alias : encryptedApplicationKeys.keySet()) { 416 keyEntries.add( 417 new WrappedApplicationKey( 418 alias, 419 encryptedApplicationKeys.get(alias))); 420 } 421 return keyEntries; 422 } 423} 424