blob: d2a29e48b6889a01aaed76aac78cdb1f0c18d6b5 [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;
20import static android.Manifest.permission.MANAGE_FACE;
21import static android.Manifest.permission.RESET_FACE_LOCKOUT;
22import static android.Manifest.permission.USE_BIOMETRIC;
Gilad Brettercb51b8b2018-03-22 17:04:51 +020023
24import android.app.ActivityManager;
Gilad Brettercb51b8b2018-03-22 17:04:51 +020025import android.app.AppOpsManager;
Gilad Brettercb51b8b2018-03-22 17:04:51 +020026import android.content.Context;
Gilad Brettercb51b8b2018-03-22 17:04:51 +020027import android.content.pm.UserInfo;
Kevin Chyna56dff72018-06-19 18:41:12 -070028import android.hardware.biometrics.BiometricAuthenticator;
29import android.hardware.biometrics.BiometricConstants;
30import android.hardware.biometrics.IBiometricPromptReceiver;
31import android.hardware.biometrics.IBiometricServiceLockoutResetCallback;
Gilad Brettercb51b8b2018-03-22 17:04:51 +020032import android.hardware.biometrics.face.V1_0.IBiometricsFace;
33import android.hardware.biometrics.face.V1_0.IBiometricsFaceClientCallback;
34import android.hardware.face.Face;
Gilad Brettercb51b8b2018-03-22 17:04:51 +020035import android.hardware.face.IFaceService;
Gilad Brettercb51b8b2018-03-22 17:04:51 +020036import android.hardware.face.IFaceServiceReceiver;
37import android.os.Binder;
38import android.os.Bundle;
Gilad Brettercb51b8b2018-03-22 17:04:51 +020039import android.os.Environment;
Gilad Brettercb51b8b2018-03-22 17:04:51 +020040import android.os.IBinder;
Gilad Brettercb51b8b2018-03-22 17:04:51 +020041import android.os.RemoteException;
42import android.os.SELinux;
Kevin Chyna56dff72018-06-19 18:41:12 -070043import android.os.ServiceManager;
Gilad Brettercb51b8b2018-03-22 17:04:51 +020044import android.os.UserHandle;
45import android.os.UserManager;
Gilad Brettercb51b8b2018-03-22 17:04:51 +020046import android.util.Slog;
47import android.util.proto.ProtoOutputStream;
48
49import com.android.internal.annotations.GuardedBy;
50import com.android.internal.logging.MetricsLogger;
Kevin Chyna56dff72018-06-19 18:41:12 -070051import com.android.internal.statusbar.IStatusBarService;
Gilad Brettercb51b8b2018-03-22 17:04:51 +020052import com.android.internal.util.DumpUtils;
53import com.android.server.SystemServerInitThreadPool;
Kevin Chyna56dff72018-06-19 18:41:12 -070054import com.android.server.biometrics.common.BiometricService;
55import com.android.server.biometrics.common.BiometricUtils;
56import com.android.server.biometrics.common.Metrics;
Gilad Brettercb51b8b2018-03-22 17:04:51 +020057
58import org.json.JSONArray;
59import org.json.JSONException;
60import org.json.JSONObject;
61
62import java.io.File;
63import java.io.FileDescriptor;
64import java.io.PrintWriter;
65import java.util.ArrayList;
Gilad Brettercb51b8b2018-03-22 17:04:51 +020066import java.util.List;
Gilad Brettercb51b8b2018-03-22 17:04:51 +020067
68/**
69 * A service to manage multiple clients that want to access the face HAL API.
70 * The service is responsible for maintaining a list of clients and dispatching all
71 * face -related events.
72 *
73 * @hide
74 */
Kevin Chyna56dff72018-06-19 18:41:12 -070075public class FaceService extends BiometricService {
76
77 protected static final String TAG = "FaceService";
78 private static final boolean DEBUG = true;
Gilad Brettercb51b8b2018-03-22 17:04:51 +020079 private static final String FACE_DATA_DIR = "facedata";
Gilad Brettercb51b8b2018-03-22 17:04:51 +020080 private static final String ACTION_LOCKOUT_RESET =
Kevin Chyn2ffadb32018-06-19 11:29:38 -070081 "com.android.server.biometrics.face.ACTION_LOCKOUT_RESET";
Kevin Chyna56dff72018-06-19 18:41:12 -070082 private static final int MAX_FAILED_ATTEMPTS_LOCKOUT_TIMED = 3;
83 private static final int MAX_FAILED_ATTEMPTS_LOCKOUT_PERMANENT = 12;
Gilad Brettercb51b8b2018-03-22 17:04:51 +020084
85 /**
Kevin Chyna56dff72018-06-19 18:41:12 -070086 * Receives the incoming binder calls from FaceManager.
Gilad Brettercb51b8b2018-03-22 17:04:51 +020087 */
Gilad Brettercb51b8b2018-03-22 17:04:51 +020088 private final class FaceServiceWrapper extends IFaceService.Stub {
Kevin Chyna56dff72018-06-19 18:41:12 -070089
90 /**
91 * The following methods contain common code which is shared in biometrics/common.
92 */
Gilad Brettercb51b8b2018-03-22 17:04:51 +020093 @Override // Binder call
94 public long preEnroll(IBinder token) {
95 checkPermission(MANAGE_FACE);
96 return startPreEnroll(token);
97 }
98
99 @Override // Binder call
100 public int postEnroll(IBinder token) {
101 checkPermission(MANAGE_FACE);
102 return startPostEnroll(token);
103 }
104
105 @Override // Binder call
106 public void enroll(final IBinder token, final byte[] cryptoToken, final int userId,
107 final IFaceServiceReceiver receiver, final int flags,
108 final String opPackageName) {
109 checkPermission(MANAGE_FACE);
110
Gilad Brettercb51b8b2018-03-22 17:04:51 +0200111 final boolean restricted = isRestricted();
Kevin Chyna56dff72018-06-19 18:41:12 -0700112 final EnrollClientImpl client = new EnrollClientImpl(getContext(), mDaemonWrapper,
113 mHalDeviceId, token, new ServiceListenerImpl(receiver), mCurrentUserId,
114 0 /* groupId */, cryptoToken, restricted, opPackageName);
Gilad Brettercb51b8b2018-03-22 17:04:51 +0200115
Kevin Chyna56dff72018-06-19 18:41:12 -0700116 enrollInternal(client, userId);
Gilad Brettercb51b8b2018-03-22 17:04:51 +0200117 }
118
119 @Override // Binder call
120 public void cancelEnrollment(final IBinder token) {
121 checkPermission(MANAGE_FACE);
Kevin Chyna56dff72018-06-19 18:41:12 -0700122 cancelEnrollmentInternal(token);
Gilad Brettercb51b8b2018-03-22 17:04:51 +0200123 }
124
125 @Override // Binder call
126 public void authenticate(final IBinder token, final long opId,
Kevin Chyna56dff72018-06-19 18:41:12 -0700127 final IFaceServiceReceiver receiver, final int flags,
128 final String opPackageName, final Bundle bundle,
129 final IBiometricPromptReceiver dialogReceiver) {
Gilad Brettercb51b8b2018-03-22 17:04:51 +0200130 final boolean restricted = isRestricted();
Kevin Chyna56dff72018-06-19 18:41:12 -0700131 final AuthenticationClientImpl client = new AuthenticationClientImpl(getContext(),
132 mDaemonWrapper, mHalDeviceId, token, new ServiceListenerImpl(receiver),
133 mCurrentUserId, 0 /* groupId */, opId, restricted, opPackageName, bundle,
134 dialogReceiver, mStatusBarService);
Gilad Brettercb51b8b2018-03-22 17:04:51 +0200135
Kevin Chyna56dff72018-06-19 18:41:12 -0700136 authenticateInternal(client, opId, opPackageName);
Gilad Brettercb51b8b2018-03-22 17:04:51 +0200137 }
138
139 @Override // Binder call
140 public void cancelAuthentication(final IBinder token, final String opPackageName) {
Kevin Chyna56dff72018-06-19 18:41:12 -0700141 cancelAuthenticationInternal(token, opPackageName);
Gilad Brettercb51b8b2018-03-22 17:04:51 +0200142 }
143
144 @Override // Binder call
145 public void setActiveUser(final int userId) {
146 checkPermission(MANAGE_FACE);
Kevin Chyna56dff72018-06-19 18:41:12 -0700147 setActiveUserInternal(userId);
Gilad Brettercb51b8b2018-03-22 17:04:51 +0200148 }
149
150 @Override // Binder call
Kevin Chyna56dff72018-06-19 18:41:12 -0700151 public void remove(final IBinder token, final int faceId, final int userId,
152 final IFaceServiceReceiver receiver) {
153 checkPermission(MANAGE_FACE);
154
155 if (token == null) {
156 Slog.w(TAG, "remove(): token is null");
157 return;
158 }
159
Gilad Brettercb51b8b2018-03-22 17:04:51 +0200160 final boolean restricted = isRestricted();
Kevin Chyna56dff72018-06-19 18:41:12 -0700161 final RemovalClientImpl client = new RemovalClientImpl(getContext(), mDaemonWrapper,
162 mHalDeviceId, token, new ServiceListenerImpl(receiver), faceId, 0 /* groupId */,
163 userId, restricted, token.toString());
164 client.setShouldNotifyUserActivity(true);
165 removeInternal(client);
Gilad Brettercb51b8b2018-03-22 17:04:51 +0200166 }
167
Kevin Chyna56dff72018-06-19 18:41:12 -0700168 @Override
169 public void enumerate(final IBinder token, final int userId,
170 final IFaceServiceReceiver receiver) {
171 checkPermission(MANAGE_FACE);
172
173 final boolean restricted = isRestricted();
174 final EnumerateClientImpl client = new EnumerateClientImpl(getContext(), mDaemonWrapper,
175 mHalDeviceId, token, new ServiceListenerImpl(receiver), userId, userId,
176 restricted, getContext().getOpPackageName());
177 enumerateInternal(client);
178 }
179
180 @Override
181 public void addLockoutResetCallback(final IBiometricServiceLockoutResetCallback callback)
182 throws RemoteException {
183 FaceService.super.addLockoutResetCallback(callback);
184 }
185
186 @Override // Binder call
187 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
188 if (!DumpUtils.checkDumpPermission(getContext(), TAG, pw)) {
189 return;
190 }
191
192 final long ident = Binder.clearCallingIdentity();
193 try {
194 if (args.length > 0 && "--proto".equals(args[0])) {
195 dumpProto(fd);
196 } else {
197 dumpInternal(pw);
198 }
199 } finally {
200 Binder.restoreCallingIdentity(ident);
201 }
202 }
203
204 /**
205 * The following methods don't use any common code from BiometricService
206 */
207
208 // TODO: refactor out common code here
Gilad Brettercb51b8b2018-03-22 17:04:51 +0200209 @Override // Binder call
210 public boolean isHardwareDetected(long deviceId, String opPackageName) {
Kevin Chyna56dff72018-06-19 18:41:12 -0700211 if (!canUseBiometric(opPackageName, false /* foregroundOnly */,
Gilad Brettercb51b8b2018-03-22 17:04:51 +0200212 Binder.getCallingUid(), Binder.getCallingPid(),
213 UserHandle.getCallingUserId())) {
214 return false;
215 }
216
217 final long token = Binder.clearCallingIdentity();
218 try {
219 IBiometricsFace daemon = getFaceDaemon();
220 return daemon != null && mHalDeviceId != 0;
221 } finally {
222 Binder.restoreCallingIdentity(token);
223 }
224 }
225
226 @Override // Binder call
Kevin Chyna56dff72018-06-19 18:41:12 -0700227 public void rename(final int faceId, final String name) {
228 checkPermission(MANAGE_FACE);
229 if (!isCurrentUserOrProfile(UserHandle.getCallingUserId())) {
230 return;
231 }
232 mHandler.post(new Runnable() {
233 @Override
234 public void run() {
235 getBiometricUtils().renameBiometricForUser(getContext(), mCurrentUserId,
236 faceId, name);
237 }
238 });
239 }
240
241 @Override // Binder call
242 public List<Face> getEnrolledFaces(int userId, String opPackageName) {
243 if (!canUseBiometric(opPackageName, false /* foregroundOnly */,
Gilad Brettercb51b8b2018-03-22 17:04:51 +0200244 Binder.getCallingUid(), Binder.getCallingPid(),
245 UserHandle.getCallingUserId())) {
246 return null;
247 }
248
Kevin Chyna56dff72018-06-19 18:41:12 -0700249 return FaceService.this.getEnrolledFaces(userId);
Gilad Brettercb51b8b2018-03-22 17:04:51 +0200250 }
251
252 @Override // Binder call
Kevin Chyna56dff72018-06-19 18:41:12 -0700253 public boolean hasEnrolledFaces(int userId, String opPackageName) {
254 if (!canUseBiometric(opPackageName, false /* foregroundOnly */,
Gilad Brettercb51b8b2018-03-22 17:04:51 +0200255 Binder.getCallingUid(), Binder.getCallingPid(),
256 UserHandle.getCallingUserId())) {
257 return false;
258 }
259
Kevin Chyna56dff72018-06-19 18:41:12 -0700260 return FaceService.this.hasEnrolledBiometrics(userId);
Gilad Brettercb51b8b2018-03-22 17:04:51 +0200261 }
262
263 @Override // Binder call
264 public long getAuthenticatorId(String opPackageName) {
265 // In this method, we're not checking whether the caller is permitted to use face
266 // API because current authenticator ID is leaked (in a more contrived way) via Android
267 // Keystore (android.security.keystore package): the user of that API can create a key
268 // which requires face authentication for its use, and then query the key's
269 // characteristics (hidden API) which returns, among other things, face
270 // authenticator ID which was active at key creation time.
271 //
272 // Reason: The part of Android Keystore which runs inside an app's process invokes this
273 // method in certain cases. Those cases are not always where the developer demonstrates
274 // explicit intent to use face functionality. Thus, to avoiding throwing an
275 // unexpected SecurityException this method does not check whether its caller is
276 // permitted to use face API.
277 //
278 // The permission check should be restored once Android Keystore no longer invokes this
279 // method from inside app processes.
280
281 return FaceService.this.getAuthenticatorId(opPackageName);
282 }
283
284 @Override // Binder call
Kevin Chyna56dff72018-06-19 18:41:12 -0700285 public void resetTimeout(byte[] token) {
Gilad Brettercb51b8b2018-03-22 17:04:51 +0200286 checkPermission(RESET_FACE_LOCKOUT);
287 // TODO: confirm security token when we move timeout management into the HAL layer.
Kevin Chyna56dff72018-06-19 18:41:12 -0700288 mHandler.post(mResetFailedAttemptsForCurrentUserRunnable);
289 }
290 }
291
292 /**
293 * Receives callbacks from the ClientMonitor implementations. The results are forwarded to
294 * the FaceManager.
295 */
296 private class ServiceListenerImpl implements ServiceListener {
297
298 private IFaceServiceReceiver mFaceServiceReceiver;
299
300 public ServiceListenerImpl(IFaceServiceReceiver receiver) {
301 mFaceServiceReceiver = receiver;
Gilad Brettercb51b8b2018-03-22 17:04:51 +0200302 }
303
304 @Override
Kevin Chyna56dff72018-06-19 18:41:12 -0700305 public void onEnrollResult(BiometricAuthenticator.Identifier identifier, int remaining)
Gilad Brettercb51b8b2018-03-22 17:04:51 +0200306 throws RemoteException {
Kevin Chyna56dff72018-06-19 18:41:12 -0700307 if (mFaceServiceReceiver != null) {
308 mFaceServiceReceiver.onEnrollResult(identifier.getDeviceId(),
309 identifier.getBiometricId(),
310 remaining);
311 }
Gilad Brettercb51b8b2018-03-22 17:04:51 +0200312 }
Kevin Chyna56dff72018-06-19 18:41:12 -0700313
314 @Override
315 public void onAcquired(long deviceId, int acquiredInfo, int vendorCode)
316 throws RemoteException {
317 if (mFaceServiceReceiver != null) {
318 mFaceServiceReceiver.onAcquired(deviceId, acquiredInfo, vendorCode);
319 }
320 }
321
322 @Override
323 public void onAuthenticationSucceeded(long deviceId,
324 BiometricAuthenticator.Identifier biometric, int userId)
325 throws RemoteException {
326 if (mFaceServiceReceiver != null) {
327 if (biometric instanceof Face) {
328 mFaceServiceReceiver.onAuthenticationSucceeded(deviceId, (Face)biometric);
329 } else {
330 Slog.e(TAG, "onAuthenticationSucceeded received non-face biometric");
331 }
332 }
333 }
334
335 @Override
336 public void onAuthenticationFailed(long deviceId) throws RemoteException {
337 if (mFaceServiceReceiver != null) {
338 mFaceServiceReceiver.onAuthenticationFailed(deviceId);
339 }
340 }
341
342 @Override
343 public void onError(long deviceId, int error, int vendorCode) throws RemoteException {
344 if (mFaceServiceReceiver != null) {
345 mFaceServiceReceiver.onError(deviceId, error, vendorCode);
346 }
347 }
348
349 @Override
350 public void onRemoved(BiometricAuthenticator.Identifier identifier,
351 int remaining) throws RemoteException {
352 if (mFaceServiceReceiver != null) {
353 mFaceServiceReceiver.onRemoved(identifier.getDeviceId(),
354 identifier.getBiometricId(), remaining);
355 }
356 }
357
358 @Override
359 public void onEnumerated(BiometricAuthenticator.Identifier identifier, int remaining)
360 throws RemoteException {
361 if (mFaceServiceReceiver != null) {
362
363 }
364 }
365 }
366
367 private final FaceMetrics mFaceMetrics = new FaceMetrics();
368
369 @GuardedBy("this")
370 private IBiometricsFace mDaemon;
371
372 private long mHalDeviceId;
373 private IStatusBarService mStatusBarService;
374
375 /**
376 * Receives callbacks from the HAL.
377 */
378 private IBiometricsFaceClientCallback mDaemonCallback =
379 new IBiometricsFaceClientCallback.Stub() {
380 @Override
381 public void onEnrollResult(final long deviceId, int faceId, int userId,
382 int remaining) {
383 mHandler.post(() -> {
384 final Face face = new Face(getBiometricUtils()
385 .getUniqueName(getContext(), userId), faceId, deviceId);
386 FaceService.super.handleEnrollResult(face, remaining);
387 });
388 }
389
390 @Override
391 public void onAcquired(final long deviceId, final int userId,
392 final int acquiredInfo,
393 final int vendorCode) {
394 mHandler.post(() -> {
395 FaceService.super.handleAcquired(deviceId, acquiredInfo, vendorCode);
396 });
397 }
398
399 @Override
400 public void onAuthenticated(final long deviceId, final int faceId, final int userId,
401 ArrayList<Byte> token) {
402 mHandler.post(() -> {
403 FaceService.super.handleAuthenticated(deviceId, faceId, userId, token);
404 });
405 }
406
407 @Override
408 public void onError(final long deviceId, final int userId, final int error,
409 final int vendorCode) {
410 mHandler.post(() -> {
411 FaceService.super.handleError(deviceId, error, vendorCode);
412
413 // TODO: this chunk of code should be common to all biometric services
414 if (error == BiometricConstants.BIOMETRIC_ERROR_HW_UNAVAILABLE) {
415 // If we get HW_UNAVAILABLE, try to connect again later...
416 Slog.w(TAG, "Got ERROR_HW_UNAVAILABLE; try reconnecting next client.");
417 synchronized (this) {
418 mDaemon = null;
419 mHalDeviceId = 0;
420 mCurrentUserId = UserHandle.USER_NULL;
421 }
422 }
423 });
424 }
425
426 @Override
427 public void onRemoved(final long deviceId, final int faceId, final int userId,
428 final int remaining) {
429 mHandler.post(() -> {
430 final Face face = new Face("", faceId, deviceId);
431 FaceService.super.handleRemoved(face, remaining);
432 });
433 }
434
435 @Override
436 public void onEnumerate(long deviceId, ArrayList<Integer> faceIds, int userId)
437 throws RemoteException {
438 // TODO
439 }
440 };
441
442 /**
443 * Wraps the HAL-specific code and is passed to the ClientMonitor implementations so that they
444 * can be shared between the multiple biometric services.
445 */
446 private final DaemonWrapper mDaemonWrapper = new DaemonWrapper() {
447 @Override
448 public int authenticate(long operationId, int groupId) throws RemoteException {
449 IBiometricsFace daemon = getFaceDaemon();
450 if (daemon == null) {
451 Slog.w(TAG, "authenticate(): no face HAL!");
452 return ERROR_ESRCH;
453 }
454 return daemon.authenticate(operationId);
455 }
456
457 @Override
458 public int cancel() throws RemoteException {
459 IBiometricsFace daemon = getFaceDaemon();
460 if (daemon == null) {
461 Slog.w(TAG, "cancel(): no face HAL!");
462 return ERROR_ESRCH;
463 }
464 return daemon.cancel();
465 }
466
467 @Override
468 public int remove(int groupId, int biometricId) throws RemoteException {
469 IBiometricsFace daemon = getFaceDaemon();
470 if (daemon == null) {
471 Slog.w(TAG, "remove(): no face HAL!");
472 return ERROR_ESRCH;
473 }
474 return daemon.remove(biometricId);
475 }
476
477 @Override
478 public int enumerate() throws RemoteException {
479 IBiometricsFace daemon = getFaceDaemon();
480 if (daemon == null) {
481 Slog.w(TAG, "enumerate(): no face HAL!");
482 return ERROR_ESRCH;
483 }
484 return daemon.enumerate();
485 }
486
487 @Override
488 public int enroll(byte[] cryptoToken, int groupId, int timeout) throws RemoteException {
489 IBiometricsFace daemon = getFaceDaemon();
490 if (daemon == null) {
491 Slog.w(TAG, "enroll(): no face HAL!");
492 return ERROR_ESRCH;
493 }
494 final ArrayList<Byte> token = new ArrayList<>();
495 for (int i = 0; i < cryptoToken.length; i++) {
496 token.add(cryptoToken[i]);
497 }
498 return daemon.enroll(token, timeout);
499 }
500 };
501
502
503 public FaceService(Context context) {
504 super(context);
505 // TODO: can this be retrieved from AuthenticationClient, or BiometricService?
506 mStatusBarService = IStatusBarService.Stub.asInterface(
507 ServiceManager.getService(Context.STATUS_BAR_SERVICE));
508 }
509
510 @Override
511 public void onStart() {
512 publishBinderService(Context.FACE_SERVICE, new FaceServiceWrapper());
513 SystemServerInitThreadPool.get().submit(this::getFaceDaemon, TAG + ".onStart");
514 }
515
516 @Override
517 public String getTag() {
518 return TAG;
519 }
520
521 @Override
522 protected BiometricUtils getBiometricUtils() {
523 return FaceUtils.getInstance();
524 }
525
526 @Override
527 protected int getFailedAttemptsLockoutTimed() {
528 return MAX_FAILED_ATTEMPTS_LOCKOUT_TIMED;
529 }
530
531 @Override
532 protected int getFailedAttemptsLockoutPermanent() {
533 return MAX_FAILED_ATTEMPTS_LOCKOUT_PERMANENT;
534 }
535
536 @Override
537 protected Metrics getMetrics() {
538 return mFaceMetrics;
539 }
540
541 @Override
542 protected boolean hasReachedEnrollmentLimit(int userId) {
543 final int limit = getContext().getResources().getInteger(
544 com.android.internal.R.integer.config_face_MaxTemplatesPerUser);
545 final int enrolled = FaceService.this.getEnrolledFaces(userId).size();
546 if (enrolled >= limit) {
547 Slog.w(TAG, "Too many faces registered");
548 return true;
549 }
550 return false;
551 }
552
553 @Override
554 protected void updateActiveGroup(int userId, String clientPackage) {
555 IBiometricsFace daemon = getFaceDaemon();
556
557 if (daemon != null) {
558 try {
559 userId = getUserOrWorkProfileId(clientPackage, userId);
560 if (userId != mCurrentUserId) {
561 final File baseDir = Environment.getDataVendorDeDirectory(userId);
562 final File faceDir = new File(baseDir, FACE_DATA_DIR);
563 if (!faceDir.exists()) {
564 if (!faceDir.mkdir()) {
565 Slog.v(TAG, "Cannot make directory: " + faceDir.getAbsolutePath());
566 return;
567 }
568 // Calling mkdir() from this process will create a directory with our
569 // permissions (inherited from the containing dir). This command fixes
570 // the label.
571 if (!SELinux.restorecon(faceDir)) {
572 Slog.w(TAG, "Restorecons failed. Directory will have wrong label.");
573 return;
574 }
575 }
576
577 daemon.setActiveUser(userId, faceDir.getAbsolutePath());
578 mCurrentUserId = userId;
579 }
580 mAuthenticatorIds.put(userId,
581 hasEnrolledBiometrics(userId) ? daemon.getAuthenticatorId().value : 0L);
582 } catch (RemoteException e) {
583 Slog.e(TAG, "Failed to setActiveUser():", e);
584 }
585 }
586 }
587
588 @Override
589 protected String getLockoutResetIntent() {
590 return ACTION_LOCKOUT_RESET;
591 }
592
593 @Override
594 protected String getLockoutBroadcastPermission() {
595 return RESET_FACE_LOCKOUT;
596 }
597
598 @Override
599 protected long getHalDeviceId() {
600 return mHalDeviceId;
601 }
602
603 @Override
604 protected void handleUserSwitching(int userId) {
605 updateActiveGroup(userId, null);
606 }
607
608 @Override
609 protected boolean hasEnrolledBiometrics(int userId) {
610 if (userId != UserHandle.getCallingUserId()) {
611 checkPermission(INTERACT_ACROSS_USERS);
612 }
613 return getBiometricUtils().getBiometricsForUser(getContext(), userId).size() > 0;
614 }
615
616 @Override
617 protected String getManageBiometricPermission() {
618 return MANAGE_FACE;
619 }
620
621 @Override
622 protected void checkUseBiometricPermission() {
623 checkPermission(USE_BIOMETRIC);
624 }
625
626 @Override
627 protected int getAppOp() {
628 return AppOpsManager.OP_USE_FACE;
629 }
630
631 @Override
632 protected void notifyClientActiveCallbacks(boolean isActive) {
633 // noop for Face.
634 }
635
636 /** Gets the face daemon */
637 private synchronized IBiometricsFace getFaceDaemon() {
638 if (mDaemon == null) {
639 Slog.v(TAG, "mDaemon was null, reconnect to face");
640 try {
641 mDaemon = IBiometricsFace.getService();
642 } catch (java.util.NoSuchElementException e) {
643 // Service doesn't exist or cannot be opened. Logged below.
644 } catch (RemoteException e) {
645 Slog.e(TAG, "Failed to get biometric interface", e);
646 }
647 if (mDaemon == null) {
648 Slog.w(TAG, "face HIDL not available");
649 return null;
650 }
651
652 mDaemon.asBinder().linkToDeath(this, 0);
653
654 try {
655 mHalDeviceId = mDaemon.setCallback(mDaemonCallback).value;
656 } catch (RemoteException e) {
657 Slog.e(TAG, "Failed to open face HAL", e);
658 mDaemon = null; // try again later!
659 }
660
661 if (DEBUG) Slog.v(TAG, "Face HAL id: " + mHalDeviceId);
662 if (mHalDeviceId != 0) {
663 loadAuthenticatorIds();
664 updateActiveGroup(ActivityManager.getCurrentUser(), null);
665 } else {
666 Slog.w(TAG, "Failed to open Face HAL!");
667 MetricsLogger.count(getContext(), "faced_openhal_error", 1);
668 mDaemon = null;
669 }
670 }
671 return mDaemon;
672 }
673
674 private long startPreEnroll(IBinder token) {
675 IBiometricsFace daemon = getFaceDaemon();
676 if (daemon == null) {
677 Slog.w(TAG, "startPreEnroll: no face HAL!");
678 return 0;
679 }
680 try {
681 return daemon.preEnroll().value;
682 } catch (RemoteException e) {
683 Slog.e(TAG, "startPreEnroll failed", e);
684 }
685 return 0;
686 }
687
688 private int startPostEnroll(IBinder token) {
689 IBiometricsFace daemon = getFaceDaemon();
690 if (daemon == null) {
691 Slog.w(TAG, "startPostEnroll: no face HAL!");
692 return 0;
693 }
694 try {
695 return daemon.postEnroll();
696 } catch (RemoteException e) {
697 Slog.e(TAG, "startPostEnroll failed", e);
698 }
699 return 0;
700 }
701
702 private List<Face> getEnrolledFaces(int userId) {
703 return getBiometricUtils().getBiometricsForUser(getContext(), userId);
Gilad Brettercb51b8b2018-03-22 17:04:51 +0200704 }
705
706 private void dumpInternal(PrintWriter pw) {
707 JSONObject dump = new JSONObject();
708 try {
709 dump.put("service", "Face Manager");
710
711 JSONArray sets = new JSONArray();
712 for (UserInfo user : UserManager.get(getContext()).getUsers()) {
713 final int userId = user.getUserHandle().getIdentifier();
Kevin Chyna56dff72018-06-19 18:41:12 -0700714 final int N = getBiometricUtils().getBiometricsForUser(getContext(), userId).size();
Gilad Brettercb51b8b2018-03-22 17:04:51 +0200715 PerformanceStats stats = mPerformanceMap.get(userId);
716 PerformanceStats cryptoStats = mCryptoPerformanceMap.get(userId);
717 JSONObject set = new JSONObject();
718 set.put("id", userId);
Kevin Chyna56dff72018-06-19 18:41:12 -0700719 set.put("count", N);
Gilad Brettercb51b8b2018-03-22 17:04:51 +0200720 set.put("accept", (stats != null) ? stats.accept : 0);
721 set.put("reject", (stats != null) ? stats.reject : 0);
722 set.put("acquire", (stats != null) ? stats.acquire : 0);
723 set.put("lockout", (stats != null) ? stats.lockout : 0);
724 set.put("permanentLockout", (stats != null) ? stats.permanentLockout : 0);
725 // cryptoStats measures statistics about secure face transactions
726 // (e.g. to unlock password storage, make secure purchases, etc.)
727 set.put("acceptCrypto", (cryptoStats != null) ? cryptoStats.accept : 0);
728 set.put("rejectCrypto", (cryptoStats != null) ? cryptoStats.reject : 0);
729 set.put("acquireCrypto", (cryptoStats != null) ? cryptoStats.acquire : 0);
730 set.put("lockoutCrypto", (cryptoStats != null) ? cryptoStats.lockout : 0);
Kevin Chyna56dff72018-06-19 18:41:12 -0700731 set.put("permanentLockoutCrypto",
732 (cryptoStats != null) ? cryptoStats.permanentLockout : 0);
Gilad Brettercb51b8b2018-03-22 17:04:51 +0200733 sets.put(set);
734 }
735
736 dump.put("prints", sets);
737 } catch (JSONException e) {
738 Slog.e(TAG, "dump formatting failure", e);
739 }
740 pw.println(dump);
741 }
742
743 private void dumpProto(FileDescriptor fd) {
744 final ProtoOutputStream proto = new ProtoOutputStream(fd);
745 for (UserInfo user : UserManager.get(getContext()).getUsers()) {
746 final int userId = user.getUserHandle().getIdentifier();
747
748 final long userToken = proto.start(FaceServiceDumpProto.USERS);
749
750 proto.write(FaceUserStatsProto.USER_ID, userId);
Kevin Chyna56dff72018-06-19 18:41:12 -0700751 proto.write(FaceUserStatsProto.NUM_FACES,
752 getBiometricUtils().getBiometricsForUser(getContext(), userId).size());
Gilad Brettercb51b8b2018-03-22 17:04:51 +0200753
754 // Normal face authentications (e.g. lockscreen)
755 final PerformanceStats normal = mPerformanceMap.get(userId);
756 if (normal != null) {
757 final long countsToken = proto.start(FaceUserStatsProto.NORMAL);
758 proto.write(FaceActionStatsProto.ACCEPT, normal.accept);
759 proto.write(FaceActionStatsProto.REJECT, normal.reject);
760 proto.write(FaceActionStatsProto.ACQUIRE, normal.acquire);
761 proto.write(FaceActionStatsProto.LOCKOUT, normal.lockout);
762 proto.write(FaceActionStatsProto.LOCKOUT_PERMANENT, normal.lockout);
763 proto.end(countsToken);
764 }
765
766 // Statistics about secure face transactions (e.g. to unlock password
767 // storage, make secure purchases, etc.)
768 final PerformanceStats crypto = mCryptoPerformanceMap.get(userId);
769 if (crypto != null) {
770 final long countsToken = proto.start(FaceUserStatsProto.CRYPTO);
771 proto.write(FaceActionStatsProto.ACCEPT, crypto.accept);
772 proto.write(FaceActionStatsProto.REJECT, crypto.reject);
773 proto.write(FaceActionStatsProto.ACQUIRE, crypto.acquire);
774 proto.write(FaceActionStatsProto.LOCKOUT, crypto.lockout);
775 proto.write(FaceActionStatsProto.LOCKOUT_PERMANENT, crypto.lockout);
776 proto.end(countsToken);
777 }
778
779 proto.end(userToken);
780 }
781 proto.flush();
Kevin Chyna56dff72018-06-19 18:41:12 -0700782 mPerformanceMap.clear();
783 mCryptoPerformanceMap.clear();
Gilad Brettercb51b8b2018-03-22 17:04:51 +0200784 }
Kevin Chyna56dff72018-06-19 18:41:12 -0700785}