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 17 package com.android.server.locksettings.recoverablekeystore; 18 19 import android.app.KeyguardManager; 20 import android.content.Context; 21 import android.os.RemoteException; 22 import android.os.UserHandle; 23 import android.security.GateKeeper; 24 import android.security.keystore.KeyPermanentlyInvalidatedException; 25 import android.security.keystore.KeyProperties; 26 import android.security.keystore.KeyProtection; 27 import android.service.gatekeeper.IGateKeeperService; 28 import android.util.Log; 29 30 import com.android.internal.annotations.VisibleForTesting; 31 import com.android.server.locksettings.recoverablekeystore.storage.RecoverableKeyStoreDb; 32 33 import java.io.IOException; 34 import java.security.InvalidAlgorithmParameterException; 35 import java.security.InvalidKeyException; 36 import java.security.KeyStore; 37 import java.security.KeyStoreException; 38 import java.security.NoSuchAlgorithmException; 39 import java.security.UnrecoverableKeyException; 40 import java.security.cert.CertificateException; 41 import java.util.Locale; 42 43 import javax.crypto.Cipher; 44 import javax.crypto.KeyGenerator; 45 import javax.crypto.NoSuchPaddingException; 46 import javax.crypto.SecretKey; 47 import javax.crypto.spec.GCMParameterSpec; 48 49 /** 50 * Manages creating and checking the validity of the platform key. 51 * 52 * <p>The platform key is used to wrap the material of recoverable keys before persisting them to 53 * disk. It is also used to decrypt the same keys on a screen unlock, before re-wrapping them with 54 * a recovery key and syncing them with remote storage. 55 * 56 * <p>Each platform key has two entries in AndroidKeyStore: 57 * 58 * <ul> 59 * <li>Encrypt entry - this entry enables the root user to at any time encrypt. 60 * <li>Decrypt entry - this entry enables the root user to decrypt only after recent user 61 * authentication, i.e., within 15 seconds after a screen unlock. 62 * </ul> 63 * 64 * <p>Both entries are enabled only for AES/GCM/NoPadding Cipher algorithm. 65 * 66 * @hide 67 */ 68 public class PlatformKeyManager { 69 static final int MIN_GENERATION_ID_FOR_UNLOCKED_DEVICE_REQUIRED = 1001000; 70 71 private static final String TAG = "PlatformKeyManager"; 72 private static final String KEY_ALGORITHM = "AES"; 73 private static final int KEY_SIZE_BITS = 256; 74 private static final String KEY_ALIAS_PREFIX = 75 "com.android.server.locksettings.recoverablekeystore/platform/"; 76 private static final String ENCRYPT_KEY_ALIAS_SUFFIX = "encrypt"; 77 private static final String DECRYPT_KEY_ALIAS_SUFFIX = "decrypt"; 78 private static final String KEY_WRAP_CIPHER_ALGORITHM = "AES/GCM/NoPadding"; 79 private static final int GCM_TAG_LENGTH_BITS = 128; 80 // Only used for checking if a key is usable 81 private static final byte[] GCM_INSECURE_NONCE_BYTES = new byte[12]; 82 83 private final Context mContext; 84 private final KeyStoreProxy mKeyStore; 85 private final RecoverableKeyStoreDb mDatabase; 86 87 /** 88 * A new instance operating on behalf of {@code userId}, storing its prefs in the location 89 * defined by {@code context}. 90 * 91 * @param context This should be the context of the RecoverableKeyStoreLoader service. 92 * @throws KeyStoreException if failed to initialize AndroidKeyStore. 93 * @throws NoSuchAlgorithmException if AES is unavailable - should never happen. 94 * @throws SecurityException if the caller does not have permission to write to /data/system. 95 * 96 * @hide 97 */ getInstance(Context context, RecoverableKeyStoreDb database)98 public static PlatformKeyManager getInstance(Context context, RecoverableKeyStoreDb database) 99 throws KeyStoreException, NoSuchAlgorithmException { 100 return new PlatformKeyManager( 101 context.getApplicationContext(), 102 new KeyStoreProxyImpl(getAndLoadAndroidKeyStore()), 103 database); 104 } 105 106 @VisibleForTesting PlatformKeyManager( Context context, KeyStoreProxy keyStore, RecoverableKeyStoreDb database)107 PlatformKeyManager( 108 Context context, 109 KeyStoreProxy keyStore, 110 RecoverableKeyStoreDb database) { 111 mKeyStore = keyStore; 112 mContext = context; 113 mDatabase = database; 114 } 115 116 /** 117 * Returns the current generation ID of the platform key. This increments whenever a platform 118 * key has to be replaced. (e.g., because the user has removed and then re-added their lock 119 * screen). Returns -1 if no key has been generated yet. 120 * 121 * @param userId The ID of the user to whose lock screen the platform key must be bound. 122 * 123 * @hide 124 */ getGenerationId(int userId)125 public int getGenerationId(int userId) { 126 return mDatabase.getPlatformKeyGenerationId(userId); 127 } 128 129 /** 130 * Returns {@code true} if the platform key is available. A platform key won't be available if 131 * device is locked. 132 * 133 * @param userId The ID of the user to whose lock screen the platform key must be bound. 134 * 135 * @hide 136 */ isDeviceLocked(int userId)137 public boolean isDeviceLocked(int userId) { 138 return mContext.getSystemService(KeyguardManager.class).isDeviceLocked(userId); 139 } 140 141 /** 142 * Removes the platform key from Android KeyStore. 143 * It is triggered when user disables lock screen. 144 * 145 * @param userId The ID of the user to whose lock screen the platform key must be bound. 146 * @param generationId Generation id. 147 * 148 * @hide 149 */ invalidatePlatformKey(int userId, int generationId)150 public void invalidatePlatformKey(int userId, int generationId) { 151 if (generationId != -1) { 152 try { 153 mKeyStore.deleteEntry(getEncryptAlias(userId, generationId)); 154 mKeyStore.deleteEntry(getDecryptAlias(userId, generationId)); 155 } catch (KeyStoreException e) { 156 // Ignore failed attempt to delete key. 157 } 158 } 159 } 160 161 /** 162 * Generates a new key and increments the generation ID. Should be invoked if the platform key 163 * is corrupted and needs to be rotated. 164 * Updates status of old keys to {@code RecoveryController.RECOVERY_STATUS_PERMANENT_FAILURE}. 165 * 166 * @param userId The ID of the user to whose lock screen the platform key must be bound. 167 * @throws NoSuchAlgorithmException if AES is unavailable - should never happen. 168 * @throws KeyStoreException if there is an error in AndroidKeyStore. 169 * @throws InsecureUserException if the user does not have a lock screen set. 170 * @throws IOException if there was an issue with local database update. 171 * @throws RemoteException if there was an issue communicating with {@link IGateKeeperService}. 172 * 173 * @hide 174 */ 175 @VisibleForTesting regenerate(int userId)176 void regenerate(int userId) 177 throws NoSuchAlgorithmException, KeyStoreException, IOException, 178 RemoteException, InsecureUserException { 179 int generationId = getGenerationId(userId); 180 int nextId; 181 if (generationId == -1) { 182 nextId = 1; 183 } else { 184 invalidatePlatformKey(userId, generationId); 185 nextId = generationId + 1; 186 } 187 generateAndLoadKey(userId, nextId); 188 } 189 190 /** 191 * Returns the platform key used for encryption. 192 * Tries to regenerate key one time if it is permanently invalid. 193 * 194 * @param userId The ID of the user to whose lock screen the platform key must be bound. 195 * @throws KeyStoreException if there was an AndroidKeyStore error. 196 * @throws UnrecoverableKeyException if the key could not be recovered. 197 * @throws NoSuchAlgorithmException if AES is unavailable - should never occur. 198 * @throws IOException if there was an issue with local database update. 199 * @throws InsecureUserException if the user does not have a lock screen set. 200 * @throws RemoteException if there was an issue communicating with {@link IGateKeeperService}. 201 * 202 * @hide 203 */ getEncryptKey(int userId)204 public PlatformEncryptionKey getEncryptKey(int userId) 205 throws KeyStoreException, UnrecoverableKeyException, NoSuchAlgorithmException, 206 IOException, RemoteException, InsecureUserException { 207 init(userId); 208 try { 209 // Try to see if the decryption key is still accessible before using the encryption key. 210 // The auth-bound decryption will be unrecoverable if the screen lock is disabled. 211 getDecryptKeyInternal(userId); 212 return getEncryptKeyInternal(userId); 213 } catch (UnrecoverableKeyException e) { 214 Log.i(TAG, String.format(Locale.US, 215 "Regenerating permanently invalid Platform key for user %d.", 216 userId)); 217 regenerate(userId); 218 return getEncryptKeyInternal(userId); 219 } 220 } 221 222 /** 223 * Returns the platform key used for encryption. 224 * 225 * @param userId The ID of the user to whose lock screen the platform key must be bound. 226 * @throws KeyStoreException if there was an AndroidKeyStore error. 227 * @throws UnrecoverableKeyException if the key could not be recovered. 228 * @throws NoSuchAlgorithmException if AES is unavailable - should never occur. 229 * 230 * @hide 231 */ getEncryptKeyInternal(int userId)232 private PlatformEncryptionKey getEncryptKeyInternal(int userId) throws KeyStoreException, 233 UnrecoverableKeyException, NoSuchAlgorithmException { 234 int generationId = getGenerationId(userId); 235 String alias = getEncryptAlias(userId, generationId); 236 if (!isKeyLoaded(userId, generationId)) { 237 throw new UnrecoverableKeyException("KeyStore doesn't contain key " + alias); 238 } 239 SecretKey key = (SecretKey) mKeyStore.getKey( 240 alias, /*password=*/ null); 241 return new PlatformEncryptionKey(generationId, key); 242 } 243 244 /** 245 * Returns the platform key used for decryption. Only works after a recent screen unlock. 246 * Tries to regenerate key one time if it is permanently invalid. 247 * 248 * @param userId The ID of the user to whose lock screen the platform key must be bound. 249 * @throws KeyStoreException if there was an AndroidKeyStore error. 250 * @throws UnrecoverableKeyException if the key could not be recovered. 251 * @throws NoSuchAlgorithmException if AES is unavailable - should never occur. 252 * @throws IOException if there was an issue with local database update. 253 * @throws RemoteException if there was an issue communicating with {@link IGateKeeperService}. 254 * 255 * @hide 256 */ getDecryptKey(int userId)257 public PlatformDecryptionKey getDecryptKey(int userId) 258 throws KeyStoreException, UnrecoverableKeyException, NoSuchAlgorithmException, 259 IOException, InsecureUserException, RemoteException { 260 init(userId); 261 try { 262 PlatformDecryptionKey decryptionKey = getDecryptKeyInternal(userId); 263 ensureDecryptionKeyIsValid(userId, decryptionKey); 264 return decryptionKey; 265 } catch (UnrecoverableKeyException e) { 266 Log.i(TAG, String.format(Locale.US, 267 "Regenerating permanently invalid Platform key for user %d.", 268 userId)); 269 regenerate(userId); 270 return getDecryptKeyInternal(userId); 271 } 272 } 273 274 /** 275 * Returns the platform key used for decryption. Only works after a recent screen unlock. 276 * 277 * @param userId The ID of the user to whose lock screen the platform key must be bound. 278 * @throws KeyStoreException if there was an AndroidKeyStore error. 279 * @throws UnrecoverableKeyException if the key could not be recovered. 280 * @throws NoSuchAlgorithmException if AES is unavailable - should never occur. 281 * 282 * @hide 283 */ getDecryptKeyInternal(int userId)284 private PlatformDecryptionKey getDecryptKeyInternal(int userId) throws KeyStoreException, 285 UnrecoverableKeyException, NoSuchAlgorithmException { 286 int generationId = getGenerationId(userId); 287 String alias = getDecryptAlias(userId, generationId); 288 if (!isKeyLoaded(userId, generationId)) { 289 throw new UnrecoverableKeyException("KeyStore doesn't contain key " + alias); 290 } 291 SecretKey key = (SecretKey) mKeyStore.getKey( 292 alias, /*password=*/ null); 293 return new PlatformDecryptionKey(generationId, key); 294 } 295 296 /** 297 * Tries to use the decryption key to make sure it is not permanently invalidated. The exception 298 * {@code KeyPermanentlyInvalidatedException} is thrown only when the key is in use. 299 * 300 * <p>Note that we ignore all other InvalidKeyException exceptions, because such an exception 301 * may be thrown for auth-bound keys if there's no recent unlock event. 302 */ ensureDecryptionKeyIsValid(int userId, PlatformDecryptionKey decryptionKey)303 private void ensureDecryptionKeyIsValid(int userId, PlatformDecryptionKey decryptionKey) 304 throws UnrecoverableKeyException { 305 try { 306 Cipher.getInstance(KEY_WRAP_CIPHER_ALGORITHM).init(Cipher.UNWRAP_MODE, 307 decryptionKey.getKey(), 308 new GCMParameterSpec(GCM_TAG_LENGTH_BITS, GCM_INSECURE_NONCE_BYTES)); 309 } catch (KeyPermanentlyInvalidatedException e) { 310 Log.e(TAG, String.format(Locale.US, "The platform key for user %d became invalid.", 311 userId)); 312 throw new UnrecoverableKeyException(e.getMessage()); 313 } catch (NoSuchAlgorithmException | InvalidKeyException 314 | InvalidAlgorithmParameterException | NoSuchPaddingException e) { 315 // Ignore all other exceptions 316 } 317 } 318 319 /** 320 * Initializes the class. If there is no current platform key, and the user has a lock screen 321 * set, will create the platform key and set the generation ID. 322 * 323 * @param userId The ID of the user to whose lock screen the platform key must be bound. 324 * @throws KeyStoreException if there was an error in AndroidKeyStore. 325 * @throws NoSuchAlgorithmException if AES is unavailable - should never happen. 326 * @throws IOException if there was an issue with local database update. 327 * @throws RemoteException if there was an issue communicating with {@link IGateKeeperService}. 328 * 329 * @hide 330 */ init(int userId)331 void init(int userId) 332 throws KeyStoreException, NoSuchAlgorithmException, IOException, 333 RemoteException, InsecureUserException { 334 int generationId = getGenerationId(userId); 335 if (isKeyLoaded(userId, generationId)) { 336 Log.i(TAG, String.format( 337 Locale.US, "Platform key generation %d exists already.", generationId)); 338 return; 339 } 340 if (generationId == -1) { 341 Log.i(TAG, "Generating initial platform key generation ID."); 342 generationId = 1; 343 } else { 344 Log.w(TAG, String.format(Locale.US, "Platform generation ID was %d but no " 345 + "entry was present in AndroidKeyStore. Generating fresh key.", generationId)); 346 // Have to generate a fresh key, so bump the generation id 347 generationId++; 348 } 349 350 generationId = Math.max(generationId, MIN_GENERATION_ID_FOR_UNLOCKED_DEVICE_REQUIRED); 351 generateAndLoadKey(userId, generationId); 352 } 353 354 /** 355 * Returns the alias of the encryption key with the specific {@code generationId} in the 356 * AndroidKeyStore. 357 * 358 * <p>These IDs look as follows: 359 * {@code com.security.recoverablekeystore/platform/<user id>/<generation id>/encrypt} 360 * 361 * @param userId The ID of the user to whose lock screen the platform key must be bound. 362 * @param generationId The generation ID. 363 * @return The alias. 364 */ getEncryptAlias(int userId, int generationId)365 private String getEncryptAlias(int userId, int generationId) { 366 return KEY_ALIAS_PREFIX + userId + "/" + generationId + "/" + ENCRYPT_KEY_ALIAS_SUFFIX; 367 } 368 369 /** 370 * Returns the alias of the decryption key with the specific {@code generationId} in the 371 * AndroidKeyStore. 372 * 373 * <p>These IDs look as follows: 374 * {@code com.security.recoverablekeystore/platform/<user id>/<generation id>/decrypt} 375 * 376 * @param userId The ID of the user to whose lock screen the platform key must be bound. 377 * @param generationId The generation ID. 378 * @return The alias. 379 */ getDecryptAlias(int userId, int generationId)380 private String getDecryptAlias(int userId, int generationId) { 381 return KEY_ALIAS_PREFIX + userId + "/" + generationId + "/" + DECRYPT_KEY_ALIAS_SUFFIX; 382 } 383 384 /** 385 * Sets the current generation ID to {@code generationId}. 386 * @throws IOException if there was an issue with local database update. 387 */ setGenerationId(int userId, int generationId)388 private void setGenerationId(int userId, int generationId) throws IOException { 389 mDatabase.setPlatformKeyGenerationId(userId, generationId); 390 } 391 392 /** 393 * Returns {@code true} if a key has been loaded with the given {@code generationId} into 394 * AndroidKeyStore. 395 * 396 * @throws KeyStoreException if there was an error checking AndroidKeyStore. 397 */ isKeyLoaded(int userId, int generationId)398 private boolean isKeyLoaded(int userId, int generationId) throws KeyStoreException { 399 return mKeyStore.containsAlias(getEncryptAlias(userId, generationId)) 400 && mKeyStore.containsAlias(getDecryptAlias(userId, generationId)); 401 } 402 403 @VisibleForTesting getGateKeeperService()404 IGateKeeperService getGateKeeperService() { 405 return GateKeeper.getService(); 406 } 407 408 /** 409 * Generates a new 256-bit AES key, and loads it into AndroidKeyStore with the given 410 * {@code generationId} determining its aliases. 411 * 412 * @throws NoSuchAlgorithmException if AES is unavailable. This should never happen, as it is 413 * available since API version 1. 414 * @throws KeyStoreException if there was an issue loading the keys into AndroidKeyStore. 415 * @throws IOException if there was an issue with local database update. 416 * @throws RemoteException if there was an issue communicating with {@link IGateKeeperService}. 417 */ generateAndLoadKey(int userId, int generationId)418 private void generateAndLoadKey(int userId, int generationId) 419 throws NoSuchAlgorithmException, KeyStoreException, IOException, RemoteException, 420 InsecureUserException { 421 String encryptAlias = getEncryptAlias(userId, generationId); 422 String decryptAlias = getDecryptAlias(userId, generationId); 423 // SecretKey implementation doesn't provide reliable way to destroy the secret 424 // so it may live in memory for some time. 425 SecretKey secretKey = generateAesKey(); 426 427 KeyProtection.Builder decryptionKeyProtection = 428 new KeyProtection.Builder(KeyProperties.PURPOSE_DECRYPT) 429 .setBlockModes(KeyProperties.BLOCK_MODE_GCM) 430 .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE); 431 // Skip UserAuthenticationRequired for main user 432 if (userId == UserHandle.USER_SYSTEM) { 433 // attempt to store key will fail if screenlock is not set. 434 decryptionKeyProtection.setUnlockedDeviceRequired(true); 435 } else { 436 // Don't set protection params to prevent losing key. 437 } 438 // Store decryption key first since it is more likely to fail. 439 try { 440 mKeyStore.setEntry( 441 decryptAlias, 442 new KeyStore.SecretKeyEntry(secretKey), 443 decryptionKeyProtection.build()); 444 mKeyStore.setEntry( 445 encryptAlias, 446 new KeyStore.SecretKeyEntry(secretKey), 447 new KeyProtection.Builder(KeyProperties.PURPOSE_ENCRYPT) 448 .setBlockModes(KeyProperties.BLOCK_MODE_GCM) 449 .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE) 450 .build()); 451 } catch (KeyStoreException e) { 452 if (!isDeviceSecure(userId)) { 453 throw new InsecureUserException("Screenlock is not set"); 454 } else { 455 throw e; 456 } 457 } 458 setGenerationId(userId, generationId); 459 } 460 461 /** 462 * Generates a new 256-bit AES key, in software. 463 * 464 * @return The software-generated AES key. 465 * @throws NoSuchAlgorithmException if AES key generation is not available. This should never 466 * happen, as AES has been supported since API level 1. 467 */ generateAesKey()468 private static SecretKey generateAesKey() throws NoSuchAlgorithmException { 469 KeyGenerator keyGenerator = KeyGenerator.getInstance(KEY_ALGORITHM); 470 keyGenerator.init(KEY_SIZE_BITS); 471 return keyGenerator.generateKey(); 472 } 473 474 /** 475 * Returns AndroidKeyStore-provided {@link KeyStore}, having already invoked 476 * {@link KeyStore#load(KeyStore.LoadStoreParameter)}. 477 * 478 * @throws KeyStoreException if there was a problem getting or initializing the key store. 479 */ getAndLoadAndroidKeyStore()480 private static KeyStore getAndLoadAndroidKeyStore() throws KeyStoreException { 481 KeyStore keyStore = KeyStore.getInstance(KeyStoreProxyImpl.ANDROID_KEY_STORE_PROVIDER); 482 try { 483 keyStore.load(/*param=*/ null); 484 } catch (CertificateException | IOException | NoSuchAlgorithmException e) { 485 // Should never happen. 486 throw new KeyStoreException("Unable to load keystore.", e); 487 } 488 return keyStore; 489 } 490 isDeviceSecure(int userId)491 private boolean isDeviceSecure(int userId) { 492 return mContext.getSystemService(KeyguardManager.class).isDeviceSecure(userId); 493 } 494 495 } 496