blob: def7f75ac3b6496cf20893113d9cba6aff2a49ae [file] [log] [blame]
Gilad Brettercb51b8b2018-03-22 17:04:51 +02001/*
2 * Copyright (C) 2018 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
Kevin Chyn2ffadb32018-06-19 11:29:38 -070017package com.android.server.biometrics.face;
Gilad Brettercb51b8b2018-03-22 17:04:51 +020018
19import static android.Manifest.permission.INTERACT_ACROSS_USERS;
Kevin Chyna24e9fd2018-08-27 12:39:17 -070020import static android.Manifest.permission.MANAGE_BIOMETRIC;
Gilad Brettercb51b8b2018-03-22 17:04:51 +020021import static android.Manifest.permission.RESET_FACE_LOCKOUT;
Kevin Chyna24e9fd2018-08-27 12:39:17 -070022import static android.Manifest.permission.USE_BIOMETRIC_INTERNAL;
Gilad Brettercb51b8b2018-03-22 17:04:51 +020023
24import android.app.ActivityManager;
Gilad Brettercb51b8b2018-03-22 17:04:51 +020025import android.app.AppOpsManager;
Kevin Chyn56e4c3d2019-04-23 11:28:43 -070026import android.app.Notification;
27import android.app.NotificationChannel;
28import android.app.NotificationManager;
29import android.app.PendingIntent;
Gilad Brettercb51b8b2018-03-22 17:04:51 +020030import android.content.Context;
Kevin Chyn56e4c3d2019-04-23 11:28:43 -070031import android.content.Intent;
Gilad Brettercb51b8b2018-03-22 17:04:51 +020032import android.content.pm.UserInfo;
Kevin Chyna56dff72018-06-19 18:41:12 -070033import android.hardware.biometrics.BiometricAuthenticator;
34import android.hardware.biometrics.BiometricConstants;
Kevin Chyn7782d142019-01-18 12:51:33 -080035import android.hardware.biometrics.BiometricsProtoEnums;
Kevin Chyna56dff72018-06-19 18:41:12 -070036import android.hardware.biometrics.IBiometricServiceLockoutResetCallback;
Kevin Chyn23289ef2018-11-28 16:32:36 -080037import android.hardware.biometrics.IBiometricServiceReceiverInternal;
Gilad Brettercb51b8b2018-03-22 17:04:51 +020038import android.hardware.biometrics.face.V1_0.IBiometricsFace;
39import android.hardware.biometrics.face.V1_0.IBiometricsFaceClientCallback;
Kevin Chynb95f1522019-03-04 16:45:15 -080040import android.hardware.biometrics.face.V1_0.OptionalBool;
Kevin Chynd79e24e2018-09-25 12:06:59 -070041import android.hardware.biometrics.face.V1_0.Status;
Gilad Brettercb51b8b2018-03-22 17:04:51 +020042import android.hardware.face.Face;
Kevin Chyna24e9fd2018-08-27 12:39:17 -070043import android.hardware.face.FaceManager;
Gilad Brettercb51b8b2018-03-22 17:04:51 +020044import android.hardware.face.IFaceService;
Gilad Brettercb51b8b2018-03-22 17:04:51 +020045import android.hardware.face.IFaceServiceReceiver;
46import android.os.Binder;
Joe Onoratobf955d22019-03-25 00:16:58 -070047import android.os.Build;
Gilad Brettercb51b8b2018-03-22 17:04:51 +020048import android.os.Environment;
Gilad Brettercb51b8b2018-03-22 17:04:51 +020049import android.os.IBinder;
Joe Onoratodb396002019-04-05 19:49:27 -070050import android.os.NativeHandle;
Gilad Brettercb51b8b2018-03-22 17:04:51 +020051import android.os.RemoteException;
52import android.os.SELinux;
Joe Onorato108413a2019-04-03 18:20:52 -070053import android.os.SystemProperties;
Gilad Brettercb51b8b2018-03-22 17:04:51 +020054import android.os.UserHandle;
55import android.os.UserManager;
Gilad Brettercb51b8b2018-03-22 17:04:51 +020056import android.util.Slog;
Gilad Brettercb51b8b2018-03-22 17:04:51 +020057
Kevin Chyn56e4c3d2019-04-23 11:28:43 -070058import com.android.internal.R;
Gilad Brettercb51b8b2018-03-22 17:04:51 +020059import com.android.internal.annotations.GuardedBy;
60import com.android.internal.logging.MetricsLogger;
61import com.android.internal.util.DumpUtils;
62import com.android.server.SystemServerInitThreadPool;
Kevin Chyna38653c2019-02-11 17:46:21 -080063import com.android.server.biometrics.AuthenticationClient;
Kevin Chyn355c6bf2018-09-20 22:14:19 -070064import com.android.server.biometrics.BiometricServiceBase;
Kevin Chyn836f2cf2018-08-27 11:06:39 -070065import com.android.server.biometrics.BiometricUtils;
Kevin Chyn4cc49f72019-04-24 13:53:35 -070066import com.android.server.biometrics.Constants;
Kevin Chyn0ce70852019-05-10 10:29:18 -070067import com.android.server.biometrics.EnumerateClient;
Kevin Chyn6737c572019-02-08 16:10:54 -080068import com.android.server.biometrics.RemovalClient;
Gilad Brettercb51b8b2018-03-22 17:04:51 +020069
70import org.json.JSONArray;
71import org.json.JSONException;
72import org.json.JSONObject;
73
74import java.io.File;
75import java.io.FileDescriptor;
Joe Onoratodb396002019-04-05 19:49:27 -070076import java.io.FileOutputStream;
77import java.io.IOException;
Gilad Brettercb51b8b2018-03-22 17:04:51 +020078import java.io.PrintWriter;
79import java.util.ArrayList;
Joe Onoratodb396002019-04-05 19:49:27 -070080import java.util.Arrays;
Kevin Chyn9bc1d492019-06-21 15:31:50 -070081import java.util.HashMap;
Gilad Brettercb51b8b2018-03-22 17:04:51 +020082import java.util.List;
Kevin Chyn9bc1d492019-06-21 15:31:50 -070083import java.util.Map;
Gilad Brettercb51b8b2018-03-22 17:04:51 +020084
85/**
86 * A service to manage multiple clients that want to access the face HAL API.
87 * The service is responsible for maintaining a list of clients and dispatching all
Kevin Chyn51676d22018-11-05 18:00:43 -080088 * face-related events.
Gilad Brettercb51b8b2018-03-22 17:04:51 +020089 *
90 * @hide
91 */
Kevin Chyn355c6bf2018-09-20 22:14:19 -070092public class FaceService extends BiometricServiceBase {
Kevin Chyna56dff72018-06-19 18:41:12 -070093
94 protected static final String TAG = "FaceService";
95 private static final boolean DEBUG = true;
Gilad Brettercb51b8b2018-03-22 17:04:51 +020096 private static final String FACE_DATA_DIR = "facedata";
Gilad Brettercb51b8b2018-03-22 17:04:51 +020097 private static final String ACTION_LOCKOUT_RESET =
Kevin Chyn2ffadb32018-06-19 11:29:38 -070098 "com.android.server.biometrics.face.ACTION_LOCKOUT_RESET";
Kevin Chyne46a2162018-09-20 18:43:01 -070099 private static final int CHALLENGE_TIMEOUT_SEC = 600; // 10 minutes
Gilad Brettercb51b8b2018-03-22 17:04:51 +0200100
Kevin Chyndbfbed42019-06-13 17:01:30 -0700101 private static final String NOTIFICATION_TAG = "FaceService";
102 private static final int NOTIFICATION_ID = 1;
103
Kevin Chyn9bc1d492019-06-21 15:31:50 -0700104 /**
105 * Events for bugreports.
106 */
107 public static final class AuthenticationEvent {
108 private long mStartTime;
109 private long mLatency;
110 // Only valid if mError is 0
111 private boolean mAuthenticated;
112 private int mError;
113 // Only valid if mError is ERROR_VENDOR
114 private int mVendorError;
115
116 AuthenticationEvent(long startTime, long latency, boolean authenticated, int error,
117 int vendorError) {
118 mStartTime = startTime;
119 mLatency = latency;
120 mAuthenticated = authenticated;
121 mError = error;
122 mVendorError = vendorError;
123 }
124
125 public String toString(Context context) {
126 return "Start: " + mStartTime
127 + "\tLatency: " + mLatency
128 + "\tAuthenticated: " + mAuthenticated
129 + "\tError: " + mError
130 + "\tVendorCode: " + mVendorError
131 + "\t" + FaceManager.getErrorString(context, mError, mVendorError);
132 }
133 }
134
135 /**
136 * Keep a short historical buffer of stats, with an aggregated usage time.
137 */
138 private class UsageStats {
139 static final int EVENT_LOG_SIZE = 100;
140
141 Context mContext;
142 List<AuthenticationEvent> mAuthenticationEvents;
143
144 int acceptCount;
145 int rejectCount;
146 Map<Integer, Integer> mErrorCount;
147
148 long acceptLatency;
149 long rejectLatency;
150 Map<Integer, Long> mErrorLatency;
151
152 UsageStats(Context context) {
153 mAuthenticationEvents = new ArrayList<>();
154 mErrorCount = new HashMap<>();
155 mErrorLatency = new HashMap<>();
156 mContext = context;
157 }
158
159 void addEvent(AuthenticationEvent event) {
160 if (mAuthenticationEvents.size() >= EVENT_LOG_SIZE) {
161 mAuthenticationEvents.remove(0);
162 }
163 mAuthenticationEvents.add(event);
164
165 if (event.mAuthenticated) {
166 acceptCount++;
167 acceptLatency += event.mLatency;
168 } else if (event.mError == 0) {
169 rejectCount++;
170 rejectLatency += event.mLatency;
171 } else {
172 mErrorCount.put(event.mError, mErrorCount.getOrDefault(event.mError, 0) + 1);
173 mErrorLatency.put(event.mError,
174 mErrorLatency.getOrDefault(event.mError, 0l) + event.mLatency);
175 }
176 }
177
178 void print(PrintWriter pw) {
179 pw.println("Events since last reboot: " + mAuthenticationEvents.size());
180 for (int i = 0; i < mAuthenticationEvents.size(); i++) {
181 pw.println(mAuthenticationEvents.get(i).toString(mContext));
182 }
183
184 // Dump aggregated usage stats
185 // TODO: Remove or combine with json dump in a future release
186 pw.println("Accept\tCount: " + acceptCount + "\tLatency: " + acceptLatency
187 + "\tAverage: " + (acceptCount > 0 ? acceptLatency / acceptCount : 0));
188 pw.println("Reject\tCount: " + rejectCount + "\tLatency: " + rejectLatency
189 + "\tAverage: " + (rejectCount > 0 ? rejectLatency / rejectCount : 0));
190
191 for (Integer key : mErrorCount.keySet()) {
192 final int count = mErrorCount.get(key);
193 pw.println("Error" + key + "\tCount: " + count
194 + "\tLatency: " + mErrorLatency.getOrDefault(key, 0l)
195 + "\tAverage: " + (count > 0 ? mErrorLatency.getOrDefault(key, 0l) / count
196 : 0)
197 + "\t" + FaceManager.getErrorString(mContext, key, 0 /* vendorCode */));
198 }
199 }
200 }
201
Kevin Chyn8b7a0372018-09-17 15:06:05 -0700202 private final class FaceAuthClient extends AuthenticationClientImpl {
Kevin Chyn0ce70852019-05-10 10:29:18 -0700203 private int mLastAcquire;
204
Kevin Chyn8b7a0372018-09-17 15:06:05 -0700205 public FaceAuthClient(Context context,
206 DaemonWrapper daemon, long halDeviceId, IBinder token,
207 ServiceListener listener, int targetUserId, int groupId, long opId,
Kevin Chyn87f257a2018-11-27 16:26:07 -0800208 boolean restricted, String owner, int cookie, boolean requireConfirmation) {
Kevin Chyn8b7a0372018-09-17 15:06:05 -0700209 super(context, daemon, halDeviceId, token, listener, targetUserId, groupId, opId,
Kevin Chyn87f257a2018-11-27 16:26:07 -0800210 restricted, owner, cookie, requireConfirmation);
Kevin Chyn8b7a0372018-09-17 15:06:05 -0700211 }
Kevin Chyn7782d142019-01-18 12:51:33 -0800212
213 @Override
214 protected int statsModality() {
215 return FaceService.this.statsModality();
216 }
Kevin Chyna38653c2019-02-11 17:46:21 -0800217
218 @Override
219 public boolean shouldFrameworkHandleLockout() {
220 return false;
221 }
Kevin Chyn56d6b072019-02-13 18:39:01 -0800222
223 @Override
Kevin Chyn0ce70852019-05-10 10:29:18 -0700224 public boolean wasUserDetected() {
225 return mLastAcquire != FaceManager.FACE_ACQUIRED_NOT_DETECTED;
226 }
227
228 @Override
Kevin Chyn56d6b072019-02-13 18:39:01 -0800229 public boolean onAuthenticated(BiometricAuthenticator.Identifier identifier,
230 boolean authenticated, ArrayList<Byte> token) {
231 final boolean result = super.onAuthenticated(identifier, authenticated, token);
232
Kevin Chyn9bc1d492019-06-21 15:31:50 -0700233 mUsageStats.addEvent(new AuthenticationEvent(
234 getStartTimeMs(),
235 System.currentTimeMillis() - getStartTimeMs() /* latency */,
236 authenticated,
237 0 /* error */,
238 0 /* vendorError */));
239
Kevin Chyn56d6b072019-02-13 18:39:01 -0800240 // For face, the authentication lifecycle ends either when
241 // 1) Authenticated == true
242 // 2) Error occurred
243 // 3) Authenticated == false
244 // Fingerprint currently does not end when the third condition is met which is a bug,
245 // but let's leave it as-is for now.
246 return result || !authenticated;
247 }
Kevin Chyn56e4c3d2019-04-23 11:28:43 -0700248
249 @Override
Kevin Chyn9bc1d492019-06-21 15:31:50 -0700250 public boolean onError(long deviceId, int error, int vendorCode) {
251 mUsageStats.addEvent(new AuthenticationEvent(
252 getStartTimeMs(),
253 System.currentTimeMillis() - getStartTimeMs() /* latency */,
254 false /* authenticated */,
255 error,
256 vendorCode));
257
258 return super.onError(deviceId, error, vendorCode);
259 }
260
261 @Override
Kevin Chyn4cc49f72019-04-24 13:53:35 -0700262 public int[] getAcquireIgnorelist() {
263 if (isBiometricPrompt()) {
264 return mBiometricPromptIgnoreList;
265 } else {
266 // Keyguard
267 return mKeyguardIgnoreList;
268 }
269 }
270
271 @Override
272 public int[] getAcquireVendorIgnorelist() {
273 if (isBiometricPrompt()) {
274 return mBiometricPromptIgnoreListVendor;
275 } else {
276 // Keyguard
277 return mKeyguardIgnoreListVendor;
278 }
279 }
280
281 @Override
Kevin Chyn56e4c3d2019-04-23 11:28:43 -0700282 public boolean onAcquired(int acquireInfo, int vendorCode) {
283
Kevin Chyn0ce70852019-05-10 10:29:18 -0700284 mLastAcquire = acquireInfo;
285
Kevin Chyn56e4c3d2019-04-23 11:28:43 -0700286 if (acquireInfo == FaceManager.FACE_ACQUIRED_RECALIBRATE) {
287 final String name =
288 getContext().getString(R.string.face_recalibrate_notification_name);
289 final String title =
290 getContext().getString(R.string.face_recalibrate_notification_title);
291 final String content =
292 getContext().getString(R.string.face_recalibrate_notification_content);
293
294 final Intent intent = new Intent("android.settings.FACE_SETTINGS");
295 intent.setPackage("com.android.settings");
296
297 final PendingIntent pendingIntent = PendingIntent.getActivityAsUser(getContext(),
298 0 /* requestCode */, intent, 0 /* flags */, null /* options */,
299 UserHandle.CURRENT);
300
Kevin Chyndbfbed42019-06-13 17:01:30 -0700301 final String channelName = "FaceEnrollNotificationChannel";
Kevin Chyn56e4c3d2019-04-23 11:28:43 -0700302
Kevin Chyndbfbed42019-06-13 17:01:30 -0700303 NotificationChannel channel = new NotificationChannel(channelName, name,
Kevin Chyn56e4c3d2019-04-23 11:28:43 -0700304 NotificationManager.IMPORTANCE_HIGH);
Kevin Chyndbfbed42019-06-13 17:01:30 -0700305 Notification notification = new Notification.Builder(getContext(), channelName)
Kevin Chyn56e4c3d2019-04-23 11:28:43 -0700306 .setSmallIcon(R.drawable.ic_lock)
307 .setContentTitle(title)
308 .setContentText(content)
309 .setSubText(name)
310 .setOnlyAlertOnce(true)
311 .setLocalOnly(true)
312 .setAutoCancel(true)
313 .setCategory(Notification.CATEGORY_SYSTEM)
314 .setContentIntent(pendingIntent)
Kevin Chyn0c3a9982019-06-11 19:09:27 -0700315 .setVisibility(Notification.VISIBILITY_SECRET)
Kevin Chyn56e4c3d2019-04-23 11:28:43 -0700316 .build();
317
Kevin Chyndbfbed42019-06-13 17:01:30 -0700318 mNotificationManager.createNotificationChannel(channel);
319 mNotificationManager.notifyAsUser(NOTIFICATION_TAG, NOTIFICATION_ID, notification,
320 UserHandle.CURRENT);
Kevin Chyn56e4c3d2019-04-23 11:28:43 -0700321 }
322
323 return super.onAcquired(acquireInfo, vendorCode);
324 }
Kevin Chyn8b7a0372018-09-17 15:06:05 -0700325 }
326
Gilad Brettercb51b8b2018-03-22 17:04:51 +0200327 /**
Kevin Chyna56dff72018-06-19 18:41:12 -0700328 * Receives the incoming binder calls from FaceManager.
Gilad Brettercb51b8b2018-03-22 17:04:51 +0200329 */
Gilad Brettercb51b8b2018-03-22 17:04:51 +0200330 private final class FaceServiceWrapper extends IFaceService.Stub {
Kevin Chyna56dff72018-06-19 18:41:12 -0700331
332 /**
333 * The following methods contain common code which is shared in biometrics/common.
334 */
Kevin Chyna38653c2019-02-11 17:46:21 -0800335
Gilad Brettercb51b8b2018-03-22 17:04:51 +0200336 @Override // Binder call
Kevin Chynd79e24e2018-09-25 12:06:59 -0700337 public long generateChallenge(IBinder token) {
Kevin Chyna24e9fd2018-08-27 12:39:17 -0700338 checkPermission(MANAGE_BIOMETRIC);
Kevin Chynd79e24e2018-09-25 12:06:59 -0700339 return startGenerateChallenge(token);
Gilad Brettercb51b8b2018-03-22 17:04:51 +0200340 }
341
342 @Override // Binder call
Kevin Chynd79e24e2018-09-25 12:06:59 -0700343 public int revokeChallenge(IBinder token) {
Kevin Chyna24e9fd2018-08-27 12:39:17 -0700344 checkPermission(MANAGE_BIOMETRIC);
Kevin Chynd79e24e2018-09-25 12:06:59 -0700345 return startRevokeChallenge(token);
Gilad Brettercb51b8b2018-03-22 17:04:51 +0200346 }
347
348 @Override // Binder call
Kevin Chyn1f16c2d2018-12-07 13:06:08 -0800349 public void enroll(final IBinder token, final byte[] cryptoToken,
350 final IFaceServiceReceiver receiver, final String opPackageName,
351 final int[] disabledFeatures) {
Kevin Chyna24e9fd2018-08-27 12:39:17 -0700352 checkPermission(MANAGE_BIOMETRIC);
Gilad Brettercb51b8b2018-03-22 17:04:51 +0200353
Kevin Chyndbfbed42019-06-13 17:01:30 -0700354 mNotificationManager.cancelAsUser(NOTIFICATION_TAG, NOTIFICATION_ID,
355 UserHandle.CURRENT);
356
Gilad Brettercb51b8b2018-03-22 17:04:51 +0200357 final boolean restricted = isRestricted();
Kevin Chyna56dff72018-06-19 18:41:12 -0700358 final EnrollClientImpl client = new EnrollClientImpl(getContext(), mDaemonWrapper,
359 mHalDeviceId, token, new ServiceListenerImpl(receiver), mCurrentUserId,
Kevin Chyn1429a312019-01-28 16:08:09 -0800360 0 /* groupId */, cryptoToken, restricted, opPackageName, disabledFeatures) {
Kevin Chyn4cc49f72019-04-24 13:53:35 -0700361
362 @Override
363 public int[] getAcquireIgnorelist() {
364 return mEnrollIgnoreList;
365 }
366
367 @Override
368 public int[] getAcquireVendorIgnorelist() {
369 return mEnrollIgnoreListVendor;
370 }
371
Kevin Chyn1429a312019-01-28 16:08:09 -0800372 @Override
373 public boolean shouldVibrate() {
374 return false;
375 }
Kevin Chyn7782d142019-01-18 12:51:33 -0800376
377 @Override
378 protected int statsModality() {
379 return FaceService.this.statsModality();
380 }
Kevin Chyn1429a312019-01-28 16:08:09 -0800381 };
Gilad Brettercb51b8b2018-03-22 17:04:51 +0200382
Kevin Chyn1a878c12019-04-04 15:50:11 -0700383 enrollInternal(client, mCurrentUserId);
Gilad Brettercb51b8b2018-03-22 17:04:51 +0200384 }
385
386 @Override // Binder call
387 public void cancelEnrollment(final IBinder token) {
Kevin Chyna24e9fd2018-08-27 12:39:17 -0700388 checkPermission(MANAGE_BIOMETRIC);
Kevin Chyna56dff72018-06-19 18:41:12 -0700389 cancelEnrollmentInternal(token);
Gilad Brettercb51b8b2018-03-22 17:04:51 +0200390 }
391
392 @Override // Binder call
Kevin Chyn747e29b2019-01-11 17:01:53 -0800393 public void authenticate(final IBinder token, final long opId, int userId,
Kevin Chyna56dff72018-06-19 18:41:12 -0700394 final IFaceServiceReceiver receiver, final int flags,
Kevin Chyna24e9fd2018-08-27 12:39:17 -0700395 final String opPackageName) {
396 checkPermission(USE_BIOMETRIC_INTERNAL);
Kevin Chyn747e29b2019-01-11 17:01:53 -0800397 updateActiveGroup(userId, opPackageName);
Gilad Brettercb51b8b2018-03-22 17:04:51 +0200398 final boolean restricted = isRestricted();
Kevin Chyn8b7a0372018-09-17 15:06:05 -0700399 final AuthenticationClientImpl client = new FaceAuthClient(getContext(),
Kevin Chyna56dff72018-06-19 18:41:12 -0700400 mDaemonWrapper, mHalDeviceId, token, new ServiceListenerImpl(receiver),
Kevin Chyna24e9fd2018-08-27 12:39:17 -0700401 mCurrentUserId, 0 /* groupId */, opId, restricted, opPackageName,
Kevin Chyn87f257a2018-11-27 16:26:07 -0800402 0 /* cookie */, false /* requireConfirmation */);
Kevin Chyna56dff72018-06-19 18:41:12 -0700403 authenticateInternal(client, opId, opPackageName);
Gilad Brettercb51b8b2018-03-22 17:04:51 +0200404 }
405
406 @Override // Binder call
Kevin Chyn87f257a2018-11-27 16:26:07 -0800407 public void prepareForAuthentication(boolean requireConfirmation, IBinder token, long opId,
Kevin Chyn23289ef2018-11-28 16:32:36 -0800408 int groupId, IBiometricServiceReceiverInternal wrapperReceiver,
409 String opPackageName, int cookie, int callingUid, int callingPid,
410 int callingUserId) {
Kevin Chyna24e9fd2018-08-27 12:39:17 -0700411 checkPermission(USE_BIOMETRIC_INTERNAL);
Kevin Chyn41a80902019-02-06 08:12:15 -0800412 updateActiveGroup(groupId, opPackageName);
Kevin Chyna24e9fd2018-08-27 12:39:17 -0700413 final boolean restricted = true; // BiometricPrompt is always restricted
Kevin Chyn8b7a0372018-09-17 15:06:05 -0700414 final AuthenticationClientImpl client = new FaceAuthClient(getContext(),
Kevin Chyna24e9fd2018-08-27 12:39:17 -0700415 mDaemonWrapper, mHalDeviceId, token,
Kevin Chyn87f257a2018-11-27 16:26:07 -0800416 new BiometricPromptServiceListenerImpl(wrapperReceiver),
417 mCurrentUserId, 0 /* groupId */, opId, restricted, opPackageName, cookie,
Kevin Chyn158fefb2019-01-03 18:59:05 -0800418 requireConfirmation);
Kevin Chyna24e9fd2018-08-27 12:39:17 -0700419 authenticateInternal(client, opId, opPackageName, callingUid, callingPid,
420 callingUserId);
421 }
422
423 @Override // Binder call
Kevin Chyn87f257a2018-11-27 16:26:07 -0800424 public void startPreparedClient(int cookie) {
425 checkPermission(MANAGE_BIOMETRIC);
426 startCurrentClient(cookie);
427 }
428
429 @Override // Binder call
Gilad Brettercb51b8b2018-03-22 17:04:51 +0200430 public void cancelAuthentication(final IBinder token, final String opPackageName) {
Kevin Chyna24e9fd2018-08-27 12:39:17 -0700431 checkPermission(USE_BIOMETRIC_INTERNAL);
Kevin Chyna56dff72018-06-19 18:41:12 -0700432 cancelAuthenticationInternal(token, opPackageName);
Gilad Brettercb51b8b2018-03-22 17:04:51 +0200433 }
434
435 @Override // Binder call
Kevin Chyna24e9fd2018-08-27 12:39:17 -0700436 public void cancelAuthenticationFromService(final IBinder token, final String opPackageName,
Kevin Chyne92cdae2018-11-21 16:35:04 -0800437 int callingUid, int callingPid, int callingUserId, boolean fromClient) {
Kevin Chyna24e9fd2018-08-27 12:39:17 -0700438 checkPermission(USE_BIOMETRIC_INTERNAL);
Kevin Chyne92cdae2018-11-21 16:35:04 -0800439 cancelAuthenticationInternal(token, opPackageName, callingUid, callingPid,
440 callingUserId, fromClient);
Kevin Chyna24e9fd2018-08-27 12:39:17 -0700441 }
442
443 @Override // Binder call
Gilad Brettercb51b8b2018-03-22 17:04:51 +0200444 public void setActiveUser(final int userId) {
Kevin Chyna24e9fd2018-08-27 12:39:17 -0700445 checkPermission(MANAGE_BIOMETRIC);
Kevin Chyna56dff72018-06-19 18:41:12 -0700446 setActiveUserInternal(userId);
Gilad Brettercb51b8b2018-03-22 17:04:51 +0200447 }
448
449 @Override // Binder call
Kevin Chyna56dff72018-06-19 18:41:12 -0700450 public void remove(final IBinder token, final int faceId, final int userId,
451 final IFaceServiceReceiver receiver) {
Kevin Chyna24e9fd2018-08-27 12:39:17 -0700452 checkPermission(MANAGE_BIOMETRIC);
Kevin Chyna56dff72018-06-19 18:41:12 -0700453
454 if (token == null) {
455 Slog.w(TAG, "remove(): token is null");
456 return;
457 }
458
Gilad Brettercb51b8b2018-03-22 17:04:51 +0200459 final boolean restricted = isRestricted();
Kevin Chyn4cc49f72019-04-24 13:53:35 -0700460 final RemovalClient client = new RemovalClient(getContext(), getConstants(),
Kevin Chyn6737c572019-02-08 16:10:54 -0800461 mDaemonWrapper, mHalDeviceId, token, new ServiceListenerImpl(receiver), faceId,
462 0 /* groupId */, userId, restricted, token.toString(), getBiometricUtils()) {
Kevin Chyn7782d142019-01-18 12:51:33 -0800463 @Override
464 protected int statsModality() {
465 return FaceService.this.statsModality();
466 }
467 };
Kevin Chyna56dff72018-06-19 18:41:12 -0700468 removeInternal(client);
Gilad Brettercb51b8b2018-03-22 17:04:51 +0200469 }
470
Kevin Chyna56dff72018-06-19 18:41:12 -0700471 @Override
472 public void enumerate(final IBinder token, final int userId,
473 final IFaceServiceReceiver receiver) {
Kevin Chyna24e9fd2018-08-27 12:39:17 -0700474 checkPermission(MANAGE_BIOMETRIC);
Kevin Chyna56dff72018-06-19 18:41:12 -0700475
476 final boolean restricted = isRestricted();
Kevin Chyn4cc49f72019-04-24 13:53:35 -0700477 final EnumerateClient client = new EnumerateClient(getContext(), getConstants(),
Kevin Chyn6737c572019-02-08 16:10:54 -0800478 mDaemonWrapper, mHalDeviceId, token, new ServiceListenerImpl(receiver), userId,
479 userId, restricted, getContext().getOpPackageName()) {
Kevin Chyn7782d142019-01-18 12:51:33 -0800480 @Override
481 protected int statsModality() {
482 return FaceService.this.statsModality();
483 }
484 };
Kevin Chyna56dff72018-06-19 18:41:12 -0700485 enumerateInternal(client);
486 }
487
488 @Override
489 public void addLockoutResetCallback(final IBiometricServiceLockoutResetCallback callback)
490 throws RemoteException {
Kevin Chyna24e9fd2018-08-27 12:39:17 -0700491 checkPermission(USE_BIOMETRIC_INTERNAL);
Kevin Chyna56dff72018-06-19 18:41:12 -0700492 FaceService.super.addLockoutResetCallback(callback);
493 }
494
495 @Override // Binder call
496 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
497 if (!DumpUtils.checkDumpPermission(getContext(), TAG, pw)) {
498 return;
499 }
500
501 final long ident = Binder.clearCallingIdentity();
502 try {
Joe Onoratodb396002019-04-05 19:49:27 -0700503 if (args.length > 1 && "--hal".equals(args[0])) {
504 dumpHal(fd, Arrays.copyOfRange(args, 1, args.length, args.getClass()));
Kevin Chyna56dff72018-06-19 18:41:12 -0700505 } else {
506 dumpInternal(pw);
507 }
508 } finally {
509 Binder.restoreCallingIdentity(ident);
510 }
511 }
512
513 /**
514 * The following methods don't use any common code from BiometricService
515 */
516
517 // TODO: refactor out common code here
Gilad Brettercb51b8b2018-03-22 17:04:51 +0200518 @Override // Binder call
519 public boolean isHardwareDetected(long deviceId, String opPackageName) {
Kevin Chyna24e9fd2018-08-27 12:39:17 -0700520 checkPermission(USE_BIOMETRIC_INTERNAL);
Kevin Chyna56dff72018-06-19 18:41:12 -0700521 if (!canUseBiometric(opPackageName, false /* foregroundOnly */,
Gilad Brettercb51b8b2018-03-22 17:04:51 +0200522 Binder.getCallingUid(), Binder.getCallingPid(),
523 UserHandle.getCallingUserId())) {
524 return false;
525 }
526
527 final long token = Binder.clearCallingIdentity();
528 try {
529 IBiometricsFace daemon = getFaceDaemon();
530 return daemon != null && mHalDeviceId != 0;
531 } finally {
532 Binder.restoreCallingIdentity(token);
533 }
534 }
535
536 @Override // Binder call
Kevin Chyna56dff72018-06-19 18:41:12 -0700537 public void rename(final int faceId, final String name) {
Kevin Chyna24e9fd2018-08-27 12:39:17 -0700538 checkPermission(MANAGE_BIOMETRIC);
Kevin Chyna56dff72018-06-19 18:41:12 -0700539 if (!isCurrentUserOrProfile(UserHandle.getCallingUserId())) {
540 return;
541 }
542 mHandler.post(new Runnable() {
543 @Override
544 public void run() {
545 getBiometricUtils().renameBiometricForUser(getContext(), mCurrentUserId,
546 faceId, name);
547 }
548 });
549 }
550
551 @Override // Binder call
552 public List<Face> getEnrolledFaces(int userId, String opPackageName) {
Kevin Chyna24e9fd2018-08-27 12:39:17 -0700553 checkPermission(MANAGE_BIOMETRIC);
Kevin Chyna56dff72018-06-19 18:41:12 -0700554 if (!canUseBiometric(opPackageName, false /* foregroundOnly */,
Gilad Brettercb51b8b2018-03-22 17:04:51 +0200555 Binder.getCallingUid(), Binder.getCallingPid(),
556 UserHandle.getCallingUserId())) {
557 return null;
558 }
559
Kevin Chyn6737c572019-02-08 16:10:54 -0800560 return FaceService.this.getEnrolledTemplates(userId);
Gilad Brettercb51b8b2018-03-22 17:04:51 +0200561 }
562
563 @Override // Binder call
Kevin Chyna56dff72018-06-19 18:41:12 -0700564 public boolean hasEnrolledFaces(int userId, String opPackageName) {
Kevin Chyna24e9fd2018-08-27 12:39:17 -0700565 checkPermission(USE_BIOMETRIC_INTERNAL);
Kevin Chyna56dff72018-06-19 18:41:12 -0700566 if (!canUseBiometric(opPackageName, false /* foregroundOnly */,
Gilad Brettercb51b8b2018-03-22 17:04:51 +0200567 Binder.getCallingUid(), Binder.getCallingPid(),
568 UserHandle.getCallingUserId())) {
569 return false;
570 }
571
Kevin Chyna56dff72018-06-19 18:41:12 -0700572 return FaceService.this.hasEnrolledBiometrics(userId);
Gilad Brettercb51b8b2018-03-22 17:04:51 +0200573 }
574
575 @Override // Binder call
576 public long getAuthenticatorId(String opPackageName) {
577 // In this method, we're not checking whether the caller is permitted to use face
578 // API because current authenticator ID is leaked (in a more contrived way) via Android
579 // Keystore (android.security.keystore package): the user of that API can create a key
580 // which requires face authentication for its use, and then query the key's
581 // characteristics (hidden API) which returns, among other things, face
582 // authenticator ID which was active at key creation time.
583 //
584 // Reason: The part of Android Keystore which runs inside an app's process invokes this
585 // method in certain cases. Those cases are not always where the developer demonstrates
586 // explicit intent to use face functionality. Thus, to avoiding throwing an
587 // unexpected SecurityException this method does not check whether its caller is
588 // permitted to use face API.
589 //
590 // The permission check should be restored once Android Keystore no longer invokes this
591 // method from inside app processes.
592
593 return FaceService.this.getAuthenticatorId(opPackageName);
594 }
595
596 @Override // Binder call
Kevin Chyna38653c2019-02-11 17:46:21 -0800597 public void resetLockout(byte[] token) {
Kevin Chyna24e9fd2018-08-27 12:39:17 -0700598 checkPermission(MANAGE_BIOMETRIC);
Kevin Chyn1d6a2862019-04-02 16:20:21 -0700599
600 if (!FaceService.this.hasEnrolledBiometrics(mCurrentUserId)) {
601 Slog.w(TAG, "Ignoring lockout reset, no templates enrolled");
602 return;
603 }
604
Kevin Chynbe67ce02019-06-10 16:14:22 -0700605 Slog.d(TAG, "Resetting lockout for user: " + mCurrentUserId);
606
Kevin Chyna38653c2019-02-11 17:46:21 -0800607 try {
608 mDaemonWrapper.resetLockout(token);
609 } catch (RemoteException e) {
610 Slog.e(getTag(), "Unable to reset lockout", e);
611 }
Kevin Chyna56dff72018-06-19 18:41:12 -0700612 }
Kevin Chynd79e24e2018-09-25 12:06:59 -0700613
614 @Override
Kevin Chyne62749a2019-04-02 19:33:56 -0700615 public void setFeature(int feature, boolean enabled, final byte[] token,
616 IFaceServiceReceiver receiver) {
Kevin Chynd79e24e2018-09-25 12:06:59 -0700617 checkPermission(MANAGE_BIOMETRIC);
618
Kevin Chyne62749a2019-04-02 19:33:56 -0700619 mHandler.post(() -> {
620 if (!FaceService.this.hasEnrolledBiometrics(mCurrentUserId)) {
621 Slog.e(TAG, "No enrolled biometrics while setting feature: " + feature);
622 return;
Kevin Chynb95f1522019-03-04 16:45:15 -0800623 }
Kevin Chyne62749a2019-04-02 19:33:56 -0700624
625 final ArrayList<Byte> byteToken = new ArrayList<>();
626 for (int i = 0; i < token.length; i++) {
627 byteToken.add(token[i]);
628 }
629
630 // TODO: Support multiple faces
631 final int faceId = getFirstTemplateForUser(mCurrentUserId);
632
633 if (mDaemon != null) {
634 try {
635 final int result = mDaemon.setFeature(feature, enabled, byteToken, faceId);
636 receiver.onFeatureSet(result == Status.OK, feature);
637 } catch (RemoteException e) {
638 Slog.e(getTag(), "Unable to set feature: " + feature
639 + " to enabled:" + enabled, e);
640 }
641 }
642 });
643
Kevin Chynd79e24e2018-09-25 12:06:59 -0700644 }
645
646 @Override
Kevin Chyne62749a2019-04-02 19:33:56 -0700647 public void getFeature(int feature, IFaceServiceReceiver receiver) {
Kevin Chynd79e24e2018-09-25 12:06:59 -0700648 checkPermission(MANAGE_BIOMETRIC);
649
Kevin Chyne62749a2019-04-02 19:33:56 -0700650 mHandler.post(() -> {
651 // This should ideally return tri-state, but the user isn't shown settings unless
652 // they are enrolled so it's fine for now.
653 if (!FaceService.this.hasEnrolledBiometrics(mCurrentUserId)) {
654 Slog.e(TAG, "No enrolled biometrics while getting feature: " + feature);
655 return;
Kevin Chynb95f1522019-03-04 16:45:15 -0800656 }
Kevin Chyne62749a2019-04-02 19:33:56 -0700657
658 // TODO: Support multiple faces
659 final int faceId = getFirstTemplateForUser(mCurrentUserId);
660
661 if (mDaemon != null) {
662 try {
663 OptionalBool result = mDaemon.getFeature(feature, faceId);
664 receiver.onFeatureGet(result.status == Status.OK, feature, result.value);
665 } catch (RemoteException e) {
666 Slog.e(getTag(), "Unable to getRequireAttention", e);
667 }
668 }
669 });
670
Kevin Chynd79e24e2018-09-25 12:06:59 -0700671 }
Kevin Chyn57f119b2018-10-25 12:03:41 -0700672
673 @Override
674 public void userActivity() {
675 checkPermission(MANAGE_BIOMETRIC);
676
677 if (mDaemon != null) {
678 try {
679 mDaemon.userActivity();
680 } catch (RemoteException e) {
681 Slog.e(getTag(), "Unable to send userActivity", e);
682 }
683 }
684 }
Kevin Chynb95f1522019-03-04 16:45:15 -0800685
686 // TODO: Support multiple faces
687 private int getFirstTemplateForUser(int user) {
688 final List<Face> faces = FaceService.this.getEnrolledTemplates(user);
689 if (!faces.isEmpty()) {
690 return faces.get(0).getBiometricId();
691 }
692 return 0;
693 }
Kevin Chyna56dff72018-06-19 18:41:12 -0700694 }
695
696 /**
697 * Receives callbacks from the ClientMonitor implementations. The results are forwarded to
Kevin Chyna24e9fd2018-08-27 12:39:17 -0700698 * BiometricPrompt.
699 */
Kevin Chyne92cdae2018-11-21 16:35:04 -0800700 private class BiometricPromptServiceListenerImpl extends BiometricServiceListener {
Kevin Chyn23289ef2018-11-28 16:32:36 -0800701 BiometricPromptServiceListenerImpl(IBiometricServiceReceiverInternal wrapperReceiver) {
Kevin Chyn87f257a2018-11-27 16:26:07 -0800702 super(wrapperReceiver);
Kevin Chyna24e9fd2018-08-27 12:39:17 -0700703 }
704
705 @Override
706 public void onAcquired(long deviceId, int acquiredInfo, int vendorCode)
707 throws RemoteException {
708 /**
709 * Map the acquired codes onto existing {@link BiometricConstants} acquired codes.
710 */
Kevin Chyne92cdae2018-11-21 16:35:04 -0800711 if (getWrapperReceiver() != null) {
712 getWrapperReceiver().onAcquired(
Kevin Chyn8b7a0372018-09-17 15:06:05 -0700713 FaceManager.getMappedAcquiredInfo(acquiredInfo, vendorCode),
714 FaceManager.getAcquiredString(getContext(), acquiredInfo, vendorCode));
Kevin Chyna24e9fd2018-08-27 12:39:17 -0700715 }
716 }
717
718 @Override
Kevin Chyn87f257a2018-11-27 16:26:07 -0800719 public void onError(long deviceId, int error, int vendorCode, int cookie)
720 throws RemoteException {
Kevin Chyne92cdae2018-11-21 16:35:04 -0800721 if (getWrapperReceiver() != null) {
Kevin Chyn23289ef2018-11-28 16:32:36 -0800722 getWrapperReceiver().onError(cookie, error,
723 FaceManager.getErrorString(getContext(), error, vendorCode));
Kevin Chyna24e9fd2018-08-27 12:39:17 -0700724 }
725 }
726 }
727
728 /**
729 * Receives callbacks from the ClientMonitor implementations. The results are forwarded to
Kevin Chyna56dff72018-06-19 18:41:12 -0700730 * the FaceManager.
731 */
732 private class ServiceListenerImpl implements ServiceListener {
Kevin Chyna56dff72018-06-19 18:41:12 -0700733 private IFaceServiceReceiver mFaceServiceReceiver;
734
735 public ServiceListenerImpl(IFaceServiceReceiver receiver) {
736 mFaceServiceReceiver = receiver;
Gilad Brettercb51b8b2018-03-22 17:04:51 +0200737 }
738
739 @Override
Kevin Chyna56dff72018-06-19 18:41:12 -0700740 public void onEnrollResult(BiometricAuthenticator.Identifier identifier, int remaining)
Gilad Brettercb51b8b2018-03-22 17:04:51 +0200741 throws RemoteException {
Kevin Chyna56dff72018-06-19 18:41:12 -0700742 if (mFaceServiceReceiver != null) {
743 mFaceServiceReceiver.onEnrollResult(identifier.getDeviceId(),
744 identifier.getBiometricId(),
745 remaining);
746 }
Gilad Brettercb51b8b2018-03-22 17:04:51 +0200747 }
Kevin Chyna56dff72018-06-19 18:41:12 -0700748
749 @Override
750 public void onAcquired(long deviceId, int acquiredInfo, int vendorCode)
751 throws RemoteException {
752 if (mFaceServiceReceiver != null) {
753 mFaceServiceReceiver.onAcquired(deviceId, acquiredInfo, vendorCode);
754 }
755 }
756
757 @Override
758 public void onAuthenticationSucceeded(long deviceId,
759 BiometricAuthenticator.Identifier biometric, int userId)
760 throws RemoteException {
761 if (mFaceServiceReceiver != null) {
Kevin Chyn628b7182018-11-13 12:00:48 -0800762 if (biometric == null || biometric instanceof Face) {
Kevin Chyn8d2694a2019-04-11 18:30:40 -0700763 mFaceServiceReceiver.onAuthenticationSucceeded(deviceId, (Face) biometric,
764 userId);
Kevin Chyna56dff72018-06-19 18:41:12 -0700765 } else {
766 Slog.e(TAG, "onAuthenticationSucceeded received non-face biometric");
767 }
768 }
769 }
770
771 @Override
772 public void onAuthenticationFailed(long deviceId) throws RemoteException {
773 if (mFaceServiceReceiver != null) {
774 mFaceServiceReceiver.onAuthenticationFailed(deviceId);
775 }
776 }
777
778 @Override
Kevin Chyn87f257a2018-11-27 16:26:07 -0800779 public void onError(long deviceId, int error, int vendorCode, int cookie)
780 throws RemoteException {
Kevin Chyna56dff72018-06-19 18:41:12 -0700781 if (mFaceServiceReceiver != null) {
782 mFaceServiceReceiver.onError(deviceId, error, vendorCode);
783 }
784 }
785
786 @Override
787 public void onRemoved(BiometricAuthenticator.Identifier identifier,
788 int remaining) throws RemoteException {
789 if (mFaceServiceReceiver != null) {
790 mFaceServiceReceiver.onRemoved(identifier.getDeviceId(),
791 identifier.getBiometricId(), remaining);
792 }
793 }
794
795 @Override
796 public void onEnumerated(BiometricAuthenticator.Identifier identifier, int remaining)
797 throws RemoteException {
798 if (mFaceServiceReceiver != null) {
Kevin Chyn6737c572019-02-08 16:10:54 -0800799 mFaceServiceReceiver.onEnumerated(identifier.getDeviceId(),
800 identifier.getBiometricId(), remaining);
Kevin Chyna56dff72018-06-19 18:41:12 -0700801 }
802 }
803 }
804
Kevin Chyn4cc49f72019-04-24 13:53:35 -0700805 private final FaceConstants mFaceConstants = new FaceConstants();
Kevin Chyna56dff72018-06-19 18:41:12 -0700806
807 @GuardedBy("this")
808 private IBiometricsFace mDaemon;
Kevin Chyn9bc1d492019-06-21 15:31:50 -0700809 private UsageStats mUsageStats;
Kevin Chyna38653c2019-02-11 17:46:21 -0800810 // One of the AuthenticationClient constants
811 private int mCurrentUserLockoutMode;
Kevin Chyna56dff72018-06-19 18:41:12 -0700812
Kevin Chyndbfbed42019-06-13 17:01:30 -0700813 private NotificationManager mNotificationManager;
814
Kevin Chyn4cc49f72019-04-24 13:53:35 -0700815 private int[] mBiometricPromptIgnoreList;
816 private int[] mBiometricPromptIgnoreListVendor;
817 private int[] mKeyguardIgnoreList;
818 private int[] mKeyguardIgnoreListVendor;
819 private int[] mEnrollIgnoreList;
820 private int[] mEnrollIgnoreListVendor;
821
Kevin Chyna56dff72018-06-19 18:41:12 -0700822 /**
823 * Receives callbacks from the HAL.
824 */
825 private IBiometricsFaceClientCallback mDaemonCallback =
826 new IBiometricsFaceClientCallback.Stub() {
Kevin Chyn6737c572019-02-08 16:10:54 -0800827 @Override
828 public void onEnrollResult(final long deviceId, int faceId, int userId,
829 int remaining) {
830 mHandler.post(() -> {
831 final Face face = new Face(getBiometricUtils()
832 .getUniqueName(getContext(), userId), faceId, deviceId);
833 FaceService.super.handleEnrollResult(face, remaining);
Kevin Chyn576811e2019-06-12 14:50:35 -0700834
835 // Enrollment changes the authenticatorId, so update it here.
836 IBiometricsFace daemon = getFaceDaemon();
837 if (remaining == 0 && daemon != null) {
838 try {
839 mAuthenticatorIds.put(userId,
840 hasEnrolledBiometrics(userId) ? daemon.getAuthenticatorId().value
841 : 0L);
842 } catch (RemoteException e) {
843 Slog.e(TAG, "Unable to get authenticatorId", e);
844 }
845 }
Kevin Chyn6737c572019-02-08 16:10:54 -0800846 });
847 }
848
849 @Override
850 public void onAcquired(final long deviceId, final int userId,
851 final int acquiredInfo,
852 final int vendorCode) {
853 mHandler.post(() -> {
854 FaceService.super.handleAcquired(deviceId, acquiredInfo, vendorCode);
855 });
856 }
857
858 @Override
859 public void onAuthenticated(final long deviceId, final int faceId, final int userId,
860 ArrayList<Byte> token) {
861 mHandler.post(() -> {
862 Face face = new Face("", faceId, deviceId);
863 FaceService.super.handleAuthenticated(face, token);
864 });
865 }
866
867 @Override
868 public void onError(final long deviceId, final int userId, final int error,
869 final int vendorCode) {
870 mHandler.post(() -> {
871 FaceService.super.handleError(deviceId, error, vendorCode);
872
873 // TODO: this chunk of code should be common to all biometric services
874 if (error == BiometricConstants.BIOMETRIC_ERROR_HW_UNAVAILABLE) {
875 // If we get HW_UNAVAILABLE, try to connect again later...
876 Slog.w(TAG, "Got ERROR_HW_UNAVAILABLE; try reconnecting next client.");
877 synchronized (this) {
878 mDaemon = null;
879 mHalDeviceId = 0;
880 mCurrentUserId = UserHandle.USER_NULL;
881 }
Kevin Chyna56dff72018-06-19 18:41:12 -0700882 }
Kevin Chyn6737c572019-02-08 16:10:54 -0800883 });
884 }
Kevin Chyna56dff72018-06-19 18:41:12 -0700885
Kevin Chyn6737c572019-02-08 16:10:54 -0800886 @Override
Kevin Chyn31ae8d22019-03-11 14:12:32 -0700887 public void onRemoved(final long deviceId, ArrayList<Integer> faceIds, final int userId) {
Kevin Chyn6737c572019-02-08 16:10:54 -0800888 mHandler.post(() -> {
Kevin Chyn31ae8d22019-03-11 14:12:32 -0700889 if (!faceIds.isEmpty()) {
890 for (int i = 0; i < faceIds.size(); i++) {
891 final Face face = new Face("", faceIds.get(i), deviceId);
892 // Convert to old behavior
893 FaceService.super.handleRemoved(face, faceIds.size() - i - 1);
894 }
895 } else {
896 final Face face = new Face("", 0 /* identifier */, deviceId);
897 FaceService.super.handleRemoved(face, 0 /* remaining */);
898 }
899
Kevin Chyn6737c572019-02-08 16:10:54 -0800900 });
901 }
902
903 @Override
904 public void onEnumerate(long deviceId, ArrayList<Integer> faceIds, int userId)
905 throws RemoteException {
906 mHandler.post(() -> {
907 if (!faceIds.isEmpty()) {
908 for (int i = 0; i < faceIds.size(); i++) {
909 final Face face = new Face("", faceIds.get(i), deviceId);
910 // Convert to old old behavior
911 FaceService.super.handleEnumerate(face, faceIds.size() - i - 1);
912 }
913 } else {
914 // For face, the HIDL contract is to receive an empty list when there are no
915 // templates enrolled. Send a null identifier since we don't consume them
916 // anywhere, and send remaining == 0 to plumb this with existing common code.
917 FaceService.super.handleEnumerate(null /* identifier */, 0);
Kevin Chyna56dff72018-06-19 18:41:12 -0700918 }
Kevin Chyn6737c572019-02-08 16:10:54 -0800919 });
920 }
Kevin Chyna56dff72018-06-19 18:41:12 -0700921
Kevin Chyn6737c572019-02-08 16:10:54 -0800922 @Override
923 public void onLockoutChanged(long duration) {
Kevin Chyna38653c2019-02-11 17:46:21 -0800924 Slog.d(TAG, "onLockoutChanged: " + duration);
925 if (duration == 0) {
926 mCurrentUserLockoutMode = AuthenticationClient.LOCKOUT_NONE;
927 } else if (duration == Long.MAX_VALUE) {
928 mCurrentUserLockoutMode = AuthenticationClient.LOCKOUT_PERMANENT;
929 } else {
930 mCurrentUserLockoutMode = AuthenticationClient.LOCKOUT_TIMED;
931 }
Kevin Chyna56dff72018-06-19 18:41:12 -0700932
Kevin Chyna38653c2019-02-11 17:46:21 -0800933 mHandler.post(() -> {
934 if (duration == 0) {
935 notifyLockoutResetMonitors();
936 }
937 });
Kevin Chyn6737c572019-02-08 16:10:54 -0800938 }
939 };
Kevin Chyna56dff72018-06-19 18:41:12 -0700940
941 /**
942 * Wraps the HAL-specific code and is passed to the ClientMonitor implementations so that they
943 * can be shared between the multiple biometric services.
944 */
945 private final DaemonWrapper mDaemonWrapper = new DaemonWrapper() {
946 @Override
947 public int authenticate(long operationId, int groupId) throws RemoteException {
948 IBiometricsFace daemon = getFaceDaemon();
949 if (daemon == null) {
950 Slog.w(TAG, "authenticate(): no face HAL!");
951 return ERROR_ESRCH;
952 }
953 return daemon.authenticate(operationId);
954 }
955
956 @Override
957 public int cancel() throws RemoteException {
958 IBiometricsFace daemon = getFaceDaemon();
959 if (daemon == null) {
960 Slog.w(TAG, "cancel(): no face HAL!");
961 return ERROR_ESRCH;
962 }
963 return daemon.cancel();
964 }
965
966 @Override
967 public int remove(int groupId, int biometricId) throws RemoteException {
968 IBiometricsFace daemon = getFaceDaemon();
969 if (daemon == null) {
970 Slog.w(TAG, "remove(): no face HAL!");
971 return ERROR_ESRCH;
972 }
973 return daemon.remove(biometricId);
974 }
975
976 @Override
977 public int enumerate() throws RemoteException {
978 IBiometricsFace daemon = getFaceDaemon();
979 if (daemon == null) {
980 Slog.w(TAG, "enumerate(): no face HAL!");
981 return ERROR_ESRCH;
982 }
983 return daemon.enumerate();
984 }
985
986 @Override
Kevin Chyn1f16c2d2018-12-07 13:06:08 -0800987 public int enroll(byte[] cryptoToken, int groupId, int timeout,
988 ArrayList<Integer> disabledFeatures) throws RemoteException {
Kevin Chyna56dff72018-06-19 18:41:12 -0700989 IBiometricsFace daemon = getFaceDaemon();
990 if (daemon == null) {
991 Slog.w(TAG, "enroll(): no face HAL!");
992 return ERROR_ESRCH;
993 }
994 final ArrayList<Byte> token = new ArrayList<>();
995 for (int i = 0; i < cryptoToken.length; i++) {
996 token.add(cryptoToken[i]);
997 }
Kevin Chyn1f16c2d2018-12-07 13:06:08 -0800998 return daemon.enroll(token, timeout, disabledFeatures);
Kevin Chyna56dff72018-06-19 18:41:12 -0700999 }
Kevin Chyna38653c2019-02-11 17:46:21 -08001000
1001 @Override
1002 public void resetLockout(byte[] cryptoToken) throws RemoteException {
1003 IBiometricsFace daemon = getFaceDaemon();
1004 if (daemon == null) {
1005 Slog.w(TAG, "resetLockout(): no face HAL!");
1006 return;
1007 }
1008 final ArrayList<Byte> token = new ArrayList<>();
1009 for (int i = 0; i < cryptoToken.length; i++) {
1010 token.add(cryptoToken[i]);
1011 }
1012 daemon.resetLockout(token);
1013 }
Kevin Chyna56dff72018-06-19 18:41:12 -07001014 };
1015
1016
1017 public FaceService(Context context) {
1018 super(context);
Kevin Chyn4cc49f72019-04-24 13:53:35 -07001019
Kevin Chyn9bc1d492019-06-21 15:31:50 -07001020 mUsageStats = new UsageStats(context);
1021
Kevin Chyndbfbed42019-06-13 17:01:30 -07001022 mNotificationManager = getContext().getSystemService(NotificationManager.class);
1023
Kevin Chyn4cc49f72019-04-24 13:53:35 -07001024 mBiometricPromptIgnoreList = getContext().getResources()
1025 .getIntArray(R.array.config_face_acquire_biometricprompt_ignorelist);
1026 mBiometricPromptIgnoreListVendor = getContext().getResources()
1027 .getIntArray(R.array.config_face_acquire_vendor_biometricprompt_ignorelist);
1028 mKeyguardIgnoreList = getContext().getResources()
1029 .getIntArray(R.array.config_face_acquire_keyguard_ignorelist);
1030 mKeyguardIgnoreListVendor = getContext().getResources()
1031 .getIntArray(R.array.config_face_acquire_vendor_keyguard_ignorelist);
1032 mEnrollIgnoreList = getContext().getResources()
1033 .getIntArray(R.array.config_face_acquire_enroll_ignorelist);
1034 mEnrollIgnoreListVendor = getContext().getResources()
1035 .getIntArray(R.array.config_face_acquire_vendor_enroll_ignorelist);
Kevin Chyna56dff72018-06-19 18:41:12 -07001036 }
1037
1038 @Override
1039 public void onStart() {
Kevin Chyn5a2ff5d2018-08-29 19:07:30 -07001040 super.onStart();
Kevin Chyna56dff72018-06-19 18:41:12 -07001041 publishBinderService(Context.FACE_SERVICE, new FaceServiceWrapper());
Kevin Chyn8398a712019-06-13 16:44:50 -07001042 // Get the face daemon on FaceService's on thread so SystemServerInitThreadPool isn't
1043 // blocked
1044 SystemServerInitThreadPool.get().submit(() -> mHandler.post(this::getFaceDaemon),
1045 TAG + ".onStart");
Kevin Chyna56dff72018-06-19 18:41:12 -07001046 }
1047
1048 @Override
1049 public String getTag() {
1050 return TAG;
1051 }
1052
1053 @Override
Kevin Chyn6737c572019-02-08 16:10:54 -08001054 protected DaemonWrapper getDaemonWrapper() {
1055 return mDaemonWrapper;
1056 }
1057
1058 @Override
Kevin Chyna56dff72018-06-19 18:41:12 -07001059 protected BiometricUtils getBiometricUtils() {
1060 return FaceUtils.getInstance();
1061 }
1062
1063 @Override
Kevin Chyn4cc49f72019-04-24 13:53:35 -07001064 protected Constants getConstants() {
1065 return mFaceConstants;
Kevin Chyna56dff72018-06-19 18:41:12 -07001066 }
1067
1068 @Override
1069 protected boolean hasReachedEnrollmentLimit(int userId) {
1070 final int limit = getContext().getResources().getInteger(
Kevin Chyn017e76e2018-06-27 18:35:06 -07001071 com.android.internal.R.integer.config_faceMaxTemplatesPerUser);
Kevin Chyn6737c572019-02-08 16:10:54 -08001072 final int enrolled = FaceService.this.getEnrolledTemplates(userId).size();
Kevin Chyna56dff72018-06-19 18:41:12 -07001073 if (enrolled >= limit) {
Kevin Chyn1a878c12019-04-04 15:50:11 -07001074 Slog.w(TAG, "Too many faces registered, user: " + userId);
Kevin Chyna56dff72018-06-19 18:41:12 -07001075 return true;
1076 }
1077 return false;
1078 }
1079
1080 @Override
Kevin Chyn9ba99912019-01-16 16:24:36 -08001081 public void serviceDied(long cookie) {
1082 super.serviceDied(cookie);
1083 mDaemon = null;
Jim Miller7b78b222019-02-07 16:47:38 -08001084
1085 mCurrentUserId = UserHandle.USER_NULL; // Force updateActiveGroup() to re-evaluate
Kevin Chyn9ba99912019-01-16 16:24:36 -08001086 }
1087
1088 @Override
Kevin Chyna56dff72018-06-19 18:41:12 -07001089 protected void updateActiveGroup(int userId, String clientPackage) {
1090 IBiometricsFace daemon = getFaceDaemon();
1091
1092 if (daemon != null) {
1093 try {
1094 userId = getUserOrWorkProfileId(clientPackage, userId);
1095 if (userId != mCurrentUserId) {
Kevin Chyn27e33d02019-04-30 01:37:32 +00001096 final File baseDir = Environment.getDataVendorDeDirectory(userId);
Kevin Chyna56dff72018-06-19 18:41:12 -07001097 final File faceDir = new File(baseDir, FACE_DATA_DIR);
1098 if (!faceDir.exists()) {
1099 if (!faceDir.mkdir()) {
1100 Slog.v(TAG, "Cannot make directory: " + faceDir.getAbsolutePath());
1101 return;
1102 }
1103 // Calling mkdir() from this process will create a directory with our
1104 // permissions (inherited from the containing dir). This command fixes
1105 // the label.
1106 if (!SELinux.restorecon(faceDir)) {
1107 Slog.w(TAG, "Restorecons failed. Directory will have wrong label.");
1108 return;
1109 }
1110 }
1111
1112 daemon.setActiveUser(userId, faceDir.getAbsolutePath());
1113 mCurrentUserId = userId;
Kevin Chyn576811e2019-06-12 14:50:35 -07001114 mAuthenticatorIds.put(userId,
1115 hasEnrolledBiometrics(userId) ? daemon.getAuthenticatorId().value : 0L);
Kevin Chyna56dff72018-06-19 18:41:12 -07001116 }
Kevin Chyna56dff72018-06-19 18:41:12 -07001117 } catch (RemoteException e) {
1118 Slog.e(TAG, "Failed to setActiveUser():", e);
1119 }
1120 }
1121 }
1122
1123 @Override
1124 protected String getLockoutResetIntent() {
1125 return ACTION_LOCKOUT_RESET;
1126 }
1127
1128 @Override
1129 protected String getLockoutBroadcastPermission() {
1130 return RESET_FACE_LOCKOUT;
1131 }
1132
1133 @Override
1134 protected long getHalDeviceId() {
1135 return mHalDeviceId;
1136 }
1137
1138 @Override
Kevin Chyna38653c2019-02-11 17:46:21 -08001139 protected void handleUserSwitching(int userId) {
1140 super.handleUserSwitching(userId);
1141 // Will be updated when we get the callback from HAL
1142 mCurrentUserLockoutMode = AuthenticationClient.LOCKOUT_NONE;
1143 }
1144
1145 @Override
Kevin Chyna56dff72018-06-19 18:41:12 -07001146 protected boolean hasEnrolledBiometrics(int userId) {
1147 if (userId != UserHandle.getCallingUserId()) {
1148 checkPermission(INTERACT_ACROSS_USERS);
1149 }
1150 return getBiometricUtils().getBiometricsForUser(getContext(), userId).size() > 0;
1151 }
1152
1153 @Override
1154 protected String getManageBiometricPermission() {
Kevin Chyna24e9fd2018-08-27 12:39:17 -07001155 return MANAGE_BIOMETRIC;
Kevin Chyna56dff72018-06-19 18:41:12 -07001156 }
1157
1158 @Override
1159 protected void checkUseBiometricPermission() {
Kevin Chyna24e9fd2018-08-27 12:39:17 -07001160 // noop for Face. The permission checks are all done on the incoming binder call.
Kevin Chyna56dff72018-06-19 18:41:12 -07001161 }
1162
1163 @Override
Kevin Chynb3c05aa2018-09-21 16:50:32 -07001164 protected boolean checkAppOps(int uid, String opPackageName) {
1165 return mAppOps.noteOp(AppOpsManager.OP_USE_BIOMETRIC, uid, opPackageName)
1166 == AppOpsManager.MODE_ALLOWED;
Kevin Chyna56dff72018-06-19 18:41:12 -07001167 }
1168
1169 @Override
Kevin Chyn6737c572019-02-08 16:10:54 -08001170 protected List<Face> getEnrolledTemplates(int userId) {
1171 return getBiometricUtils().getBiometricsForUser(getContext(), userId);
1172 }
1173
1174 @Override
Kevin Chyna56dff72018-06-19 18:41:12 -07001175 protected void notifyClientActiveCallbacks(boolean isActive) {
1176 // noop for Face.
1177 }
1178
Kevin Chyn7782d142019-01-18 12:51:33 -08001179 @Override
1180 protected int statsModality() {
1181 return BiometricsProtoEnums.MODALITY_FACE;
1182 }
1183
Kevin Chyna38653c2019-02-11 17:46:21 -08001184 @Override
1185 protected int getLockoutMode() {
1186 return mCurrentUserLockoutMode;
1187 }
1188
Kevin Chyna56dff72018-06-19 18:41:12 -07001189 /** Gets the face daemon */
1190 private synchronized IBiometricsFace getFaceDaemon() {
1191 if (mDaemon == null) {
1192 Slog.v(TAG, "mDaemon was null, reconnect to face");
1193 try {
1194 mDaemon = IBiometricsFace.getService();
1195 } catch (java.util.NoSuchElementException e) {
1196 // Service doesn't exist or cannot be opened. Logged below.
1197 } catch (RemoteException e) {
1198 Slog.e(TAG, "Failed to get biometric interface", e);
1199 }
1200 if (mDaemon == null) {
1201 Slog.w(TAG, "face HIDL not available");
1202 return null;
1203 }
1204
1205 mDaemon.asBinder().linkToDeath(this, 0);
1206
1207 try {
1208 mHalDeviceId = mDaemon.setCallback(mDaemonCallback).value;
1209 } catch (RemoteException e) {
1210 Slog.e(TAG, "Failed to open face HAL", e);
1211 mDaemon = null; // try again later!
1212 }
1213
1214 if (DEBUG) Slog.v(TAG, "Face HAL id: " + mHalDeviceId);
1215 if (mHalDeviceId != 0) {
1216 loadAuthenticatorIds();
1217 updateActiveGroup(ActivityManager.getCurrentUser(), null);
Kevin Chyn6737c572019-02-08 16:10:54 -08001218 doTemplateCleanupForUser(ActivityManager.getCurrentUser());
Kevin Chyna56dff72018-06-19 18:41:12 -07001219 } else {
1220 Slog.w(TAG, "Failed to open Face HAL!");
1221 MetricsLogger.count(getContext(), "faced_openhal_error", 1);
1222 mDaemon = null;
1223 }
1224 }
1225 return mDaemon;
1226 }
1227
Kevin Chynd79e24e2018-09-25 12:06:59 -07001228 private long startGenerateChallenge(IBinder token) {
Kevin Chyna56dff72018-06-19 18:41:12 -07001229 IBiometricsFace daemon = getFaceDaemon();
1230 if (daemon == null) {
Kevin Chynd79e24e2018-09-25 12:06:59 -07001231 Slog.w(TAG, "startGenerateChallenge: no face HAL!");
Kevin Chyna56dff72018-06-19 18:41:12 -07001232 return 0;
1233 }
1234 try {
Kevin Chyne46a2162018-09-20 18:43:01 -07001235 return daemon.generateChallenge(CHALLENGE_TIMEOUT_SEC).value;
Kevin Chyna56dff72018-06-19 18:41:12 -07001236 } catch (RemoteException e) {
Kevin Chynd79e24e2018-09-25 12:06:59 -07001237 Slog.e(TAG, "startGenerateChallenge failed", e);
Kevin Chyna56dff72018-06-19 18:41:12 -07001238 }
1239 return 0;
1240 }
1241
Kevin Chynd79e24e2018-09-25 12:06:59 -07001242 private int startRevokeChallenge(IBinder token) {
Kevin Chyna56dff72018-06-19 18:41:12 -07001243 IBiometricsFace daemon = getFaceDaemon();
1244 if (daemon == null) {
Kevin Chynd79e24e2018-09-25 12:06:59 -07001245 Slog.w(TAG, "startRevokeChallenge: no face HAL!");
Kevin Chyna56dff72018-06-19 18:41:12 -07001246 return 0;
1247 }
1248 try {
Kevin Chyn96c92972018-08-31 16:09:31 -07001249 return daemon.revokeChallenge();
Kevin Chyna56dff72018-06-19 18:41:12 -07001250 } catch (RemoteException e) {
Kevin Chynd79e24e2018-09-25 12:06:59 -07001251 Slog.e(TAG, "startRevokeChallenge failed", e);
Kevin Chyna56dff72018-06-19 18:41:12 -07001252 }
1253 return 0;
1254 }
1255
Gilad Brettercb51b8b2018-03-22 17:04:51 +02001256 private void dumpInternal(PrintWriter pw) {
1257 JSONObject dump = new JSONObject();
1258 try {
1259 dump.put("service", "Face Manager");
1260
1261 JSONArray sets = new JSONArray();
1262 for (UserInfo user : UserManager.get(getContext()).getUsers()) {
1263 final int userId = user.getUserHandle().getIdentifier();
Kevin Chyna56dff72018-06-19 18:41:12 -07001264 final int N = getBiometricUtils().getBiometricsForUser(getContext(), userId).size();
Gilad Brettercb51b8b2018-03-22 17:04:51 +02001265 PerformanceStats stats = mPerformanceMap.get(userId);
1266 PerformanceStats cryptoStats = mCryptoPerformanceMap.get(userId);
1267 JSONObject set = new JSONObject();
1268 set.put("id", userId);
Kevin Chyna56dff72018-06-19 18:41:12 -07001269 set.put("count", N);
Gilad Brettercb51b8b2018-03-22 17:04:51 +02001270 set.put("accept", (stats != null) ? stats.accept : 0);
1271 set.put("reject", (stats != null) ? stats.reject : 0);
1272 set.put("acquire", (stats != null) ? stats.acquire : 0);
1273 set.put("lockout", (stats != null) ? stats.lockout : 0);
1274 set.put("permanentLockout", (stats != null) ? stats.permanentLockout : 0);
1275 // cryptoStats measures statistics about secure face transactions
1276 // (e.g. to unlock password storage, make secure purchases, etc.)
1277 set.put("acceptCrypto", (cryptoStats != null) ? cryptoStats.accept : 0);
1278 set.put("rejectCrypto", (cryptoStats != null) ? cryptoStats.reject : 0);
1279 set.put("acquireCrypto", (cryptoStats != null) ? cryptoStats.acquire : 0);
1280 set.put("lockoutCrypto", (cryptoStats != null) ? cryptoStats.lockout : 0);
Kevin Chyna56dff72018-06-19 18:41:12 -07001281 set.put("permanentLockoutCrypto",
1282 (cryptoStats != null) ? cryptoStats.permanentLockout : 0);
Gilad Brettercb51b8b2018-03-22 17:04:51 +02001283 sets.put(set);
1284 }
1285
1286 dump.put("prints", sets);
1287 } catch (JSONException e) {
1288 Slog.e(TAG, "dump formatting failure", e);
1289 }
1290 pw.println(dump);
Kevin Chyn9bc1d492019-06-21 15:31:50 -07001291 pw.println("HAL deaths since last reboot: " + mHALDeathCount);
1292
1293 mUsageStats.print(pw);
Gilad Brettercb51b8b2018-03-22 17:04:51 +02001294 }
1295
Joe Onoratodb396002019-04-05 19:49:27 -07001296 private void dumpHal(FileDescriptor fd, String[] args) {
Joe Onoratobf955d22019-03-25 00:16:58 -07001297 // WARNING: CDD restricts image data from leaving TEE unencrypted on
1298 // production devices:
1299 // [C-1-10] MUST not allow unencrypted access to identifiable biometric
1300 // data or any data derived from it (such as embeddings) to the
1301 // Application Processor outside the context of the TEE.
1302 // As such, this API should only be enabled for testing purposes on
1303 // engineering and userdebug builds. All modules in the software stack
1304 // MUST enforce final build products do NOT have this functionality.
1305 // Additionally, the following check MUST NOT be removed.
1306 if (!(Build.IS_ENG || Build.IS_USERDEBUG)) {
1307 return;
1308 }
1309
Joe Onorato108413a2019-04-03 18:20:52 -07001310 // Additionally, this flag allows turning off face for a device
1311 // (either permanently through the build or on an individual device).
1312 if (SystemProperties.getBoolean("ro.face.disable_debug_data", false)
1313 || SystemProperties.getBoolean("persist.face.disable_debug_data", false)) {
1314 return;
1315 }
1316
Joe Onoratodb396002019-04-05 19:49:27 -07001317 // The debug method takes two file descriptors. The first is for text
1318 // output, which we will drop. The second is for binary data, which
1319 // will be the protobuf data.
1320 final IBiometricsFace daemon = getFaceDaemon();
1321 if (daemon != null) {
1322 FileOutputStream devnull = null;
1323 try {
1324 devnull = new FileOutputStream("/dev/null");
1325 final NativeHandle handle = new NativeHandle(
1326 new FileDescriptor[] { devnull.getFD(), fd },
1327 new int[0], false);
1328 daemon.debug(handle, new ArrayList<String>(Arrays.asList(args)));
1329 } catch (IOException | RemoteException ex) {
1330 Slog.d(TAG, "error while reading face debugging data", ex);
1331 } finally {
1332 if (devnull != null) {
1333 try {
1334 devnull.close();
1335 } catch (IOException ex) {
1336 }
1337 }
1338 }
Joe Onoratobf955d22019-03-25 00:16:58 -07001339 }
Joe Onoratobf955d22019-03-25 00:16:58 -07001340 }
Kevin Chyn8b7a0372018-09-17 15:06:05 -07001341}