Debian Codegraph @

keystore/java/android/security/KeyStore2.java

raw symbols SCIP
1 /*
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
17 package android.security;
18
19 import android.annotation.NonNull;
20 import android.compat.annotation.ChangeId;
21 import android.compat.annotation.Disabled;
22 import android.os.Binder;
23 import android.os.RemoteException;
24 import android.os.ServiceManager;
25 import android.os.ServiceSpecificException;
26 import android.security.keymaster.KeymasterDefs;
27 import android.system.keystore2.Domain;
28 import android.system.keystore2.IKeystoreService;
29 import android.system.keystore2.KeyDescriptor;
30 import android.system.keystore2.KeyEntryResponse;
31 import android.system.keystore2.ResponseCode;
32 import android.util.Log;
33
34 import java.util.Calendar;
35
36 /**
37 * @hide This should not be made public in its present form because it
38 * assumes that private and secret key bytes are available and would
39 * preclude the use of hardware crypto.
40 */
41 public class KeyStore2 {
42 private static final String TAG = "KeyStore";
43
44 private static final int RECOVERY_GRACE_PERIOD_MS = 50;
45
46 /**
47 * Keystore operation creation may fail
48 *
49 * Keystore used to work under the assumption that the creation of cryptographic operations
50 * always succeeds. However, the KeyMint backend has only a limited number of operation slots.
51 * In order to keep up the appearance of "infinite" operation slots, the Keystore daemon
52 * would prune least recently used operations if there is no available operation slot.
53 * As a result, good operations could be terminated prematurely.
54 *
55 * This opens AndroidKeystore up to denial-of-service and unintended livelock situations.
56 * E.g.: if multiple apps wake up at the same time, e.g., due to power management optimizations,
57 * and attempt to perform crypto operations, they start terminating each others operations
58 * without making any progress.
59 *
60 * To break out of livelocks and to discourage DoS attempts we have changed the pruning
61 * strategy such that it prefers clients that use few operation slots and only briefly.
62 * As a result we can, almost, guarantee that single operations that don't linger inactive
63 * for more than 5 seconds will conclude unhampered by the pruning strategy. "Almost",
64 * because there are operations related to file system encryption that can prune even
65 * these operations, but those are extremely rare.
66 *
67 * As a side effect of this new pruning strategy operation creation can now fail if the
68 * client has a lower pruning power than all of the existing operations.
69 *
70 * Pruning strategy
71 *
72 * To find a suitable candidate we compute the malus for the caller and each existing
73 * operation. The malus is the inverse of the pruning power (caller) or pruning
74 * resistance (existing operation). For the caller to be able to prune an operation it must
75 * find an operation with a malus higher than its own.
76 *
77 * For more detail on the pruning strategy consult the implementation at
78 * https://android.googlesource.com/platform/system/security/+/refs/heads/master/keystore2/src/operation.rs
79 *
80 * For older SDK version, KeyStore2 will poll the Keystore daemon for a free operation
81 * slot. So to applications, targeting earlier SDK versions, it will still look like cipher and
82 * signature object initialization always succeeds, however, it may take longer to get an
83 * operation.
84 *
85 * All SDK version benefit from fairer operation slot scheduling and a better chance to
86 * successfully conclude an operation.
87 */
88 @ChangeId
89 @Disabled // See b/180133780
90 static final long KEYSTORE_OPERATION_CREATION_MAY_FAIL = 169897160L;
91
92 // Never use mBinder directly, use KeyStore2.getService() instead or better yet
93 // handleRemoteExceptionWithRetry which retries connecting to Keystore once in case
94 // of a remote exception.
95 private IKeystoreService mBinder;
96
97
98 @FunctionalInterface
99 interface CheckedRemoteRequest<R> {
100 R execute(IKeystoreService service) throws RemoteException;
101 }
102
103 private <R> R handleRemoteExceptionWithRetry(@NonNull CheckedRemoteRequest<R> request)
104 throws KeyStoreException {
105 IKeystoreService service = getService(false /* retryLookup */);
106 boolean firstTry = true;
107 while (true) {
108 try {
109 return request.execute(service);
110 } catch (ServiceSpecificException e) {
111 throw getKeyStoreException(e.errorCode, e.getMessage());
112 } catch (RemoteException e) {
113 if (firstTry) {
114 Log.w(TAG, "Looks like we may have lost connection to the Keystore "
115 + "daemon.");
116 Log.w(TAG, "Retrying after giving Keystore "
117 + RECOVERY_GRACE_PERIOD_MS + "ms to recover.");
118 interruptedPreservingSleep(RECOVERY_GRACE_PERIOD_MS);
119 service = getService(true /* retry Lookup */);
120 firstTry = false;
121 } else {
122 Log.e(TAG, "Cannot connect to Keystore daemon.", e);
123 throw new KeyStoreException(ResponseCode.SYSTEM_ERROR, "", e.getMessage());
124 }
125 }
126 }
127 }
128
129 private static final String KEYSTORE2_SERVICE_NAME =
130 "android.system.keystore2.IKeystoreService/default";
131
132 private KeyStore2() {
133 mBinder = null;
134 }
135
136 public static KeyStore2 getInstance() {
137 return new KeyStore2();
138 }
139
140 private synchronized IKeystoreService getService(boolean retryLookup) {
141 if (mBinder == null || retryLookup) {
142 mBinder = IKeystoreService.Stub.asInterface(ServiceManager
143 .getService(KEYSTORE2_SERVICE_NAME));
144 Binder.allowBlocking(mBinder.asBinder());
145 }
146 return mBinder;
147 }
148
149 void delete(KeyDescriptor descriptor) throws KeyStoreException {
150 handleRemoteExceptionWithRetry((service) -> {
151 service.deleteKey(descriptor);
152 return 0;
153 });
154 }
155
156 /**
157 * List all entries in the keystore for in the given namespace.
158 */
159 public KeyDescriptor[] list(int domain, long namespace) throws KeyStoreException {
160 return handleRemoteExceptionWithRetry((service) -> service.listEntries(domain, namespace));
161 }
162
163 /**
164 * List all entries in the keystore for in the given namespace.
165 */
166 public KeyDescriptor[] listBatch(int domain, long namespace, String startPastAlias)
167 throws KeyStoreException {
168 return handleRemoteExceptionWithRetry(
169 (service) -> service.listEntriesBatched(domain, namespace, startPastAlias));
170 }
171
172 /**
173 * Grant string prefix as used by the keystore boringssl engine. Must be kept in sync
174 * with system/security/keystore-engine. Note: The prefix here includes the 0x which
175 * std::stringstream used in keystore-engine needs to identify the number as hex represented.
176 * Here we include it in the prefix, because Long#parseUnsignedLong does not understand it
177 * and gets the radix as explicit argument.
178 * @hide
179 */
180 private static final String KEYSTORE_ENGINE_GRANT_ALIAS_PREFIX =
181 "ks2_keystore-engine_grant_id:0x";
182
183 /**
184 * This function turns a grant identifier into a specific string that is understood by the
185 * keystore-engine in system/security/keystore-engine. Is only used by VPN and WI-FI components
186 * to allow certain system components like racoon or vendor components like WPA supplicant
187 * to use keystore keys with boring ssl.
188 *
189 * @param grantId the grant id as returned by {@link #grant} in the {@code nspace} filed of
190 * the resulting {@code KeyDescriptor}.
191 * @return The grant descriptor string.
192 * @hide
193 */
194 public static String makeKeystoreEngineGrantString(long grantId) {
195 return String.format("%s%016X", KEYSTORE_ENGINE_GRANT_ALIAS_PREFIX, grantId);
196 }
197
198 /**
199 * Convenience function to turn a keystore engine grant string as returned by
200 * {@link #makeKeystoreEngineGrantString(long)} back into a grant KeyDescriptor.
201 *
202 * @param grantString As string returned by {@link #makeKeystoreEngineGrantString(long)}
203 * @return The grant key descriptor.
204 * @hide
205 */
206 public static KeyDescriptor keystoreEngineGrantString2KeyDescriptor(String grantString) {
207 KeyDescriptor key = new KeyDescriptor();
208 key.domain = Domain.GRANT;
209 key.nspace = Long.parseUnsignedLong(
210 grantString.substring(KEYSTORE_ENGINE_GRANT_ALIAS_PREFIX.length()), 16);
211 key.alias = null;
212 key.blob = null;
213 return key;
214 }
215
216 /**
217 * Create a grant that allows the grantee identified by {@code granteeUid} to use
218 * the key specified by {@code descriptor} withint the restrictions given by
219 * {@code accessVectore}.
220 * @see IKeystoreService#grant(KeyDescriptor, int, int) for more details.
221 * @param descriptor
222 * @param granteeUid
223 * @param accessVector
224 * @return
225 * @throws KeyStoreException
226 * @hide
227 */
228 public KeyDescriptor grant(KeyDescriptor descriptor, int granteeUid, int accessVector)
229 throws KeyStoreException {
230 return handleRemoteExceptionWithRetry(
231 (service) -> service.grant(descriptor, granteeUid, accessVector)
232 );
233 }
234
235 /**
236 * Destroys a grant.
237 * @see IKeystoreService#ungrant(KeyDescriptor, int) for more details.
238 * @param descriptor
239 * @param granteeUid
240 * @throws KeyStoreException
241 * @hide
242 */
243 public void ungrant(KeyDescriptor descriptor, int granteeUid)
244 throws KeyStoreException {
245 handleRemoteExceptionWithRetry((service) -> {
246 service.ungrant(descriptor, granteeUid);
247 return 0;
248 });
249 }
250
251 /**
252 * Retrieves a key entry from the keystore backend.
253 * @see IKeystoreService#getKeyEntry(KeyDescriptor) for more details.
254 * @param descriptor
255 * @return
256 * @throws KeyStoreException
257 * @hide
258 */
259 public KeyEntryResponse getKeyEntry(@NonNull KeyDescriptor descriptor)
260 throws KeyStoreException {
261 return handleRemoteExceptionWithRetry((service) -> service.getKeyEntry(descriptor));
262 }
263
264 /**
265 * Get the security level specific keystore interface from the keystore daemon.
266 * @see IKeystoreService#getSecurityLevel(int) for more details.
267 * @param securityLevel
268 * @return
269 * @throws KeyStoreException
270 * @hide
271 */
272 public KeyStoreSecurityLevel getSecurityLevel(int securityLevel)
273 throws KeyStoreException {
274 return handleRemoteExceptionWithRetry((service) ->
275 new KeyStoreSecurityLevel(
276 service.getSecurityLevel(securityLevel)
277 )
278 );
279 }
280
281 /**
282 * Update the subcomponents of a key entry designated by the key descriptor.
283 * @see IKeystoreService#updateSubcomponent(KeyDescriptor, byte[], byte[]) for more details.
284 * @param key
285 * @param publicCert
286 * @param publicCertChain
287 * @throws KeyStoreException
288 * @hide
289 */
290 public void updateSubcomponents(@NonNull KeyDescriptor key, byte[] publicCert,
291 byte[] publicCertChain) throws KeyStoreException {
292 handleRemoteExceptionWithRetry((service) -> {
293 service.updateSubcomponent(key, publicCert, publicCertChain);
294 return 0;
295 });
296 }
297
298 /**
299 * Delete the key designed by the key descriptor.
300 * @see IKeystoreService#deleteKey(KeyDescriptor) for more details.
301 * @param descriptor
302 * @throws KeyStoreException
303 * @hide
304 */
305 public void deleteKey(@NonNull KeyDescriptor descriptor)
306 throws KeyStoreException {
307 handleRemoteExceptionWithRetry((service) -> {
308 service.deleteKey(descriptor);
309 return 0;
310 });
311 }
312
313 /**
314 * Returns the number of Keystore entries for a given domain and namespace.
315 */
316 public int getNumberOfEntries(int domain, long namespace) throws KeyStoreException {
317 return handleRemoteExceptionWithRetry((service)
318 -> service.getNumberOfEntries(domain, namespace));
319 }
320 protected static void interruptedPreservingSleep(long millis) {
321 boolean wasInterrupted = false;
322 Calendar calendar = Calendar.getInstance();
323 long target = calendar.getTimeInMillis() + millis;
324 while (true) {
325 try {
326 Thread.sleep(target - calendar.getTimeInMillis());
327 break;
328 } catch (InterruptedException e) {
329 wasInterrupted = true;
330 } catch (IllegalArgumentException e) {
331 // This means that the argument to sleep was negative.
332 // So we are done sleeping.
333 break;
334 }
335 }
336 if (wasInterrupted) {
337 Thread.currentThread().interrupt();
338 }
339 }
340
341 static KeyStoreException getKeyStoreException(int errorCode, String serviceErrorMessage) {
342 if (errorCode > 0) {
343 // KeyStore layer error
344 switch (errorCode) {
345 case ResponseCode.LOCKED:
346 return new KeyStoreException(errorCode, "User authentication required",
347 serviceErrorMessage);
348 case ResponseCode.UNINITIALIZED:
349 return new KeyStoreException(errorCode, "Keystore not initialized",
350 serviceErrorMessage);
351 case ResponseCode.SYSTEM_ERROR:
352 return new KeyStoreException(errorCode, "System error", serviceErrorMessage);
353 case ResponseCode.PERMISSION_DENIED:
354 return new KeyStoreException(errorCode, "Permission denied",
355 serviceErrorMessage);
356 case ResponseCode.KEY_NOT_FOUND:
357 return new KeyStoreException(errorCode, "Key not found", serviceErrorMessage);
358 case ResponseCode.VALUE_CORRUPTED:
359 return new KeyStoreException(errorCode, "Key blob corrupted",
360 serviceErrorMessage);
361 case ResponseCode.KEY_PERMANENTLY_INVALIDATED:
362 return new KeyStoreException(errorCode, "Key permanently invalidated",
363 serviceErrorMessage);
364 case ResponseCode.OUT_OF_KEYS:
365 // Getting a more specific RKP status requires the security level, which we
366 // don't have here. Higher layers of the stack can interpret this exception
367 // and add more flavor.
368 return new KeyStoreException(errorCode, serviceErrorMessage,
369 KeyStoreException.RKP_TEMPORARILY_UNAVAILABLE);
370 default:
371 return new KeyStoreException(errorCode, String.valueOf(errorCode),
372 serviceErrorMessage);
373 }
374 } else {
375 // Keymaster layer error
376 switch (errorCode) {
377 case KeymasterDefs.KM_ERROR_INVALID_AUTHORIZATION_TIMEOUT:
378 // The name of this parameter significantly differs between Keymaster and
379 // framework APIs. Use the framework wording to make life easier for developers.
380 return new KeyStoreException(errorCode,
381 "Invalid user authentication validity duration",
382 serviceErrorMessage);
383 default:
384 return new KeyStoreException(errorCode,
385 KeymasterDefs.getErrorMessage(errorCode),
386 serviceErrorMessage);
387 }
388 }
389 }
390
391 }