blob: d38ee678c7aab5286404f5e1f61b78b3d70d2c08 [file] [log] [blame]
Rubin Xua3c71a12019-12-04 15:25:02 +00001/*
2 * Copyright (C) 2020 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;
18
19import android.annotation.Nullable;
20import android.content.pm.UserInfo;
21import android.os.UserHandle;
22import android.os.UserManager;
23import android.security.keystore.AndroidKeyStoreSpi;
24import android.security.keystore.KeyGenParameterSpec;
25import android.security.keystore.KeyProperties;
26import android.security.keystore.UserNotAuthenticatedException;
27import android.util.Slog;
28import android.util.SparseArray;
29
30import com.android.internal.widget.LockscreenCredential;
31
32import java.security.GeneralSecurityException;
33import java.security.Key;
34import java.security.KeyStore;
35import java.security.KeyStoreException;
36import java.security.NoSuchAlgorithmException;
37import java.security.UnrecoverableKeyException;
38import java.util.Arrays;
39import java.util.concurrent.TimeUnit;
40
41import javax.crypto.Cipher;
42import javax.crypto.KeyGenerator;
43import javax.crypto.SecretKey;
44import javax.crypto.spec.GCMParameterSpec;
45
46/**
47 * Caches *unified* work challenge for user 0's managed profiles. Only user 0's profile is supported
48 * at the moment because the cached credential is encrypted using a keystore key auth-bound to
49 * user 0: this is to match how unified work challenge is similarly auth-bound to its parent user's
50 * lockscreen credential normally. It's possible to extend this class to support managed profiles
51 * for secondary users, that will require generating auth-bound keys to their corresponding parent
52 * user though (which {@link KeyGenParameterSpec} does not support right now).
53 *
54 * <p> The cache is filled whenever the managed profile's unified challenge is created or derived
55 * (as part of the parent user's credential verification flow). It's removed when the profile is
56 * deleted or a (separate) lockscreen credential is explicitly set on the profile. There is also
57 * an ADB command to evict the cache "cmd lock_settings remove-cache --user X", to assist
58 * development and testing.
59
60 * <p> The encrypted credential is stored in-memory only so the cache does not persist across
61 * reboots.
62 */
63public class ManagedProfilePasswordCache {
64
65 private static final String TAG = "ManagedProfilePasswordCache";
66 private static final int KEY_LENGTH = 256;
67 private static final int CACHE_TIMEOUT_SECONDS = (int) TimeUnit.DAYS.toSeconds(7);
68
69 private final SparseArray<byte[]> mEncryptedPasswords = new SparseArray<>();
70 private final KeyStore mKeyStore;
71 private final UserManager mUserManager;
72
73 public ManagedProfilePasswordCache(KeyStore keyStore, UserManager userManager) {
74 mKeyStore = keyStore;
75 mUserManager = userManager;
76 }
77
78 /**
79 * Encrypt and store the password in the cache. Does NOT overwrite existing password cache
80 * if one for the given user already exists.
81 */
82 public void storePassword(int userId, LockscreenCredential password) {
83 synchronized (mEncryptedPasswords) {
84 if (mEncryptedPasswords.contains(userId)) {
85 return;
86 }
87 UserInfo parent = mUserManager.getProfileParent(userId);
88 if (parent == null || parent.id != UserHandle.USER_SYSTEM) {
89 // Since the cached password is encrypted using a keystore key auth-bound to user 0,
90 // only support caching password for user 0's profile.
91 return;
92 }
93 String keyName = getEncryptionKeyName(userId);
94 KeyGenerator generator;
95 SecretKey key;
96 try {
97 generator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES,
98 AndroidKeyStoreSpi.NAME);
99 generator.init(new KeyGenParameterSpec.Builder(
100 keyName, KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
101 .setKeySize(KEY_LENGTH)
102 .setBlockModes(KeyProperties.BLOCK_MODE_GCM)
103 .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
104 // Generate auth-bound key to user 0 (since we the caller is user 0)
105 .setUserAuthenticationRequired(true)
106 .setUserAuthenticationValidityDurationSeconds(CACHE_TIMEOUT_SECONDS)
107 // Only accessible after user 0's keyguard is unlocked
108 .setUnlockedDeviceRequired(true)
109 .build());
110 key = generator.generateKey();
111 } catch (GeneralSecurityException e) {
112 Slog.e(TAG, "Cannot generate key", e);
113 return;
114 }
115
116 Cipher cipher;
117 try {
118 cipher = Cipher.getInstance("AES/GCM/NoPadding");
119 cipher.init(Cipher.ENCRYPT_MODE, key);
120 byte[] ciphertext = cipher.doFinal(password.getCredential());
121 byte[] iv = cipher.getIV();
122 byte[] block = Arrays.copyOf(iv, ciphertext.length + iv.length);
123 System.arraycopy(ciphertext, 0, block, iv.length, ciphertext.length);
124 mEncryptedPasswords.put(userId, block);
125 } catch (GeneralSecurityException e) {
126 Slog.d(TAG, "Cannot encrypt", e);
127 }
128 }
129 }
130
131 /** Attempt to retrieve the password for the given user. Returns {@code null} if it's not in the
132 * cache or if decryption fails.
133 */
134 public @Nullable LockscreenCredential retrievePassword(int userId) {
135 synchronized (mEncryptedPasswords) {
136 byte[] block = mEncryptedPasswords.get(userId);
137 if (block == null) {
138 return null;
139 }
140 Key key;
141 try {
142 key = mKeyStore.getKey(getEncryptionKeyName(userId), null);
143 } catch (UnrecoverableKeyException | KeyStoreException | NoSuchAlgorithmException e) {
144 Slog.d(TAG, "Cannot get key", e);
145 return null;
146 }
147 if (key == null) {
148 return null;
149 }
150 byte[] iv = Arrays.copyOf(block, 12);
151 byte[] ciphertext = Arrays.copyOfRange(block, 12, block.length);
152 byte[] credential;
153 try {
154 Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
155 cipher.init(Cipher.DECRYPT_MODE, key, new GCMParameterSpec(128, iv));
156 credential = cipher.doFinal(ciphertext);
157 } catch (UserNotAuthenticatedException e) {
158 Slog.i(TAG, "Device not unlocked for more than 7 days");
159 return null;
160 } catch (GeneralSecurityException e) {
161 Slog.d(TAG, "Cannot decrypt", e);
162 return null;
163 }
164 LockscreenCredential result = LockscreenCredential.createManagedPassword(credential);
165 Arrays.fill(credential, (byte) 0);
166 return result;
167 }
168 }
169
170 /** Remove the given user's password from cache, if one exists. */
171 public void removePassword(int userId) {
172 synchronized (mEncryptedPasswords) {
173 String keyName = getEncryptionKeyName(userId);
174 try {
175 if (mKeyStore.containsAlias(keyName)) {
176 mKeyStore.deleteEntry(keyName);
177 }
178 } catch (KeyStoreException e) {
179 Slog.d(TAG, "Cannot delete key", e);
180 }
181 if (mEncryptedPasswords.contains(userId)) {
182 Arrays.fill(mEncryptedPasswords.get(userId), (byte) 0);
183 mEncryptedPasswords.remove(userId);
184 }
185 }
186 }
187
188 private static String getEncryptionKeyName(int userId) {
189 return "com.android.server.locksettings.unified_profile_cache_" + userId;
190 }
191}