blob: ee8cc40622f826def2ac194d9229636616b0db72 [file] [log] [blame]
Chia-chi Yeh44039172009-09-21 11:53:59 +08001/*
2 * Copyright (C) 2009 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 android.security;
18
Mathew Inwoode420f8b2018-08-16 18:40:47 +010019import android.annotation.UnsupportedAppUsage;
Svetoslav2dac95d2015-04-30 11:30:33 -070020import android.app.ActivityThread;
21import android.app.Application;
Alex Klyubin54183932015-05-08 15:25:48 -070022import android.app.KeyguardManager;
Alex Klyubin708fc9402015-04-28 18:58:47 -070023import android.content.Context;
Kevin Chyn55966422017-10-23 16:08:47 -070024import android.content.pm.PackageManager;
Kevin Chyn057b7432018-09-24 14:36:39 -070025import android.hardware.face.FaceManager;
Alex Klyubin2d7a85c2015-04-30 11:43:53 -070026import android.hardware.fingerprint.FingerprintManager;
Chad Brubakere6a461342015-02-10 21:33:23 -080027import android.os.Binder;
Mathew Inwood31755f92018-12-20 13:53:36 +000028import android.os.Build;
Chad Brubakere6a461342015-02-10 21:33:23 -080029import android.os.IBinder;
Chad Brubakera91a8502015-05-07 10:02:22 -070030import android.os.Process;
Kenny Root6b776452012-11-02 15:40:32 -070031import android.os.RemoteException;
32import android.os.ServiceManager;
Chad Brubakera91a8502015-05-07 10:02:22 -070033import android.os.UserHandle;
Janis Danisevskis1864c952018-08-09 11:14:49 -070034import android.security.KeyStoreException;
Chad Brubakere6a461342015-02-10 21:33:23 -080035import android.security.keymaster.ExportResult;
36import android.security.keymaster.KeyCharacteristics;
37import android.security.keymaster.KeymasterArguments;
Chad Brubaker5e73c0e2015-03-21 22:46:43 -070038import android.security.keymaster.KeymasterBlob;
Shawn Willden8d8c7472016-02-02 08:27:39 -070039import android.security.keymaster.KeymasterCertificateChain;
Alex Klyubinb4834ae2015-04-02 15:53:46 -070040import android.security.keymaster.KeymasterDefs;
Chad Brubakere6a461342015-02-10 21:33:23 -080041import android.security.keymaster.OperationResult;
Janis Danisevskisb0358e72018-11-02 10:34:07 -070042import android.security.keystore.IKeystoreService;
Alex Klyubin3f8d4d82015-05-13 09:15:00 -070043import android.security.keystore.KeyExpiredException;
44import android.security.keystore.KeyNotYetValidException;
45import android.security.keystore.KeyPermanentlyInvalidatedException;
Janis Danisevskis1864c952018-08-09 11:14:49 -070046import android.security.keystore.KeyProperties;
Janis Danisevskisb0358e72018-11-02 10:34:07 -070047import android.security.keystore.KeystoreResponse;
Alex Klyubin3f8d4d82015-05-13 09:15:00 -070048import android.security.keystore.UserNotAuthenticatedException;
Kenny Root6b776452012-11-02 15:40:32 -070049import android.util.Log;
Janis Danisevskisc9277ffd2019-03-27 15:50:28 -070050
Janis Danisevskis1864c952018-08-09 11:14:49 -070051import com.android.org.bouncycastle.asn1.ASN1InputStream;
52import com.android.org.bouncycastle.asn1.pkcs.PrivateKeyInfo;
Janis Danisevskisc9277ffd2019-03-27 15:50:28 -070053
Janis Danisevskis1864c952018-08-09 11:14:49 -070054import java.io.ByteArrayInputStream;
55import java.io.IOException;
Janis Danisevskisc9277ffd2019-03-27 15:50:28 -070056import java.math.BigInteger;
Alex Klyubinad9ba102015-04-21 15:17:24 -070057import java.security.InvalidKeyException;
Rob Barnesebe26742018-11-13 15:57:22 -070058import java.util.ArrayList;
Janis Danisevskis2b106ad2018-11-15 09:27:16 -080059import java.util.Date;
Alex Klyubin708fc9402015-04-28 18:58:47 -070060import java.util.List;
Kenny Rootb91773b2013-09-05 13:03:16 -070061import java.util.Locale;
Janis Danisevskisb0358e72018-11-02 10:34:07 -070062import java.util.concurrent.CompletableFuture;
63import java.util.concurrent.ExecutionException;
Janis Danisevskisc9277ffd2019-03-27 15:50:28 -070064
Janis Danisevskis1864c952018-08-09 11:14:49 -070065import sun.security.util.ObjectIdentifier;
66import sun.security.x509.AlgorithmId;
Kenny Rootb91773b2013-09-05 13:03:16 -070067
Chia-chi Yeh44039172009-09-21 11:53:59 +080068/**
Brian Carlstrom46703b02011-04-06 15:41:29 -070069 * @hide This should not be made public in its present form because it
70 * assumes that private and secret key bytes are available and would
71 * preclude the use of hardware crypto.
Chia-chi Yeh44039172009-09-21 11:53:59 +080072 */
73public class KeyStore {
Kenny Root6b776452012-11-02 15:40:32 -070074 private static final String TAG = "KeyStore";
Brian Carlstrom5cfee3f2011-05-31 01:00:15 -070075
Dmitry Dementyevefc43112017-10-27 23:10:28 -070076 // ResponseCodes - see system/security/keystore/include/keystore/keystore.h
Mathew Inwoode420f8b2018-08-16 18:40:47 +010077 @UnsupportedAppUsage
Brian Carlstrom7e4b1a42011-06-01 15:29:29 -070078 public static final int NO_ERROR = 1;
79 public static final int LOCKED = 2;
80 public static final int UNINITIALIZED = 3;
81 public static final int SYSTEM_ERROR = 4;
82 public static final int PROTOCOL_ERROR = 5;
83 public static final int PERMISSION_DENIED = 6;
84 public static final int KEY_NOT_FOUND = 7;
85 public static final int VALUE_CORRUPTED = 8;
86 public static final int UNDEFINED_ACTION = 9;
87 public static final int WRONG_PASSWORD = 10;
Janis Danisevskisd2575382018-10-08 07:56:58 -070088 public static final int KEY_ALREADY_EXISTS = 16;
Eran Messeri61692392018-03-26 16:43:14 +010089 public static final int CANNOT_ATTEST_IDS = -66;
Frank Salimea5e0382018-01-23 22:42:29 -080090 public static final int HARDWARE_TYPE_UNAVAILABLE = -68;
Brian Carlstrom5cfee3f2011-05-31 01:00:15 -070091
Chad Brubaker560d6532015-04-24 10:32:18 -070092 /**
93 * Per operation authentication is needed before this operation is valid.
94 * This is returned from {@link #begin} when begin succeeds but the operation uses
95 * per-operation authentication and must authenticate before calling {@link #update} or
96 * {@link #finish}.
97 */
98 public static final int OP_AUTH_NEEDED = 15;
99
Max Bires13f98ce2018-11-02 10:50:40 -0700100 // Used when a user changes their pin, invalidating old auth bound keys.
101 public static final int KEY_PERMANENTLY_INVALIDATED = 17;
102
Kenny Root2eeda722013-04-10 11:30:58 -0700103 // Used for UID field to indicate the calling UID.
104 public static final int UID_SELF = -1;
105
106 // Flags for "put" "import" and "generate"
107 public static final int FLAG_NONE = 0;
Alex Klyubin54183932015-05-08 15:25:48 -0700108
109 /**
110 * Indicates that this key (or key pair) must be encrypted at rest. This will protect the key
111 * (or key pair) with the secure lock screen credential (e.g., password, PIN, or pattern).
112 *
113 * <p>Note that this requires that the secure lock screen (e.g., password, PIN, pattern) is set
114 * up, otherwise key (or key pair) generation or import will fail. Moreover, this key (or key
115 * pair) will be deleted when the secure lock screen is disabled or reset (e.g., by the user or
116 * a Device Administrator). Finally, this key (or key pair) cannot be used until the user
117 * unlocks the secure lock screen after boot.
118 *
119 * @see KeyguardManager#isDeviceSecure()
120 */
Kenny Roota3788b02013-04-10 10:37:55 -0700121 public static final int FLAG_ENCRYPTED = 1;
122
Rubin Xu12b644d2017-04-21 19:21:42 +0100123 /**
Janis Danisevskis0aadf932017-12-18 17:28:52 -0800124 * Select Software keymaster device, which as of this writing is the lowest security
125 * level available on an android device. If neither FLAG_STRONGBOX nor FLAG_SOFTWARE is provided
126 * A TEE based keymaster implementation is implied.
127 *
128 * Need to be in sync with KeyStoreFlag in system/security/keystore/include/keystore/keystore.h
129 * For historical reasons this corresponds to the KEYSTORE_FLAG_FALLBACK flag.
130 */
131 public static final int FLAG_SOFTWARE = 1 << 1;
132
133 /**
Rubin Xu12b644d2017-04-21 19:21:42 +0100134 * A private flag that's only available to system server to indicate that this key is part of
135 * device encryption flow so it receives special treatment from keystore. For example this key
136 * will not be super encrypted, and it will be stored separately under an unique UID instead
137 * of the caller UID i.e. SYSTEM.
138 *
139 * Need to be in sync with KeyStoreFlag in system/security/keystore/include/keystore/keystore.h
140 */
141 public static final int FLAG_CRITICAL_TO_DEVICE_ENCRYPTION = 1 << 3;
142
Janis Danisevskis0aadf932017-12-18 17:28:52 -0800143 /**
144 * Select Strongbox keymaster device, which as of this writing the the highest security level
145 * available an android devices. If neither FLAG_STRONGBOX nor FLAG_SOFTWARE is provided
146 * A TEE based keymaster implementation is implied.
147 *
148 * Need to be in sync with KeyStoreFlag in system/security/keystore/include/keystore/keystore.h
149 */
150 public static final int FLAG_STRONGBOX = 1 << 4;
151
Brian Carlstrom5cfee3f2011-05-31 01:00:15 -0700152 // States
Mathew Inwoodefb48162018-08-01 10:24:49 +0100153 public enum State {
Mathew Inwoode420f8b2018-08-16 18:40:47 +0100154 @UnsupportedAppUsage
Mathew Inwoodefb48162018-08-01 10:24:49 +0100155 UNLOCKED,
Mathew Inwoode420f8b2018-08-16 18:40:47 +0100156 @UnsupportedAppUsage
Mathew Inwoodefb48162018-08-01 10:24:49 +0100157 LOCKED,
158 UNINITIALIZED
159 };
Chia-chi Yeh44039172009-09-21 11:53:59 +0800160
Chia-chi Yeh44039172009-09-21 11:53:59 +0800161 private int mError = NO_ERROR;
162
Kenny Root6b776452012-11-02 15:40:32 -0700163 private final IKeystoreService mBinder;
Alex Klyubin2d7a85c2015-04-30 11:43:53 -0700164 private final Context mContext;
Kenny Root6b776452012-11-02 15:40:32 -0700165
Chad Brubakere6a461342015-02-10 21:33:23 -0800166 private IBinder mToken;
167
Kenny Root6b776452012-11-02 15:40:32 -0700168 private KeyStore(IKeystoreService binder) {
169 mBinder = binder;
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700170 mContext = getApplicationContext();
Alex Klyubin2d7a85c2015-04-30 11:43:53 -0700171 }
172
Mathew Inwoode420f8b2018-08-16 18:40:47 +0100173 @UnsupportedAppUsage
Alex Klyubindcdaf872015-05-13 15:57:09 -0700174 public static Context getApplicationContext() {
Alex Klyubina99b8b52015-06-11 13:27:34 -0700175 Application application = ActivityThread.currentApplication();
Alex Klyubin2d7a85c2015-04-30 11:43:53 -0700176 if (application == null) {
177 throw new IllegalStateException(
Alex Klyubina99b8b52015-06-11 13:27:34 -0700178 "Failed to obtain application Context from ActivityThread");
Alex Klyubin2d7a85c2015-04-30 11:43:53 -0700179 }
180 return application;
Kenny Root6b776452012-11-02 15:40:32 -0700181 }
Chia-chi Yeh44039172009-09-21 11:53:59 +0800182
Mathew Inwoode420f8b2018-08-16 18:40:47 +0100183 @UnsupportedAppUsage
Chia-chi Yeh44039172009-09-21 11:53:59 +0800184 public static KeyStore getInstance() {
Kenny Root6b776452012-11-02 15:40:32 -0700185 IKeystoreService keystore = IKeystoreService.Stub.asInterface(ServiceManager
186 .getService("android.security.keystore"));
187 return new KeyStore(keystore);
Chia-chi Yeh44039172009-09-21 11:53:59 +0800188 }
189
Chad Brubakere6a461342015-02-10 21:33:23 -0800190 private synchronized IBinder getToken() {
191 if (mToken == null) {
192 mToken = new Binder();
193 }
194 return mToken;
195 }
196
Mathew Inwoode420f8b2018-08-16 18:40:47 +0100197 @UnsupportedAppUsage
Chad Brubakere35d49f2015-05-12 15:19:52 -0700198 public State state(int userId) {
Kenny Root6b776452012-11-02 15:40:32 -0700199 final int ret;
200 try {
Chad Brubakere35d49f2015-05-12 15:19:52 -0700201 ret = mBinder.getState(userId);
Kenny Root6b776452012-11-02 15:40:32 -0700202 } catch (RemoteException e) {
203 Log.w(TAG, "Cannot connect to keystore", e);
204 throw new AssertionError(e);
205 }
206
207 switch (ret) {
Brian Carlstrom5cfee3f2011-05-31 01:00:15 -0700208 case NO_ERROR: return State.UNLOCKED;
209 case LOCKED: return State.LOCKED;
210 case UNINITIALIZED: return State.UNINITIALIZED;
211 default: throw new AssertionError(mError);
212 }
Chia-chi Yeh44039172009-09-21 11:53:59 +0800213 }
214
Mathew Inwoode420f8b2018-08-16 18:40:47 +0100215 @UnsupportedAppUsage
Chad Brubakere35d49f2015-05-12 15:19:52 -0700216 public State state() {
217 return state(UserHandle.myUserId());
218 }
219
Kenny Rootb9594ce2013-02-14 10:18:38 -0800220 public boolean isUnlocked() {
221 return state() == State.UNLOCKED;
222 }
223
Chad Brubaker5bbf0482015-09-09 14:53:52 -0700224 public byte[] get(String key, int uid) {
Irina Dumitrescu4a1cccc2018-06-08 19:36:34 +0100225 return get(key, uid, false);
Chia-chi Yeh44039172009-09-21 11:53:59 +0800226 }
227
Mathew Inwoode420f8b2018-08-16 18:40:47 +0100228 @UnsupportedAppUsage
Chad Brubaker5bbf0482015-09-09 14:53:52 -0700229 public byte[] get(String key) {
230 return get(key, UID_SELF);
231 }
232
Irina Dumitrescu4a1cccc2018-06-08 19:36:34 +0100233 public byte[] get(String key, int uid, boolean suppressKeyNotFoundWarning) {
234 try {
235 key = key != null ? key : "";
236 return mBinder.get(key, uid);
237 } catch (RemoteException e) {
238 Log.w(TAG, "Cannot connect to keystore", e);
239 return null;
240 } catch (android.os.ServiceSpecificException e) {
241 if (!suppressKeyNotFoundWarning || e.errorCode != KEY_NOT_FOUND) {
242 Log.w(TAG, "KeyStore exception", e);
243 }
244 return null;
245 }
246 }
247
248 public byte[] get(String key, boolean suppressKeyNotFoundWarning) {
249 return get(key, UID_SELF, suppressKeyNotFoundWarning);
250 }
251
252
Kenny Roota3788b02013-04-10 10:37:55 -0700253 public boolean put(String key, byte[] value, int uid, int flags) {
Alex Klyubin3ceb1a02015-06-05 15:51:06 -0700254 return insert(key, value, uid, flags) == NO_ERROR;
255 }
256
257 public int insert(String key, byte[] value, int uid, int flags) {
Kenny Root6b776452012-11-02 15:40:32 -0700258 try {
Dmitry Dementyevefc43112017-10-27 23:10:28 -0700259 if (value == null) {
260 value = new byte[0];
261 }
Janis Danisevskisd2575382018-10-08 07:56:58 -0700262 int error = mBinder.insert(key, value, uid, flags);
263 if (error == KEY_ALREADY_EXISTS) {
264 mBinder.del(key, uid);
265 error = mBinder.insert(key, value, uid, flags);
266 }
267 return error;
Kenny Root78ad8492013-02-13 17:02:57 -0800268 } catch (RemoteException e) {
269 Log.w(TAG, "Cannot connect to keystore", e);
Alex Klyubin3ceb1a02015-06-05 15:51:06 -0700270 return SYSTEM_ERROR;
Kenny Root78ad8492013-02-13 17:02:57 -0800271 }
272 }
273
Janis Danisevskis906147c2018-11-06 14:14:05 -0800274 int delete2(String key, int uid) {
Kenny Root78ad8492013-02-13 17:02:57 -0800275 try {
Janis Danisevskis906147c2018-11-06 14:14:05 -0800276 return mBinder.del(key, uid);
Kenny Root6b776452012-11-02 15:40:32 -0700277 } catch (RemoteException e) {
278 Log.w(TAG, "Cannot connect to keystore", e);
Janis Danisevskis906147c2018-11-06 14:14:05 -0800279 return SYSTEM_ERROR;
Kenny Root6b776452012-11-02 15:40:32 -0700280 }
Chia-chi Yeh44039172009-09-21 11:53:59 +0800281 }
282
Janis Danisevskis906147c2018-11-06 14:14:05 -0800283 public boolean delete(String key, int uid) {
284 int ret = delete2(key, uid);
285 return ret == NO_ERROR || ret == KEY_NOT_FOUND;
286 }
287
Mathew Inwoode420f8b2018-08-16 18:40:47 +0100288 @UnsupportedAppUsage
Chia-chi Yeh44039172009-09-21 11:53:59 +0800289 public boolean delete(String key) {
Kenny Root2eeda722013-04-10 11:30:58 -0700290 return delete(key, UID_SELF);
Kenny Root78ad8492013-02-13 17:02:57 -0800291 }
292
293 public boolean contains(String key, int uid) {
Kenny Root6b776452012-11-02 15:40:32 -0700294 try {
Kenny Root78ad8492013-02-13 17:02:57 -0800295 return mBinder.exist(key, uid) == NO_ERROR;
Kenny Root6b776452012-11-02 15:40:32 -0700296 } catch (RemoteException e) {
297 Log.w(TAG, "Cannot connect to keystore", e);
298 return false;
299 }
Chia-chi Yeh44039172009-09-21 11:53:59 +0800300 }
301
302 public boolean contains(String key) {
Kenny Root2eeda722013-04-10 11:30:58 -0700303 return contains(key, UID_SELF);
Chia-chi Yeh44039172009-09-21 11:53:59 +0800304 }
305
Chad Brubakere35d49f2015-05-12 15:19:52 -0700306 /**
307 * List all entries in the keystore for {@code uid} starting with {@code prefix}.
308 */
309 public String[] list(String prefix, int uid) {
Kenny Root6b776452012-11-02 15:40:32 -0700310 try {
Chad Brubakere35d49f2015-05-12 15:19:52 -0700311 return mBinder.list(prefix, uid);
Kenny Root6b776452012-11-02 15:40:32 -0700312 } catch (RemoteException e) {
313 Log.w(TAG, "Cannot connect to keystore", e);
Chia-chi Yeh44039172009-09-21 11:53:59 +0800314 return null;
Dmitry Dementyevefc43112017-10-27 23:10:28 -0700315 } catch (android.os.ServiceSpecificException e) {
316 Log.w(TAG, "KeyStore exception", e);
317 return null;
Chia-chi Yeh44039172009-09-21 11:53:59 +0800318 }
Chia-chi Yeh44039172009-09-21 11:53:59 +0800319 }
320
Rob Barnesf1a678e2018-11-13 15:57:22 -0700321 /**
Rob Barnesebe26742018-11-13 15:57:22 -0700322 * List uids of all keys that are auth bound to the current user.
Rob Barnesf1a678e2018-11-13 15:57:22 -0700323 * Only system is allowed to call this method.
324 */
325 @UnsupportedAppUsage
326 public int[] listUidsOfAuthBoundKeys() {
Rob Barnesebe26742018-11-13 15:57:22 -0700327 // uids are returned as a list of strings because list of integers
328 // as an output parameter is not supported by aidl-cpp.
329 List<String> uidsOut = new ArrayList<>();
Rob Barnesf1a678e2018-11-13 15:57:22 -0700330 try {
331 int rc = mBinder.listUidsOfAuthBoundKeys(uidsOut);
332 if (rc != NO_ERROR) {
333 Log.w(TAG, String.format("listUidsOfAuthBoundKeys failed with error code %d", rc));
334 return null;
335 }
336 } catch (RemoteException e) {
337 Log.w(TAG, "Cannot connect to keystore", e);
338 return null;
339 } catch (android.os.ServiceSpecificException e) {
340 Log.w(TAG, "KeyStore exception", e);
341 return null;
342 }
Rob Barnesebe26742018-11-13 15:57:22 -0700343 // Turn list of strings into an array of uid integers.
344 return uidsOut.stream().mapToInt(Integer::parseInt).toArray();
Rob Barnesf1a678e2018-11-13 15:57:22 -0700345 }
346
Chad Brubakere35d49f2015-05-12 15:19:52 -0700347 public String[] list(String prefix) {
348 return list(prefix, UID_SELF);
349 }
350
Mathew Inwood31755f92018-12-20 13:53:36 +0000351 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
Chia-chi Yeh44039172009-09-21 11:53:59 +0800352 public boolean reset() {
Kenny Root6b776452012-11-02 15:40:32 -0700353 try {
354 return mBinder.reset() == NO_ERROR;
355 } catch (RemoteException e) {
356 Log.w(TAG, "Cannot connect to keystore", e);
357 return false;
358 }
Chia-chi Yeh44039172009-09-21 11:53:59 +0800359 }
360
Chad Brubakere35d49f2015-05-12 15:19:52 -0700361 /**
362 * Attempt to lock the keystore for {@code user}.
363 *
Brian Youngfd75c722018-02-23 18:04:20 +0000364 * @param userId Android user to lock.
Chad Brubakere35d49f2015-05-12 15:19:52 -0700365 * @return whether {@code user}'s keystore was locked.
366 */
367 public boolean lock(int userId) {
Kenny Root6b776452012-11-02 15:40:32 -0700368 try {
Chad Brubakere35d49f2015-05-12 15:19:52 -0700369 return mBinder.lock(userId) == NO_ERROR;
Kenny Root6b776452012-11-02 15:40:32 -0700370 } catch (RemoteException e) {
371 Log.w(TAG, "Cannot connect to keystore", e);
372 return false;
373 }
Chia-chi Yeh44039172009-09-21 11:53:59 +0800374 }
375
Chad Brubakere35d49f2015-05-12 15:19:52 -0700376 public boolean lock() {
377 return lock(UserHandle.myUserId());
378 }
379
Chad Brubakera91a8502015-05-07 10:02:22 -0700380 /**
381 * Attempt to unlock the keystore for {@code user} with the password {@code password}.
382 * This is required before keystore entries created with FLAG_ENCRYPTED can be accessed or
383 * created.
384 *
Brian Youngfd75c722018-02-23 18:04:20 +0000385 * @param userId Android user ID to operate on
Chad Brubakera91a8502015-05-07 10:02:22 -0700386 * @param password user's keystore password. Should be the most recent value passed to
387 * {@link #onUserPasswordChanged} for the user.
388 *
389 * @return whether the keystore was unlocked.
390 */
391 public boolean unlock(int userId, String password) {
Kenny Root6b776452012-11-02 15:40:32 -0700392 try {
Dmitry Dementyevefc43112017-10-27 23:10:28 -0700393 password = password != null ? password : "";
Chad Brubakera91a8502015-05-07 10:02:22 -0700394 mError = mBinder.unlock(userId, password);
Kenny Root6b776452012-11-02 15:40:32 -0700395 return mError == NO_ERROR;
396 } catch (RemoteException e) {
397 Log.w(TAG, "Cannot connect to keystore", e);
398 return false;
399 }
Chia-chi Yeh44039172009-09-21 11:53:59 +0800400 }
401
Mathew Inwoode420f8b2018-08-16 18:40:47 +0100402 @UnsupportedAppUsage
Chad Brubakera91a8502015-05-07 10:02:22 -0700403 public boolean unlock(String password) {
404 return unlock(UserHandle.getUserId(Process.myUid()), password);
405 }
406
Chad Brubakere35d49f2015-05-12 15:19:52 -0700407 /**
408 * Check if the keystore for {@code userId} is empty.
409 */
410 public boolean isEmpty(int userId) {
Kenny Root6b776452012-11-02 15:40:32 -0700411 try {
Chad Brubakere35d49f2015-05-12 15:19:52 -0700412 return mBinder.isEmpty(userId) != 0;
Kenny Root6b776452012-11-02 15:40:32 -0700413 } catch (RemoteException e) {
414 Log.w(TAG, "Cannot connect to keystore", e);
415 return false;
416 }
Kenny Root5423e682011-11-14 08:43:13 -0800417 }
418
Mathew Inwood31755f92018-12-20 13:53:36 +0000419 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
Chad Brubakere35d49f2015-05-12 15:19:52 -0700420 public boolean isEmpty() {
421 return isEmpty(UserHandle.myUserId());
422 }
423
Janis Danisevskisb50e9f62017-06-08 17:53:34 -0700424 public String grant(String key, int uid) {
Kenny Root6b776452012-11-02 15:40:32 -0700425 try {
Janis Danisevskisb50e9f62017-06-08 17:53:34 -0700426 String grantAlias = mBinder.grant(key, uid);
427 if (grantAlias == "") return null;
428 return grantAlias;
Kenny Root6b776452012-11-02 15:40:32 -0700429 } catch (RemoteException e) {
430 Log.w(TAG, "Cannot connect to keystore", e);
Janis Danisevskisb50e9f62017-06-08 17:53:34 -0700431 return null;
Kenny Root6b776452012-11-02 15:40:32 -0700432 }
Kenny Root5423e682011-11-14 08:43:13 -0800433 }
434
435 public boolean ungrant(String key, int uid) {
Kenny Root6b776452012-11-02 15:40:32 -0700436 try {
437 return mBinder.ungrant(key, uid) == NO_ERROR;
438 } catch (RemoteException e) {
439 Log.w(TAG, "Cannot connect to keystore", e);
440 return false;
Kenny Root473c7122012-08-17 21:13:48 -0700441 }
Kenny Root473c7122012-08-17 21:13:48 -0700442 }
443
444 /**
445 * Returns the last modification time of the key in milliseconds since the
446 * epoch. Will return -1L if the key could not be found or other error.
447 */
Chad Brubaker5bbf0482015-09-09 14:53:52 -0700448 public long getmtime(String key, int uid) {
Kenny Root6b776452012-11-02 15:40:32 -0700449 try {
Chad Brubaker5bbf0482015-09-09 14:53:52 -0700450 final long millis = mBinder.getmtime(key, uid);
Kenny Roote66769a2013-02-04 15:49:11 -0800451 if (millis == -1L) {
452 return -1L;
453 }
454
455 return millis * 1000L;
Kenny Root6b776452012-11-02 15:40:32 -0700456 } catch (RemoteException e) {
457 Log.w(TAG, "Cannot connect to keystore", e);
458 return -1L;
459 }
Kenny Root473c7122012-08-17 21:13:48 -0700460 }
461
Chad Brubaker5bbf0482015-09-09 14:53:52 -0700462 public long getmtime(String key) {
463 return getmtime(key, UID_SELF);
464 }
465
Alex Klyubin469cbf52015-06-04 12:36:27 -0700466 // TODO: remove this when it's removed from Settings
Kenny Root5cb5cec2013-03-29 11:14:17 -0700467 public boolean isHardwareBacked() {
Kenny Rootb91773b2013-09-05 13:03:16 -0700468 return isHardwareBacked("RSA");
469 }
470
471 public boolean isHardwareBacked(String keyType) {
Kenny Root5cb5cec2013-03-29 11:14:17 -0700472 try {
Kenny Rootb91773b2013-09-05 13:03:16 -0700473 return mBinder.is_hardware_backed(keyType.toUpperCase(Locale.US)) == NO_ERROR;
Kenny Root5cb5cec2013-03-29 11:14:17 -0700474 } catch (RemoteException e) {
475 Log.w(TAG, "Cannot connect to keystore", e);
476 return false;
477 }
478 }
479
Kenny Rootd72317a2013-04-01 15:59:59 -0700480 public boolean clearUid(int uid) {
481 try {
482 return mBinder.clear_uid(uid) == NO_ERROR;
483 } catch (RemoteException e) {
484 Log.w(TAG, "Cannot connect to keystore", e);
485 return false;
486 }
487 }
488
Chia-chi Yeh44039172009-09-21 11:53:59 +0800489 public int getLastError() {
490 return mError;
491 }
Chad Brubakere6a461342015-02-10 21:33:23 -0800492
Janis Danisevskis0aadf932017-12-18 17:28:52 -0800493 public boolean addRngEntropy(byte[] data, int flags) {
Janis Danisevskisc9277ffd2019-03-27 15:50:28 -0700494 KeystoreResultPromise promise = new KeystoreResultPromise();
Chad Brubakere6a461342015-02-10 21:33:23 -0800495 try {
Janis Danisevskisc9277ffd2019-03-27 15:50:28 -0700496 mBinder.asBinder().linkToDeath(promise, 0);
Janis Danisevskisb0358e72018-11-02 10:34:07 -0700497 int errorCode = mBinder.addRngEntropy(promise, data, flags);
498 if (errorCode == NO_ERROR) {
499 return promise.getFuture().get().getErrorCode() == NO_ERROR;
500 } else {
501 return false;
502 }
Chad Brubakere6a461342015-02-10 21:33:23 -0800503 } catch (RemoteException e) {
504 Log.w(TAG, "Cannot connect to keystore", e);
505 return false;
Janis Danisevskisb0358e72018-11-02 10:34:07 -0700506 } catch (ExecutionException | InterruptedException e) {
507 Log.e(TAG, "AddRngEntropy completed with exception", e);
508 return false;
Janis Danisevskisc9277ffd2019-03-27 15:50:28 -0700509 } finally {
510 mBinder.asBinder().unlinkToDeath(promise, 0);
Chad Brubakere6a461342015-02-10 21:33:23 -0800511 }
512 }
513
Janis Danisevskisb0358e72018-11-02 10:34:07 -0700514 private class KeyCharacteristicsCallbackResult {
515 private KeystoreResponse keystoreResponse;
516 private KeyCharacteristics keyCharacteristics;
517
518 public KeyCharacteristicsCallbackResult(KeystoreResponse keystoreResponse,
519 KeyCharacteristics keyCharacteristics) {
520 this.keystoreResponse = keystoreResponse;
521 this.keyCharacteristics = keyCharacteristics;
522 }
523
524 public KeystoreResponse getKeystoreResponse() {
525 return keystoreResponse;
526 }
527
528 public void setKeystoreResponse(KeystoreResponse keystoreResponse) {
529 this.keystoreResponse = keystoreResponse;
530 }
531
532 public KeyCharacteristics getKeyCharacteristics() {
533 return keyCharacteristics;
534 }
535
536 public void setKeyCharacteristics(KeyCharacteristics keyCharacteristics) {
537 this.keyCharacteristics = keyCharacteristics;
538 }
539 }
540
541 private class KeyCharacteristicsPromise
Janis Danisevskisc9277ffd2019-03-27 15:50:28 -0700542 extends android.security.keystore.IKeystoreKeyCharacteristicsCallback.Stub
543 implements IBinder.DeathRecipient {
Janis Danisevskisb0358e72018-11-02 10:34:07 -0700544 final private CompletableFuture<KeyCharacteristicsCallbackResult> future =
545 new CompletableFuture<KeyCharacteristicsCallbackResult>();
546 @Override
547 public void onFinished(KeystoreResponse keystoreResponse,
548 KeyCharacteristics keyCharacteristics)
549 throws android.os.RemoteException {
550 future.complete(
551 new KeyCharacteristicsCallbackResult(keystoreResponse, keyCharacteristics));
552 }
553 public final CompletableFuture<KeyCharacteristicsCallbackResult> getFuture() {
554 return future;
555 }
Janis Danisevskisc9277ffd2019-03-27 15:50:28 -0700556 @Override
557 public void binderDied() {
558 future.completeExceptionally(new RemoteException("Keystore died"));
559 }
Janis Danisevskisb0358e72018-11-02 10:34:07 -0700560 };
561
562 private int generateKeyInternal(String alias, KeymasterArguments args, byte[] entropy, int uid,
563 int flags, KeyCharacteristics outCharacteristics)
564 throws RemoteException, ExecutionException, InterruptedException {
565 KeyCharacteristicsPromise promise = new KeyCharacteristicsPromise();
Janis Danisevskisc9277ffd2019-03-27 15:50:28 -0700566 int error = NO_ERROR;
567 KeyCharacteristicsCallbackResult result = null;
568 try {
569 mBinder.asBinder().linkToDeath(promise, 0);
570 error = mBinder.generateKey(promise, alias, args, entropy, uid, flags);
571 if (error != NO_ERROR) {
572 Log.e(TAG, "generateKeyInternal failed on request " + error);
573 return error;
574 }
575 result = promise.getFuture().get();
576 } finally {
577 mBinder.asBinder().unlinkToDeath(promise, 0);
Janis Danisevskisb0358e72018-11-02 10:34:07 -0700578 }
579
Janis Danisevskisb0358e72018-11-02 10:34:07 -0700580 error = result.getKeystoreResponse().getErrorCode();
581 if (error != NO_ERROR) {
582 Log.e(TAG, "generateKeyInternal failed on response " + error);
583 return error;
584 }
585 KeyCharacteristics characteristics = result.getKeyCharacteristics();
586 if (characteristics == null) {
Solomon Kinard2bd792f32019-07-03 11:22:34 -0700587 Log.e(TAG, "generateKeyInternal got empty key characteristics " + error);
Janis Danisevskisb0358e72018-11-02 10:34:07 -0700588 return SYSTEM_ERROR;
589 }
590 outCharacteristics.shallowCopyFrom(characteristics);
591 return NO_ERROR;
592 }
593
Chad Brubakerdae79e52015-03-27 14:28:35 -0700594 public int generateKey(String alias, KeymasterArguments args, byte[] entropy, int uid,
595 int flags, KeyCharacteristics outCharacteristics) {
Chad Brubakere6a461342015-02-10 21:33:23 -0800596 try {
Dmitry Dementyevefc43112017-10-27 23:10:28 -0700597 entropy = entropy != null ? entropy : new byte[0];
598 args = args != null ? args : new KeymasterArguments();
Janis Danisevskisb0358e72018-11-02 10:34:07 -0700599 int error = generateKeyInternal(alias, args, entropy, uid, flags, outCharacteristics);
Janis Danisevskisd2575382018-10-08 07:56:58 -0700600 if (error == KEY_ALREADY_EXISTS) {
601 mBinder.del(alias, uid);
Janis Danisevskisb0358e72018-11-02 10:34:07 -0700602 error = generateKeyInternal(alias, args, entropy, uid, flags, outCharacteristics);
Janis Danisevskisd2575382018-10-08 07:56:58 -0700603 }
604 return error;
Chad Brubakere6a461342015-02-10 21:33:23 -0800605 } catch (RemoteException e) {
606 Log.w(TAG, "Cannot connect to keystore", e);
607 return SYSTEM_ERROR;
Janis Danisevskisb0358e72018-11-02 10:34:07 -0700608 } catch (ExecutionException | InterruptedException e) {
609 Log.e(TAG, "generateKey completed with exception", e);
610 return SYSTEM_ERROR;
Chad Brubakere6a461342015-02-10 21:33:23 -0800611 }
612 }
613
Chad Brubakerdae79e52015-03-27 14:28:35 -0700614 public int generateKey(String alias, KeymasterArguments args, byte[] entropy, int flags,
Chad Brubakere6a461342015-02-10 21:33:23 -0800615 KeyCharacteristics outCharacteristics) {
Chad Brubakerdae79e52015-03-27 14:28:35 -0700616 return generateKey(alias, args, entropy, UID_SELF, flags, outCharacteristics);
Chad Brubakere6a461342015-02-10 21:33:23 -0800617 }
618
Chad Brubaker5e73c0e2015-03-21 22:46:43 -0700619 public int getKeyCharacteristics(String alias, KeymasterBlob clientId, KeymasterBlob appId,
Chad Brubaker5bbf0482015-09-09 14:53:52 -0700620 int uid, KeyCharacteristics outCharacteristics) {
Janis Danisevskisc9277ffd2019-03-27 15:50:28 -0700621 KeyCharacteristicsPromise promise = new KeyCharacteristicsPromise();
Chad Brubakere6a461342015-02-10 21:33:23 -0800622 try {
Janis Danisevskisc9277ffd2019-03-27 15:50:28 -0700623 mBinder.asBinder().linkToDeath(promise, 0);
Dmitry Dementyevefc43112017-10-27 23:10:28 -0700624 clientId = clientId != null ? clientId : new KeymasterBlob(new byte[0]);
625 appId = appId != null ? appId : new KeymasterBlob(new byte[0]);
Janis Danisevskisc9277ffd2019-03-27 15:50:28 -0700626
Janis Danisevskisb0358e72018-11-02 10:34:07 -0700627 int error = mBinder.getKeyCharacteristics(promise, alias, clientId, appId, uid);
628 if (error != NO_ERROR) return error;
629
630 KeyCharacteristicsCallbackResult result = promise.getFuture().get();
631 error = result.getKeystoreResponse().getErrorCode();
632 if (error != NO_ERROR) return error;
633
634 KeyCharacteristics characteristics = result.getKeyCharacteristics();
635 if (characteristics == null) return SYSTEM_ERROR;
636 outCharacteristics.shallowCopyFrom(characteristics);
637 return NO_ERROR;
Chad Brubakere6a461342015-02-10 21:33:23 -0800638 } catch (RemoteException e) {
639 Log.w(TAG, "Cannot connect to keystore", e);
640 return SYSTEM_ERROR;
Janis Danisevskisb0358e72018-11-02 10:34:07 -0700641 } catch (ExecutionException | InterruptedException e) {
642 Log.e(TAG, "GetKeyCharacteristics completed with exception", e);
643 return SYSTEM_ERROR;
Janis Danisevskisc9277ffd2019-03-27 15:50:28 -0700644 } finally {
645 mBinder.asBinder().unlinkToDeath(promise, 0);
Chad Brubakere6a461342015-02-10 21:33:23 -0800646 }
647 }
648
Chad Brubaker5bbf0482015-09-09 14:53:52 -0700649 public int getKeyCharacteristics(String alias, KeymasterBlob clientId, KeymasterBlob appId,
650 KeyCharacteristics outCharacteristics) {
651 return getKeyCharacteristics(alias, clientId, appId, UID_SELF, outCharacteristics);
652 }
653
Janis Danisevskisb0358e72018-11-02 10:34:07 -0700654 private int importKeyInternal(String alias, KeymasterArguments args, int format, byte[] keyData,
655 int uid, int flags, KeyCharacteristics outCharacteristics)
656 throws RemoteException, ExecutionException, InterruptedException {
657 KeyCharacteristicsPromise promise = new KeyCharacteristicsPromise();
Janis Danisevskisc9277ffd2019-03-27 15:50:28 -0700658 mBinder.asBinder().linkToDeath(promise, 0);
659 try {
660 int error = mBinder.importKey(promise, alias, args, format, keyData, uid, flags);
661 if (error != NO_ERROR) return error;
Janis Danisevskisb0358e72018-11-02 10:34:07 -0700662
Janis Danisevskisc9277ffd2019-03-27 15:50:28 -0700663 KeyCharacteristicsCallbackResult result = promise.getFuture().get();
Janis Danisevskisb0358e72018-11-02 10:34:07 -0700664
Janis Danisevskisc9277ffd2019-03-27 15:50:28 -0700665 error = result.getKeystoreResponse().getErrorCode();
666 if (error != NO_ERROR) return error;
667
668 KeyCharacteristics characteristics = result.getKeyCharacteristics();
669 if (characteristics == null) return SYSTEM_ERROR;
670 outCharacteristics.shallowCopyFrom(characteristics);
671 return NO_ERROR;
672 } finally {
673 mBinder.asBinder().unlinkToDeath(promise, 0);
674 }
Janis Danisevskisb0358e72018-11-02 10:34:07 -0700675 }
676
Chad Brubakere6a461342015-02-10 21:33:23 -0800677 public int importKey(String alias, KeymasterArguments args, int format, byte[] keyData,
678 int uid, int flags, KeyCharacteristics outCharacteristics) {
679 try {
Janis Danisevskisb0358e72018-11-02 10:34:07 -0700680 int error = importKeyInternal(alias, args, format, keyData, uid, flags,
Chad Brubakere6a461342015-02-10 21:33:23 -0800681 outCharacteristics);
Janis Danisevskisd2575382018-10-08 07:56:58 -0700682 if (error == KEY_ALREADY_EXISTS) {
683 mBinder.del(alias, uid);
Janis Danisevskisb0358e72018-11-02 10:34:07 -0700684 error = importKeyInternal(alias, args, format, keyData, uid, flags,
Janis Danisevskisd2575382018-10-08 07:56:58 -0700685 outCharacteristics);
686 }
687 return error;
Chad Brubakere6a461342015-02-10 21:33:23 -0800688 } catch (RemoteException e) {
689 Log.w(TAG, "Cannot connect to keystore", e);
690 return SYSTEM_ERROR;
Janis Danisevskisb0358e72018-11-02 10:34:07 -0700691 } catch (ExecutionException | InterruptedException e) {
692 Log.e(TAG, "ImportKey completed with exception", e);
693 return SYSTEM_ERROR;
Chad Brubakere6a461342015-02-10 21:33:23 -0800694 }
695 }
696
697 public int importKey(String alias, KeymasterArguments args, int format, byte[] keyData,
698 int flags, KeyCharacteristics outCharacteristics) {
699 return importKey(alias, args, format, keyData, UID_SELF, flags, outCharacteristics);
700 }
701
Janis Danisevskis1864c952018-08-09 11:14:49 -0700702 private String getAlgorithmFromPKCS8(byte[] keyData) {
703 try {
704 final ASN1InputStream bIn = new ASN1InputStream(new ByteArrayInputStream(keyData));
705 final PrivateKeyInfo pki = PrivateKeyInfo.getInstance(bIn.readObject());
706 final String algOid = pki.getPrivateKeyAlgorithm().getAlgorithm().getId();
707 return new AlgorithmId(new ObjectIdentifier(algOid)).getName();
708 } catch (IOException e) {
709 Log.e(TAG, "getAlgorithmFromPKCS8 Failed to parse key data");
710 Log.e(TAG, Log.getStackTraceString(e));
711 return null;
712 }
713 }
714
715 private KeymasterArguments makeLegacyArguments(String algorithm) {
716 KeymasterArguments args = new KeymasterArguments();
717 args.addEnum(KeymasterDefs.KM_TAG_ALGORITHM,
718 KeyProperties.KeyAlgorithm.toKeymasterAsymmetricKeyAlgorithm(algorithm));
719 args.addEnum(KeymasterDefs.KM_TAG_PURPOSE, KeymasterDefs.KM_PURPOSE_SIGN);
720 args.addEnum(KeymasterDefs.KM_TAG_PURPOSE, KeymasterDefs.KM_PURPOSE_VERIFY);
721 args.addEnum(KeymasterDefs.KM_TAG_PURPOSE, KeymasterDefs.KM_PURPOSE_ENCRYPT);
722 args.addEnum(KeymasterDefs.KM_TAG_PURPOSE, KeymasterDefs.KM_PURPOSE_DECRYPT);
723 args.addEnum(KeymasterDefs.KM_TAG_PADDING, KeymasterDefs.KM_PAD_NONE);
724 if (algorithm.equalsIgnoreCase(KeyProperties.KEY_ALGORITHM_RSA)) {
725 args.addEnum(KeymasterDefs.KM_TAG_PADDING, KeymasterDefs.KM_PAD_RSA_OAEP);
726 args.addEnum(KeymasterDefs.KM_TAG_PADDING, KeymasterDefs.KM_PAD_RSA_PKCS1_1_5_ENCRYPT);
727 args.addEnum(KeymasterDefs.KM_TAG_PADDING, KeymasterDefs.KM_PAD_RSA_PKCS1_1_5_SIGN);
728 args.addEnum(KeymasterDefs.KM_TAG_PADDING, KeymasterDefs.KM_PAD_RSA_PSS);
729 }
730 args.addEnum(KeymasterDefs.KM_TAG_DIGEST, KeymasterDefs.KM_DIGEST_NONE);
731 args.addEnum(KeymasterDefs.KM_TAG_DIGEST, KeymasterDefs.KM_DIGEST_MD5);
732 args.addEnum(KeymasterDefs.KM_TAG_DIGEST, KeymasterDefs.KM_DIGEST_SHA1);
733 args.addEnum(KeymasterDefs.KM_TAG_DIGEST, KeymasterDefs.KM_DIGEST_SHA_2_224);
734 args.addEnum(KeymasterDefs.KM_TAG_DIGEST, KeymasterDefs.KM_DIGEST_SHA_2_256);
735 args.addEnum(KeymasterDefs.KM_TAG_DIGEST, KeymasterDefs.KM_DIGEST_SHA_2_384);
736 args.addEnum(KeymasterDefs.KM_TAG_DIGEST, KeymasterDefs.KM_DIGEST_SHA_2_512);
737 args.addBoolean(KeymasterDefs.KM_TAG_NO_AUTH_REQUIRED);
Janis Danisevskis2b106ad2018-11-15 09:27:16 -0800738 args.addDate(KeymasterDefs.KM_TAG_ORIGINATION_EXPIRE_DATETIME, new Date(Long.MAX_VALUE));
739 args.addDate(KeymasterDefs.KM_TAG_USAGE_EXPIRE_DATETIME, new Date(Long.MAX_VALUE));
740 args.addDate(KeymasterDefs.KM_TAG_ACTIVE_DATETIME, new Date(0));
Janis Danisevskis1864c952018-08-09 11:14:49 -0700741 return args;
742 }
743
744 public boolean importKey(String alias, byte[] keyData, int uid, int flags) {
745 String algorithm = getAlgorithmFromPKCS8(keyData);
746 if (algorithm == null) return false;
747 KeymasterArguments args = makeLegacyArguments(algorithm);
748 KeyCharacteristics out = new KeyCharacteristics();
749 int result = importKey(alias, args, KeymasterDefs.KM_KEY_FORMAT_PKCS8, keyData, uid,
750 flags, out);
751 if (result != NO_ERROR) {
752 Log.e(TAG, Log.getStackTraceString(
753 new KeyStoreException(result, "legacy key import failed")));
754 return false;
755 }
756 return true;
757 }
758
Janis Danisevskisb0358e72018-11-02 10:34:07 -0700759 private int importWrappedKeyInternal(String wrappedKeyAlias, byte[] wrappedKey,
760 String wrappingKeyAlias,
761 byte[] maskingKey, KeymasterArguments args, long rootSid, long fingerprintSid,
762 KeyCharacteristics outCharacteristics)
763 throws RemoteException, ExecutionException, InterruptedException {
764 KeyCharacteristicsPromise promise = new KeyCharacteristicsPromise();
Janis Danisevskisc9277ffd2019-03-27 15:50:28 -0700765 mBinder.asBinder().linkToDeath(promise, 0);
766 try {
Janis Danisevskisc9277ffd2019-03-27 15:50:28 -0700767 int error = mBinder.importWrappedKey(promise, wrappedKeyAlias, wrappedKey,
768 wrappingKeyAlias, maskingKey, args, rootSid, fingerprintSid);
769 if (error != NO_ERROR) return error;
Janis Danisevskisb0358e72018-11-02 10:34:07 -0700770
Janis Danisevskisf924b7e2019-04-17 14:06:09 -0700771 KeyCharacteristicsCallbackResult result = promise.getFuture().get();
Janis Danisevskisb0358e72018-11-02 10:34:07 -0700772
Janis Danisevskisc9277ffd2019-03-27 15:50:28 -0700773 error = result.getKeystoreResponse().getErrorCode();
774 if (error != NO_ERROR) return error;
775
776 KeyCharacteristics characteristics = result.getKeyCharacteristics();
777 if (characteristics == null) return SYSTEM_ERROR;
778 outCharacteristics.shallowCopyFrom(characteristics);
779 return NO_ERROR;
780 } finally {
781 mBinder.asBinder().unlinkToDeath(promise, 0);
782 }
Janis Danisevskisb0358e72018-11-02 10:34:07 -0700783 }
784
Frank Salim21d9c1d2017-12-19 22:38:09 -0800785 public int importWrappedKey(String wrappedKeyAlias, byte[] wrappedKey,
786 String wrappingKeyAlias,
787 byte[] maskingKey, KeymasterArguments args, long rootSid, long fingerprintSid, int uid,
788 KeyCharacteristics outCharacteristics) {
Janis Danisevskisb0358e72018-11-02 10:34:07 -0700789 // TODO b/119217337 uid parameter gets silently ignored.
Frank Salim21d9c1d2017-12-19 22:38:09 -0800790 try {
Janis Danisevskisb0358e72018-11-02 10:34:07 -0700791 int error = importWrappedKeyInternal(wrappedKeyAlias, wrappedKey, wrappingKeyAlias,
Frank Salim21d9c1d2017-12-19 22:38:09 -0800792 maskingKey, args, rootSid, fingerprintSid, outCharacteristics);
Janis Danisevskisd2575382018-10-08 07:56:58 -0700793 if (error == KEY_ALREADY_EXISTS) {
Janis Danisevskisb0358e72018-11-02 10:34:07 -0700794 mBinder.del(wrappedKeyAlias, UID_SELF);
795 error = importWrappedKeyInternal(wrappedKeyAlias, wrappedKey, wrappingKeyAlias,
Janis Danisevskisd2575382018-10-08 07:56:58 -0700796 maskingKey, args, rootSid, fingerprintSid, outCharacteristics);
797 }
798 return error;
Frank Salim21d9c1d2017-12-19 22:38:09 -0800799 } catch (RemoteException e) {
800 Log.w(TAG, "Cannot connect to keystore", e);
801 return SYSTEM_ERROR;
Janis Danisevskisb0358e72018-11-02 10:34:07 -0700802 } catch (ExecutionException | InterruptedException e) {
803 Log.e(TAG, "ImportWrappedKey completed with exception", e);
804 return SYSTEM_ERROR;
Frank Salim21d9c1d2017-12-19 22:38:09 -0800805 }
806 }
807
Janis Danisevskisb0358e72018-11-02 10:34:07 -0700808 private class ExportKeyPromise
Janis Danisevskisc9277ffd2019-03-27 15:50:28 -0700809 extends android.security.keystore.IKeystoreExportKeyCallback.Stub
810 implements IBinder.DeathRecipient {
Janis Danisevskisb0358e72018-11-02 10:34:07 -0700811 final private CompletableFuture<ExportResult> future = new CompletableFuture<ExportResult>();
812 @Override
813 public void onFinished(ExportResult exportKeyResult) throws android.os.RemoteException {
814 future.complete(exportKeyResult);
815 }
816 public final CompletableFuture<ExportResult> getFuture() {
817 return future;
818 }
Janis Danisevskisc9277ffd2019-03-27 15:50:28 -0700819 @Override
820 public void binderDied() {
821 future.completeExceptionally(new RemoteException("Keystore died"));
822 }
Janis Danisevskisb0358e72018-11-02 10:34:07 -0700823 };
824
Chad Brubaker5e73c0e2015-03-21 22:46:43 -0700825 public ExportResult exportKey(String alias, int format, KeymasterBlob clientId,
Chad Brubaker5bbf0482015-09-09 14:53:52 -0700826 KeymasterBlob appId, int uid) {
Janis Danisevskisc9277ffd2019-03-27 15:50:28 -0700827 ExportKeyPromise promise = new ExportKeyPromise();
Chad Brubakere6a461342015-02-10 21:33:23 -0800828 try {
Janis Danisevskisc9277ffd2019-03-27 15:50:28 -0700829 mBinder.asBinder().linkToDeath(promise, 0);
Dmitry Dementyevefc43112017-10-27 23:10:28 -0700830 clientId = clientId != null ? clientId : new KeymasterBlob(new byte[0]);
831 appId = appId != null ? appId : new KeymasterBlob(new byte[0]);
Janis Danisevskisb0358e72018-11-02 10:34:07 -0700832 int error = mBinder.exportKey(promise, alias, format, clientId, appId, uid);
833 if (error == NO_ERROR) {
834 return promise.getFuture().get();
835 } else {
836 return new ExportResult(error);
837 }
Chad Brubaker5bbf0482015-09-09 14:53:52 -0700838 } catch (RemoteException e) {
839 Log.w(TAG, "Cannot connect to keystore", e);
840 return null;
Janis Danisevskisb0358e72018-11-02 10:34:07 -0700841 } catch (ExecutionException | InterruptedException e) {
842 Log.e(TAG, "ExportKey completed with exception", e);
843 return null;
Janis Danisevskisc9277ffd2019-03-27 15:50:28 -0700844 } finally {
845 mBinder.asBinder().unlinkToDeath(promise, 0);
Chad Brubaker5bbf0482015-09-09 14:53:52 -0700846 }
847 }
848 public ExportResult exportKey(String alias, int format, KeymasterBlob clientId,
849 KeymasterBlob appId) {
850 return exportKey(alias, format, clientId, appId, UID_SELF);
851 }
852
Janis Danisevskisb0358e72018-11-02 10:34:07 -0700853 private class OperationPromise
Janis Danisevskisc9277ffd2019-03-27 15:50:28 -0700854 extends android.security.keystore.IKeystoreOperationResultCallback.Stub
855 implements IBinder.DeathRecipient {
Janis Danisevskisb0358e72018-11-02 10:34:07 -0700856 final private CompletableFuture<OperationResult> future = new CompletableFuture<OperationResult>();
857 @Override
858 public void onFinished(OperationResult operationResult) throws android.os.RemoteException {
859 future.complete(operationResult);
860 }
861 public final CompletableFuture<OperationResult> getFuture() {
862 return future;
863 }
Janis Danisevskisc9277ffd2019-03-27 15:50:28 -0700864 @Override
865 public void binderDied() {
866 future.completeExceptionally(new RemoteException("Keystore died"));
867 }
Janis Danisevskisb0358e72018-11-02 10:34:07 -0700868 };
869
Chad Brubaker5bbf0482015-09-09 14:53:52 -0700870 public OperationResult begin(String alias, int purpose, boolean pruneable,
871 KeymasterArguments args, byte[] entropy, int uid) {
Janis Danisevskisc9277ffd2019-03-27 15:50:28 -0700872 OperationPromise promise = new OperationPromise();
Chad Brubaker5bbf0482015-09-09 14:53:52 -0700873 try {
Janis Danisevskisc9277ffd2019-03-27 15:50:28 -0700874 mBinder.asBinder().linkToDeath(promise, 0);
Dmitry Dementyevefc43112017-10-27 23:10:28 -0700875 args = args != null ? args : new KeymasterArguments();
876 entropy = entropy != null ? entropy : new byte[0];
Janis Danisevskisb0358e72018-11-02 10:34:07 -0700877 int errorCode = mBinder.begin(promise, getToken(), alias, purpose, pruneable, args,
878 entropy, uid);
879 if (errorCode == NO_ERROR) {
880 return promise.getFuture().get();
881 } else {
882 return new OperationResult(errorCode);
883 }
Chad Brubakere6a461342015-02-10 21:33:23 -0800884 } catch (RemoteException e) {
885 Log.w(TAG, "Cannot connect to keystore", e);
886 return null;
Janis Danisevskisb0358e72018-11-02 10:34:07 -0700887 } catch (ExecutionException | InterruptedException e) {
888 Log.e(TAG, "Begin completed with exception", e);
889 return null;
Janis Danisevskisc9277ffd2019-03-27 15:50:28 -0700890 } finally {
891 mBinder.asBinder().unlinkToDeath(promise, 0);
Chad Brubakere6a461342015-02-10 21:33:23 -0800892 }
893 }
894
895 public OperationResult begin(String alias, int purpose, boolean pruneable,
Chad Brubaker966486e2015-06-01 12:57:06 -0700896 KeymasterArguments args, byte[] entropy) {
Dmitry Dementyevefc43112017-10-27 23:10:28 -0700897 entropy = entropy != null ? entropy : new byte[0];
898 args = args != null ? args : new KeymasterArguments();
Chad Brubaker5bbf0482015-09-09 14:53:52 -0700899 return begin(alias, purpose, pruneable, args, entropy, UID_SELF);
Chad Brubakere6a461342015-02-10 21:33:23 -0800900 }
901
902 public OperationResult update(IBinder token, KeymasterArguments arguments, byte[] input) {
Janis Danisevskisc9277ffd2019-03-27 15:50:28 -0700903 OperationPromise promise = new OperationPromise();
Chad Brubakere6a461342015-02-10 21:33:23 -0800904 try {
Janis Danisevskisc9277ffd2019-03-27 15:50:28 -0700905 mBinder.asBinder().linkToDeath(promise, 0);
Dmitry Dementyevefc43112017-10-27 23:10:28 -0700906 arguments = arguments != null ? arguments : new KeymasterArguments();
907 input = input != null ? input : new byte[0];
Janis Danisevskisb0358e72018-11-02 10:34:07 -0700908 int errorCode = mBinder.update(promise, token, arguments, input);
909 if (errorCode == NO_ERROR) {
910 return promise.getFuture().get();
911 } else {
912 return new OperationResult(errorCode);
913 }
Chad Brubakere6a461342015-02-10 21:33:23 -0800914 } catch (RemoteException e) {
915 Log.w(TAG, "Cannot connect to keystore", e);
916 return null;
Janis Danisevskisb0358e72018-11-02 10:34:07 -0700917 } catch (ExecutionException | InterruptedException e) {
918 Log.e(TAG, "Update completed with exception", e);
919 return null;
Janis Danisevskisc9277ffd2019-03-27 15:50:28 -0700920 } finally {
921 mBinder.asBinder().unlinkToDeath(promise, 0);
Chad Brubakere6a461342015-02-10 21:33:23 -0800922 }
923 }
924
Chad Brubaker8a077012015-05-29 12:32:51 -0700925 public OperationResult finish(IBinder token, KeymasterArguments arguments, byte[] signature,
926 byte[] entropy) {
Janis Danisevskisc9277ffd2019-03-27 15:50:28 -0700927 OperationPromise promise = new OperationPromise();
Chad Brubakere6a461342015-02-10 21:33:23 -0800928 try {
Janis Danisevskisc9277ffd2019-03-27 15:50:28 -0700929 mBinder.asBinder().linkToDeath(promise, 0);
Dmitry Dementyevefc43112017-10-27 23:10:28 -0700930 arguments = arguments != null ? arguments : new KeymasterArguments();
931 entropy = entropy != null ? entropy : new byte[0];
932 signature = signature != null ? signature : new byte[0];
Janis Danisevskisb0358e72018-11-02 10:34:07 -0700933 int errorCode = mBinder.finish(promise, token, arguments, signature, entropy);
934 if (errorCode == NO_ERROR) {
935 return promise.getFuture().get();
936 } else {
937 return new OperationResult(errorCode);
938 }
Chad Brubakere6a461342015-02-10 21:33:23 -0800939 } catch (RemoteException e) {
940 Log.w(TAG, "Cannot connect to keystore", e);
941 return null;
Janis Danisevskisb0358e72018-11-02 10:34:07 -0700942 } catch (ExecutionException | InterruptedException e) {
943 Log.e(TAG, "Finish completed with exception", e);
944 return null;
Janis Danisevskisc9277ffd2019-03-27 15:50:28 -0700945 } finally {
946 mBinder.asBinder().unlinkToDeath(promise, 0);
Chad Brubakere6a461342015-02-10 21:33:23 -0800947 }
948 }
949
Chad Brubaker8a077012015-05-29 12:32:51 -0700950 public OperationResult finish(IBinder token, KeymasterArguments arguments, byte[] signature) {
951 return finish(token, arguments, signature, null);
952 }
953
Janis Danisevskisb0358e72018-11-02 10:34:07 -0700954 private class KeystoreResultPromise
Janis Danisevskisc9277ffd2019-03-27 15:50:28 -0700955 extends android.security.keystore.IKeystoreResponseCallback.Stub
956 implements IBinder.DeathRecipient {
Janis Danisevskisb0358e72018-11-02 10:34:07 -0700957 final private CompletableFuture<KeystoreResponse> future = new CompletableFuture<KeystoreResponse>();
958 @Override
959 public void onFinished(KeystoreResponse keystoreResponse) throws android.os.RemoteException {
960 future.complete(keystoreResponse);
961 }
962 public final CompletableFuture<KeystoreResponse> getFuture() {
963 return future;
964 }
Janis Danisevskisc9277ffd2019-03-27 15:50:28 -0700965 @Override
966 public void binderDied() {
967 future.completeExceptionally(new RemoteException("Keystore died"));
968 }
Janis Danisevskisb0358e72018-11-02 10:34:07 -0700969 };
970
Chad Brubakere6a461342015-02-10 21:33:23 -0800971 public int abort(IBinder token) {
Janis Danisevskisc9277ffd2019-03-27 15:50:28 -0700972 KeystoreResultPromise promise = new KeystoreResultPromise();
Chad Brubakere6a461342015-02-10 21:33:23 -0800973 try {
Janis Danisevskisc9277ffd2019-03-27 15:50:28 -0700974 mBinder.asBinder().linkToDeath(promise, 0);
Janis Danisevskisb0358e72018-11-02 10:34:07 -0700975 int errorCode = mBinder.abort(promise, token);
976 if (errorCode == NO_ERROR) {
977 return promise.getFuture().get().getErrorCode();
978 } else {
979 return errorCode;
980 }
Chad Brubakere6a461342015-02-10 21:33:23 -0800981 } catch (RemoteException e) {
982 Log.w(TAG, "Cannot connect to keystore", e);
983 return SYSTEM_ERROR;
Janis Danisevskisb0358e72018-11-02 10:34:07 -0700984 } catch (ExecutionException | InterruptedException e) {
985 Log.e(TAG, "Abort completed with exception", e);
986 return SYSTEM_ERROR;
Janis Danisevskisc9277ffd2019-03-27 15:50:28 -0700987 } finally {
988 mBinder.asBinder().unlinkToDeath(promise, 0);
Chad Brubakere6a461342015-02-10 21:33:23 -0800989 }
990 }
Chad Brubaker5654b362015-03-17 16:59:52 -0700991
992 /**
Chad Brubaker5654b362015-03-17 16:59:52 -0700993 * Add an authentication record to the keystore authorization table.
994 *
995 * @param authToken The packed bytes of a hw_auth_token_t to be provided to keymaster.
996 * @return {@code KeyStore.NO_ERROR} on success, otherwise an error value corresponding to
997 * a {@code KeymasterDefs.KM_ERROR_} value or {@code KeyStore} ResponseCode.
998 */
Brian Youngda82e2c2018-02-22 23:36:34 +0000999 public int addAuthToken(byte[] authToken) {
Chad Brubaker5654b362015-03-17 16:59:52 -07001000 try {
Brian Youngda82e2c2018-02-22 23:36:34 +00001001 return mBinder.addAuthToken(authToken);
Chad Brubaker5654b362015-03-17 16:59:52 -07001002 } catch (RemoteException e) {
1003 Log.w(TAG, "Cannot connect to keystore", e);
1004 return SYSTEM_ERROR;
1005 }
1006 }
Alex Klyubinb4834ae2015-04-02 15:53:46 -07001007
Alex Klyubinad9ba102015-04-21 15:17:24 -07001008 /**
Chad Brubakera91a8502015-05-07 10:02:22 -07001009 * Notify keystore that a user's password has changed.
1010 *
1011 * @param userId the user whose password changed.
1012 * @param newPassword the new password or "" if the password was removed.
1013 */
1014 public boolean onUserPasswordChanged(int userId, String newPassword) {
1015 // Parcel.cpp doesn't support deserializing null strings and treats them as "". Make that
1016 // explicit here.
1017 if (newPassword == null) {
1018 newPassword = "";
1019 }
1020 try {
1021 return mBinder.onUserPasswordChanged(userId, newPassword) == NO_ERROR;
1022 } catch (RemoteException e) {
1023 Log.w(TAG, "Cannot connect to keystore", e);
1024 return false;
1025 }
1026 }
1027
Chad Brubaker83ce0952015-05-12 13:00:02 -07001028 /**
1029 * Notify keystore that a user was added.
1030 *
1031 * @param userId the new user.
1032 * @param parentId the parent of the new user, or -1 if the user has no parent. If parentId is
1033 * specified then the new user's keystore will be intialized with the same secure lockscreen
1034 * password as the parent.
1035 */
1036 public void onUserAdded(int userId, int parentId) {
1037 try {
1038 mBinder.onUserAdded(userId, parentId);
1039 } catch (RemoteException e) {
1040 Log.w(TAG, "Cannot connect to keystore", e);
1041 }
1042 }
1043
1044 /**
1045 * Notify keystore that a user was added.
1046 *
1047 * @param userId the new user.
1048 */
1049 public void onUserAdded(int userId) {
1050 onUserAdded(userId, -1);
1051 }
1052
1053 /**
1054 * Notify keystore that a user was removed.
1055 *
1056 * @param userId the removed user.
1057 */
1058 public void onUserRemoved(int userId) {
1059 try {
1060 mBinder.onUserRemoved(userId);
1061 } catch (RemoteException e) {
1062 Log.w(TAG, "Cannot connect to keystore", e);
1063 }
1064 }
1065
Chad Brubakera91a8502015-05-07 10:02:22 -07001066 public boolean onUserPasswordChanged(String newPassword) {
1067 return onUserPasswordChanged(UserHandle.getUserId(Process.myUid()), newPassword);
1068 }
1069
Janis Danisevskisb0358e72018-11-02 10:34:07 -07001070 private class KeyAttestationCallbackResult {
1071 private KeystoreResponse keystoreResponse;
1072 private KeymasterCertificateChain certificateChain;
1073
1074 public KeyAttestationCallbackResult(KeystoreResponse keystoreResponse,
1075 KeymasterCertificateChain certificateChain) {
1076 this.keystoreResponse = keystoreResponse;
1077 this.certificateChain = certificateChain;
1078 }
1079
1080 public KeystoreResponse getKeystoreResponse() {
1081 return keystoreResponse;
1082 }
1083
1084 public void setKeystoreResponse(KeystoreResponse keystoreResponse) {
1085 this.keystoreResponse = keystoreResponse;
1086 }
1087
1088 public KeymasterCertificateChain getCertificateChain() {
1089 return certificateChain;
1090 }
1091
1092 public void setCertificateChain(KeymasterCertificateChain certificateChain) {
1093 this.certificateChain = certificateChain;
1094 }
1095 }
1096
1097 private class CertificateChainPromise
Janis Danisevskisc9277ffd2019-03-27 15:50:28 -07001098 extends android.security.keystore.IKeystoreCertificateChainCallback.Stub
1099 implements IBinder.DeathRecipient {
Janis Danisevskisb0358e72018-11-02 10:34:07 -07001100 final private CompletableFuture<KeyAttestationCallbackResult> future = new CompletableFuture<KeyAttestationCallbackResult>();
1101 @Override
1102 public void onFinished(KeystoreResponse keystoreResponse,
1103 KeymasterCertificateChain certificateChain) throws android.os.RemoteException {
1104 future.complete(new KeyAttestationCallbackResult(keystoreResponse, certificateChain));
1105 }
1106 public final CompletableFuture<KeyAttestationCallbackResult> getFuture() {
1107 return future;
1108 }
Janis Danisevskisc9277ffd2019-03-27 15:50:28 -07001109 @Override
1110 public void binderDied() {
1111 future.completeExceptionally(new RemoteException("Keystore died"));
1112 }
Janis Danisevskisb0358e72018-11-02 10:34:07 -07001113 };
1114
1115
Shawn Willden8d8c7472016-02-02 08:27:39 -07001116 public int attestKey(
1117 String alias, KeymasterArguments params, KeymasterCertificateChain outChain) {
Janis Danisevskisc9277ffd2019-03-27 15:50:28 -07001118 CertificateChainPromise promise = new CertificateChainPromise();
Shawn Willden8d8c7472016-02-02 08:27:39 -07001119 try {
Janis Danisevskisc9277ffd2019-03-27 15:50:28 -07001120 mBinder.asBinder().linkToDeath(promise, 0);
Dmitry Dementyevefc43112017-10-27 23:10:28 -07001121 if (params == null) {
1122 params = new KeymasterArguments();
1123 }
1124 if (outChain == null) {
1125 outChain = new KeymasterCertificateChain();
1126 }
Janis Danisevskisb0358e72018-11-02 10:34:07 -07001127 int error = mBinder.attestKey(promise, alias, params);
1128 if (error != NO_ERROR) return error;
1129 KeyAttestationCallbackResult result = promise.getFuture().get();
1130 error = result.getKeystoreResponse().getErrorCode();
1131 if (error == NO_ERROR) {
1132 outChain.shallowCopyFrom(result.getCertificateChain());
1133 }
1134 return error;
Shawn Willden8d8c7472016-02-02 08:27:39 -07001135 } catch (RemoteException e) {
1136 Log.w(TAG, "Cannot connect to keystore", e);
1137 return SYSTEM_ERROR;
Janis Danisevskisb0358e72018-11-02 10:34:07 -07001138 } catch (ExecutionException | InterruptedException e) {
1139 Log.e(TAG, "AttestKey completed with exception", e);
1140 return SYSTEM_ERROR;
Janis Danisevskisc9277ffd2019-03-27 15:50:28 -07001141 } finally {
1142 mBinder.asBinder().unlinkToDeath(promise, 0);
Shawn Willden8d8c7472016-02-02 08:27:39 -07001143 }
1144 }
1145
Bartosz Fabianowski237f4b362017-04-24 13:57:46 +02001146 public int attestDeviceIds(KeymasterArguments params, KeymasterCertificateChain outChain) {
Janis Danisevskisc9277ffd2019-03-27 15:50:28 -07001147 CertificateChainPromise promise = new CertificateChainPromise();
Bartosz Fabianowski237f4b362017-04-24 13:57:46 +02001148 try {
Janis Danisevskisc9277ffd2019-03-27 15:50:28 -07001149 mBinder.asBinder().linkToDeath(promise, 0);
Dmitry Dementyevefc43112017-10-27 23:10:28 -07001150 if (params == null) {
1151 params = new KeymasterArguments();
1152 }
1153 if (outChain == null) {
1154 outChain = new KeymasterCertificateChain();
1155 }
Janis Danisevskisb0358e72018-11-02 10:34:07 -07001156 int error = mBinder.attestDeviceIds(promise, params);
1157 if (error != NO_ERROR) return error;
1158 KeyAttestationCallbackResult result = promise.getFuture().get();
1159 error = result.getKeystoreResponse().getErrorCode();
1160 if (error == NO_ERROR) {
1161 outChain.shallowCopyFrom(result.getCertificateChain());
1162 }
1163 return error;
Bartosz Fabianowski237f4b362017-04-24 13:57:46 +02001164 } catch (RemoteException e) {
1165 Log.w(TAG, "Cannot connect to keystore", e);
1166 return SYSTEM_ERROR;
Janis Danisevskisb0358e72018-11-02 10:34:07 -07001167 } catch (ExecutionException | InterruptedException e) {
1168 Log.e(TAG, "AttestDevicdeIds completed with exception", e);
1169 return SYSTEM_ERROR;
Janis Danisevskisc9277ffd2019-03-27 15:50:28 -07001170 } finally {
1171 mBinder.asBinder().unlinkToDeath(promise, 0);
Bartosz Fabianowski237f4b362017-04-24 13:57:46 +02001172 }
1173 }
1174
Tucker Sylvestrob32aae22016-06-23 17:23:33 -04001175 /**
1176 * Notify keystore that the device went off-body.
1177 */
1178 public void onDeviceOffBody() {
1179 try {
1180 mBinder.onDeviceOffBody();
1181 } catch (RemoteException e) {
1182 Log.w(TAG, "Cannot connect to keystore", e);
1183 }
1184 }
Shawn Willden8d8c7472016-02-02 08:27:39 -07001185
Janis Danisevskis7dacad82018-01-24 15:12:11 -08001186 // Keep in sync with confirmationui/1.0/types.hal.
1187 public static final int CONFIRMATIONUI_OK = 0;
1188 public static final int CONFIRMATIONUI_CANCELED = 1;
1189 public static final int CONFIRMATIONUI_ABORTED = 2;
1190 public static final int CONFIRMATIONUI_OPERATION_PENDING = 3;
1191 public static final int CONFIRMATIONUI_IGNORED = 4;
1192 public static final int CONFIRMATIONUI_SYSTEM_ERROR = 5;
1193 public static final int CONFIRMATIONUI_UNIMPLEMENTED = 6;
1194 public static final int CONFIRMATIONUI_UNEXPECTED = 7;
1195 public static final int CONFIRMATIONUI_UIERROR = 0x10000;
1196 public static final int CONFIRMATIONUI_UIERROR_MISSING_GLYPH = 0x10001;
1197 public static final int CONFIRMATIONUI_UIERROR_MESSAGE_TOO_LONG = 0x10002;
1198 public static final int CONFIRMATIONUI_UIERROR_MALFORMED_UTF8_ENCODING = 0x10003;
1199
1200 /**
1201 * Requests keystore call into the confirmationui HAL to display a prompt.
1202 *
1203 * @param listener the binder to use for callbacks.
1204 * @param promptText the prompt to display.
1205 * @param extraData extra data / nonce from application.
1206 * @param locale the locale as a BCP 47 langauge tag.
1207 * @param uiOptionsAsFlags the UI options to use, as flags.
1208 * @return one of the {@code CONFIRMATIONUI_*} constants, for
1209 * example {@code KeyStore.CONFIRMATIONUI_OK}.
1210 */
1211 public int presentConfirmationPrompt(IBinder listener, String promptText, byte[] extraData,
1212 String locale, int uiOptionsAsFlags) {
1213 try {
1214 return mBinder.presentConfirmationPrompt(listener, promptText, extraData, locale,
1215 uiOptionsAsFlags);
1216 } catch (RemoteException e) {
1217 Log.w(TAG, "Cannot connect to keystore", e);
1218 return CONFIRMATIONUI_SYSTEM_ERROR;
1219 }
1220 }
1221
1222 /**
1223 * Requests keystore call into the confirmationui HAL to cancel displaying a prompt.
1224 *
1225 * @param listener the binder passed to the {@link #presentConfirmationPrompt} method.
1226 * @return one of the {@code CONFIRMATIONUI_*} constants, for
1227 * example {@code KeyStore.CONFIRMATIONUI_OK}.
1228 */
1229 public int cancelConfirmationPrompt(IBinder listener) {
1230 try {
1231 return mBinder.cancelConfirmationPrompt(listener);
1232 } catch (RemoteException e) {
1233 Log.w(TAG, "Cannot connect to keystore", e);
1234 return CONFIRMATIONUI_SYSTEM_ERROR;
1235 }
1236 }
1237
Chad Brubakera91a8502015-05-07 10:02:22 -07001238 /**
David Zeuthenbbb7f652018-02-26 11:04:18 -05001239 * Requests keystore to check if the confirmationui HAL is available.
1240 *
1241 * @return whether the confirmationUI HAL is available.
1242 */
1243 public boolean isConfirmationPromptSupported() {
1244 try {
1245 return mBinder.isConfirmationPromptSupported();
1246 } catch (RemoteException e) {
1247 Log.w(TAG, "Cannot connect to keystore", e);
1248 return false;
1249 }
1250 }
1251
1252 /**
Alex Klyubinad9ba102015-04-21 15:17:24 -07001253 * Returns a {@link KeyStoreException} corresponding to the provided keystore/keymaster error
1254 * code.
1255 */
Mathew Inwoode420f8b2018-08-16 18:40:47 +01001256 @UnsupportedAppUsage
Alex Klyubindcdaf872015-05-13 15:57:09 -07001257 public static KeyStoreException getKeyStoreException(int errorCode) {
Alex Klyubinb4834ae2015-04-02 15:53:46 -07001258 if (errorCode > 0) {
1259 // KeyStore layer error
1260 switch (errorCode) {
1261 case NO_ERROR:
1262 return new KeyStoreException(errorCode, "OK");
1263 case LOCKED:
Alex Klyubin54183932015-05-08 15:25:48 -07001264 return new KeyStoreException(errorCode, "User authentication required");
Alex Klyubinb4834ae2015-04-02 15:53:46 -07001265 case UNINITIALIZED:
1266 return new KeyStoreException(errorCode, "Keystore not initialized");
1267 case SYSTEM_ERROR:
1268 return new KeyStoreException(errorCode, "System error");
1269 case PERMISSION_DENIED:
1270 return new KeyStoreException(errorCode, "Permission denied");
1271 case KEY_NOT_FOUND:
1272 return new KeyStoreException(errorCode, "Key not found");
1273 case VALUE_CORRUPTED:
1274 return new KeyStoreException(errorCode, "Key blob corrupted");
Alex Klyubin058de022015-04-29 17:32:00 -07001275 case OP_AUTH_NEEDED:
1276 return new KeyStoreException(errorCode, "Operation requires authorization");
Max Bires13f98ce2018-11-02 10:50:40 -07001277 case KEY_PERMANENTLY_INVALIDATED:
1278 return new KeyStoreException(errorCode, "Key permanently invalidated");
Alex Klyubinb4834ae2015-04-02 15:53:46 -07001279 default:
1280 return new KeyStoreException(errorCode, String.valueOf(errorCode));
1281 }
1282 } else {
1283 // Keymaster layer error
1284 switch (errorCode) {
1285 case KeymasterDefs.KM_ERROR_INVALID_AUTHORIZATION_TIMEOUT:
1286 // The name of this parameter significantly differs between Keymaster and
1287 // framework APIs. Use the framework wording to make life easier for developers.
1288 return new KeyStoreException(errorCode,
1289 "Invalid user authentication validity duration");
1290 default:
1291 return new KeyStoreException(errorCode,
1292 KeymasterDefs.getErrorMessage(errorCode));
1293 }
1294 }
1295 }
1296
Alex Klyubinad9ba102015-04-21 15:17:24 -07001297 /**
1298 * Returns an {@link InvalidKeyException} corresponding to the provided
1299 * {@link KeyStoreException}.
1300 */
Alex Klyubindcdaf872015-05-13 15:57:09 -07001301 public InvalidKeyException getInvalidKeyException(
Alex Klyubin3876b1b2015-09-09 14:55:03 -07001302 String keystoreKeyAlias, int uid, KeyStoreException e) {
Alex Klyubinb4834ae2015-04-02 15:53:46 -07001303 switch (e.getErrorCode()) {
Brian Youngda82e2c2018-02-22 23:36:34 +00001304 case LOCKED:
Alex Klyubin54183932015-05-08 15:25:48 -07001305 return new UserNotAuthenticatedException();
Brian Youngda82e2c2018-02-22 23:36:34 +00001306 case KeymasterDefs.KM_ERROR_KEY_EXPIRED:
Alex Klyubinb4834ae2015-04-02 15:53:46 -07001307 return new KeyExpiredException();
Brian Youngda82e2c2018-02-22 23:36:34 +00001308 case KeymasterDefs.KM_ERROR_KEY_NOT_YET_VALID:
Alex Klyubinb4834ae2015-04-02 15:53:46 -07001309 return new KeyNotYetValidException();
Brian Youngda82e2c2018-02-22 23:36:34 +00001310 case KeymasterDefs.KM_ERROR_KEY_USER_NOT_AUTHENTICATED:
1311 case OP_AUTH_NEEDED:
Alex Klyubin708fc9402015-04-28 18:58:47 -07001312 {
1313 // We now need to determine whether the key/operation can become usable if user
1314 // authentication is performed, or whether it can never become usable again.
1315 // User authentication requirements are contained in the key's characteristics. We
1316 // need to check whether these requirements can be be satisfied by asking the user
1317 // to authenticate.
1318 KeyCharacteristics keyCharacteristics = new KeyCharacteristics();
1319 int getKeyCharacteristicsErrorCode =
Alex Klyubin3876b1b2015-09-09 14:55:03 -07001320 getKeyCharacteristics(keystoreKeyAlias, null, null, uid,
1321 keyCharacteristics);
Alex Klyubin708fc9402015-04-28 18:58:47 -07001322 if (getKeyCharacteristicsErrorCode != NO_ERROR) {
1323 return new InvalidKeyException(
1324 "Failed to obtained key characteristics",
1325 getKeyStoreException(getKeyCharacteristicsErrorCode));
1326 }
Alex Klyubinae6cb7a2015-06-22 18:09:35 -07001327 List<BigInteger> keySids =
1328 keyCharacteristics.getUnsignedLongs(KeymasterDefs.KM_TAG_USER_SECURE_ID);
Alex Klyubin708fc9402015-04-28 18:58:47 -07001329 if (keySids.isEmpty()) {
1330 // Key is not bound to any SIDs -- no amount of authentication will help here.
1331 return new KeyPermanentlyInvalidatedException();
1332 }
1333 long rootSid = GateKeeper.getSecureUserId();
Alex Klyubinae6cb7a2015-06-22 18:09:35 -07001334 if ((rootSid != 0) && (keySids.contains(KeymasterArguments.toUint64(rootSid)))) {
Alex Klyubin708fc9402015-04-28 18:58:47 -07001335 // One of the key's SIDs is the current root SID -- user can be authenticated
1336 // against that SID.
1337 return new UserNotAuthenticatedException();
1338 }
1339
Kevin Chyn057b7432018-09-24 14:36:39 -07001340 final long fingerprintOnlySid = getFingerprintOnlySid();
Alex Klyubin708fc9402015-04-28 18:58:47 -07001341 if ((fingerprintOnlySid != 0)
Alex Klyubinae6cb7a2015-06-22 18:09:35 -07001342 && (keySids.contains(KeymasterArguments.toUint64(fingerprintOnlySid)))) {
Alex Klyubin708fc9402015-04-28 18:58:47 -07001343 // One of the key's SIDs is the current fingerprint SID -- user can be
1344 // authenticated against that SID.
1345 return new UserNotAuthenticatedException();
1346 }
1347
Kevin Chyn057b7432018-09-24 14:36:39 -07001348 final long faceOnlySid = getFaceOnlySid();
1349 if ((faceOnlySid != 0)
1350 && (keySids.contains(KeymasterArguments.toUint64(faceOnlySid)))) {
1351 // One of the key's SIDs is the current face SID -- user can be
1352 // authenticated against that SID.
1353 return new UserNotAuthenticatedException();
1354 }
1355
Alex Klyubin708fc9402015-04-28 18:58:47 -07001356 // None of the key's SIDs can ever be authenticated
1357 return new KeyPermanentlyInvalidatedException();
1358 }
Brian Youngda82e2c2018-02-22 23:36:34 +00001359 case UNINITIALIZED:
Janis Danisevskisd07d3382017-09-01 14:45:16 -07001360 return new KeyPermanentlyInvalidatedException();
Alex Klyubinb4834ae2015-04-02 15:53:46 -07001361 default:
Alex Klyubinad9ba102015-04-21 15:17:24 -07001362 return new InvalidKeyException("Keystore operation failed", e);
Alex Klyubinb4834ae2015-04-02 15:53:46 -07001363 }
1364 }
1365
Kevin Chyn057b7432018-09-24 14:36:39 -07001366 private long getFaceOnlySid() {
1367 final PackageManager packageManager = mContext.getPackageManager();
1368 if (!packageManager.hasSystemFeature(PackageManager.FEATURE_FACE)) {
1369 return 0;
1370 }
1371 FaceManager faceManager = mContext.getSystemService(FaceManager.class);
1372 if (faceManager == null) {
1373 return 0;
1374 }
1375
1376 // TODO: Restore USE_BIOMETRIC or USE_BIOMETRIC_INTERNAL permission check in
1377 // FaceManager.getAuthenticatorId once the ID is no longer needed here.
1378 return faceManager.getAuthenticatorId();
1379 }
1380
Alex Klyubin2d7a85c2015-04-30 11:43:53 -07001381 private long getFingerprintOnlySid() {
Kevin Chyn55966422017-10-23 16:08:47 -07001382 final PackageManager packageManager = mContext.getPackageManager();
1383 if (!packageManager.hasSystemFeature(PackageManager.FEATURE_FINGERPRINT)) {
1384 return 0;
1385 }
Alex Klyubina99b8b52015-06-11 13:27:34 -07001386 FingerprintManager fingerprintManager = mContext.getSystemService(FingerprintManager.class);
Alex Klyubin2d7a85c2015-04-30 11:43:53 -07001387 if (fingerprintManager == null) {
Alex Klyubin708fc9402015-04-28 18:58:47 -07001388 return 0;
1389 }
1390
Alex Klyubina99b8b52015-06-11 13:27:34 -07001391 // TODO: Restore USE_FINGERPRINT permission check in
1392 // FingerprintManager.getAuthenticatorId once the ID is no longer needed here.
Alex Klyubin2d7a85c2015-04-30 11:43:53 -07001393 return fingerprintManager.getAuthenticatorId();
Svetoslav2dac95d2015-04-30 11:30:33 -07001394 }
1395
Alex Klyubinad9ba102015-04-21 15:17:24 -07001396 /**
1397 * Returns an {@link InvalidKeyException} corresponding to the provided keystore/keymaster error
1398 * code.
1399 */
Alex Klyubin3876b1b2015-09-09 14:55:03 -07001400 public InvalidKeyException getInvalidKeyException(String keystoreKeyAlias, int uid,
1401 int errorCode) {
1402 return getInvalidKeyException(keystoreKeyAlias, uid, getKeyStoreException(errorCode));
Alex Klyubinb4834ae2015-04-02 15:53:46 -07001403 }
Chia-chi Yeh44039172009-09-21 11:53:59 +08001404}