Advertisement
xosski

Android biometric logger for whatever

Jan 10th, 2025
11
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 83.11 KB | None | 0 0
  1. // Core service implementation with improvements
  2. public class BiometricService extends SystemService {
  3. private static final String TAG = "BiometricService";
  4.  
  5. // Use concurrent collections for thread safety
  6. private final ConcurrentHashMap<Integer, BiometricSensor> sensorMap = new ConcurrentHashMap<>();
  7. private final AtomicReference<AuthSession> currentSession = new AtomicReference<>();
  8. private final BiometricMetricsCollector metricsCollector;
  9. private final SecurityLogger securityLogger;
  10. private final BiometricCache biometricCache;
  11.  
  12. // Enhanced constructor with dependency injection
  13. public BiometricService(Context context, Injector injector) {
  14. super(context);
  15. this.metricsCollector = new BiometricMetricsCollector();
  16. this.securityLogger = new SecurityLogger();
  17. this.biometricCache = new BiometricCache();
  18. initializeSensors();
  19. }
  20.  
  21. // Structured sensor initialization
  22. private void initializeSensors() {
  23. registerSensor(new FingerprintSensor());
  24. registerSensor(new FaceSensor());
  25. registerSensor(new IrisSensor());
  26. }
  27.  
  28. // Enhanced authentication flow
  29. public void authenticate(AuthenticationRequest request) {
  30. securityLogger.logAuthAttempt(request);
  31.  
  32. // Validate request
  33. validateRequest(request);
  34.  
  35. // Create new session
  36. AuthSession session = AuthSession.builder()
  37. .withRequest(request)
  38. .withSensors(sensorMap.values())
  39. .withMetrics(metricsCollector)
  40. .build();
  41.  
  42. currentSession.set(session);
  43.  
  44. // Start authentication
  45. session.start();
  46. }
  47.  
  48. // Improved sensor management
  49. private void registerSensor(BiometricSensor sensor) {
  50. sensorMap.put(sensor.getId(), sensor);
  51. metricsCollector.trackSensor(sensor);
  52. }
  53.  
  54. // Enhanced security validation
  55. private void validateRequest(AuthenticationRequest request) {
  56. if (!isValidRequest(request)) {
  57. throw new BiometricSecurityException("Invalid authentication request");
  58. }
  59. }
  60.  
  61. // Robust error handling
  62. private class BiometricSecurityException extends RuntimeException {
  63. private final SecurityEvent event;
  64.  
  65. BiometricSecurityException(String message) {
  66. super(message);
  67. this.event = new SecurityEvent();
  68. securityLogger.logSecurityException(this);
  69. }
  70. }
  71.  
  72. // Metrics collection
  73. private class BiometricMetricsCollector {
  74. private final ConcurrentHashMap<Integer, SensorMetrics> metrics = new ConcurrentHashMap<>();
  75.  
  76. void trackAuthentication(AuthenticationEvent event) {
  77. metrics.get(event.getSensorId()).track(event);
  78. }
  79.  
  80. MetricsReport generateReport() {
  81. return new MetricsReport(metrics.values());
  82. }
  83. }
  84.  
  85. // Security logging
  86. private class SecurityLogger {
  87. private static final int MAX_LOG_SIZE = 1000;
  88. private final Queue<SecurityEvent> eventLog = new CircularFifoQueue<>(MAX_LOG_SIZE);
  89.  
  90. void logSecurityEvent(SecurityEvent event) {
  91. eventLog.offer(event);
  92. if (event.isCritical()) {
  93. notifySecurityAdmin(event);
  94. }
  95. }
  96. }
  97.  
  98. // Cache management
  99. private class BiometricCache {
  100. private final LoadingCache<Integer, BiometricData> cache;
  101.  
  102. BiometricCache() {
  103. cache = CacheBuilder.newBuilder()
  104. .maximumSize(100)
  105. .expireAfterWrite(30, TimeUnit.MINUTES)
  106. .build(new BiometricCacheLoader());
  107. }
  108. }
  109.  
  110. // Enhanced testing support
  111. @VisibleForTesting
  112. void setTestMode(boolean enabled) {
  113. metricsCollector.setTestMode(enabled);
  114. securityLogger.setTestMode(enabled);
  115. }
  116. }
  117.  
  118. // Supporting classes
  119. class AuthenticationRequest {
  120. private final int userId;
  121. private final int sensorId;
  122. private final byte[] challenge;
  123. private final AuthenticationCallback callback;
  124.  
  125. // Builder pattern implementation
  126. public static class Builder {
  127. // Builder methods
  128. }
  129. }
  130.  
  131. class AuthSession {
  132. private final AuthenticationRequest request;
  133. private final Collection<BiometricSensor> sensors;
  134. private final BiometricMetricsCollector metrics;
  135.  
  136. public static Builder builder() {
  137. return new Builder();
  138. }
  139.  
  140. void start() {
  141. // Authentication logic
  142. }
  143.  
  144. // Builder implementation
  145. }
  146.  
  147. interface BiometricSensor {
  148. int getId();
  149. void authenticate(AuthenticationRequest request);
  150. boolean isAvailable();
  151. }
  152.  
  153. class SecurityEvent {
  154. private final long timestamp;
  155. private final String type;
  156. private final Map<String, String> data;
  157.  
  158. boolean isCritical() {
  159. return type.startsWith("CRITICAL_");
  160. }
  161. }
  162. // Core service implementation with improvements
  163. public class BiometricService extends SystemService {
  164. private static final String TAG = "BiometricService";
  165.  
  166. // Use concurrent collections for thread safety
  167. private final ConcurrentHashMap<Integer, BiometricSensor> sensorMap = new ConcurrentHashMap<>();
  168. private final AtomicReference<AuthSession> currentSession = new AtomicReference<>();
  169. private final BiometricMetricsCollector metricsCollector;
  170. private final SecurityLogger securityLogger;
  171. private final BiometricCache biometricCache;
  172.  
  173. // Enhanced constructor with dependency injection
  174. public BiometricService(Context context, Injector injector) {
  175. super(context);
  176. this.metricsCollector = new BiometricMetricsCollector();
  177. this.securityLogger = new SecurityLogger();
  178. this.biometricCache = new BiometricCache();
  179. initializeSensors();
  180. }
  181.  
  182. // Structured sensor initialization
  183. private void initializeSensors() {
  184. registerSensor(new FingerprintSensor());
  185. registerSensor(new FaceSensor());
  186. registerSensor(new IrisSensor());
  187. }
  188.  
  189. // Enhanced authentication flow
  190. public void authenticate(AuthenticationRequest request) {
  191. securityLogger.logAuthAttempt(request);
  192.  
  193. // Validate request
  194. validateRequest(request);
  195.  
  196. // Create new session
  197. AuthSession session = AuthSession.builder()
  198. .withRequest(request)
  199. .withSensors(sensorMap.values())
  200. .withMetrics(metricsCollector)
  201. .build();
  202.  
  203. currentSession.set(session);
  204.  
  205. // Start authentication
  206. session.start();
  207. }
  208.  
  209. // Improved sensor management
  210. private void registerSensor(BiometricSensor sensor) {
  211. sensorMap.put(sensor.getId(), sensor);
  212. metricsCollector.trackSensor(sensor);
  213. }
  214.  
  215. // Enhanced security validation
  216. private void validateRequest(AuthenticationRequest request) {
  217. if (!isValidRequest(request)) {
  218. throw new BiometricSecurityException("Invalid authentication request");
  219. }
  220. }
  221.  
  222. // Robust error handling
  223. private class BiometricSecurityException extends RuntimeException {
  224. private final SecurityEvent event;
  225.  
  226. BiometricSecurityException(String message) {
  227. super(message);
  228. this.event = new SecurityEvent();
  229. securityLogger.logSecurityException(this);
  230. }
  231. }
  232.  
  233. // Metrics collection
  234. private class BiometricMetricsCollector {
  235. private final ConcurrentHashMap<Integer, SensorMetrics> metrics = new ConcurrentHashMap<>();
  236.  
  237. void trackAuthentication(AuthenticationEvent event) {
  238. metrics.get(event.getSensorId()).track(event);
  239. }
  240.  
  241. MetricsReport generateReport() {
  242. return new MetricsReport(metrics.values());
  243. }
  244. }
  245.  
  246. // Security logging
  247. private class SecurityLogger {
  248. private static final int MAX_LOG_SIZE = 1000;
  249. private final Queue<SecurityEvent> eventLog = new CircularFifoQueue<>(MAX_LOG_SIZE);
  250.  
  251. void logSecurityEvent(SecurityEvent event) {
  252. eventLog.offer(event);
  253. if (event.isCritical()) {
  254. notifySecurityAdmin(event);
  255. }
  256. }
  257. }
  258.  
  259. // Cache management
  260. private class BiometricCache {
  261. private final LoadingCache<Integer, BiometricData> cache;
  262.  
  263. BiometricCache() {
  264. cache = CacheBuilder.newBuilder()
  265. .maximumSize(100)
  266. .expireAfterWrite(30, TimeUnit.MINUTES)
  267. .build(new BiometricCacheLoader());
  268. }
  269. }
  270.  
  271. // Enhanced testing support
  272. @VisibleForTesting
  273. void setTestMode(boolean enabled) {
  274. metricsCollector.setTestMode(enabled);
  275. securityLogger.setTestMode(enabled);
  276. }
  277. }
  278.  
  279. // Supporting classes
  280. class AuthenticationRequest {
  281. private final int userId;
  282. private final int sensorId;
  283. private final byte[] challenge;
  284. private final AuthenticationCallback callback;
  285.  
  286. // Builder pattern implementation
  287. public static class Builder {
  288. // Builder methods
  289. }
  290. }
  291.  
  292. class AuthSession {
  293. private final AuthenticationRequest request;
  294. private final Collection<BiometricSensor> sensors;
  295. private final BiometricMetricsCollector metrics;
  296.  
  297. public static Builder builder() {
  298. return new Builder();
  299. }
  300.  
  301. void start() {
  302. // Authentication logic
  303. }
  304.  
  305. // Builder implementation
  306. }
  307.  
  308. interface BiometricSensor {
  309. int getId();
  310. void authenticate(AuthenticationRequest request);
  311. boolean isAvailable();
  312. }
  313.  
  314. class SecurityEvent {
  315. private final long timestamp;
  316. private final String type;
  317. private final Map<String, String> data;
  318.  
  319. boolean isCritical() {
  320. return type.startsWith("CRITICAL_");
  321. }
  322. }
  323. package com.android.server.biometrics;
  324.  
  325. import static android.Manifest.permission.USE_BIOMETRIC_INTERNAL;
  326. import static android.hardware.biometrics.BiometricAuthenticator.TYPE_FACE;
  327. import static android.hardware.biometrics.BiometricAuthenticator.TYPE_FINGERPRINT;
  328. import static android.hardware.biometrics.BiometricManager.Authenticators;
  329. import static android.hardware.biometrics.BiometricManager.BIOMETRIC_NO_AUTHENTICATION;
  330. import static android.hardware.biometrics.SensorProperties.STRENGTH_STRONG;
  331. import static com.android.server.biometrics.BiometricServiceStateProto.STATE_AUTH_IDLE;
  332.  
  333. import android.annotation.NonNull;
  334. import android.annotation.Nullable;
  335. import android.app.ActivityManager;
  336. import android.app.IActivityManager;
  337. import android.app.UserSwitchObserver;
  338. import android.app.admin.DevicePolicyManager;
  339. import android.app.trust.ITrustManager;
  340. import android.content.ComponentName;
  341. import android.content.ContentResolver;
  342. import android.content.Context;
  343. import android.content.pm.PackageManager;
  344. import android.content.pm.UserInfo;
  345. import android.database.ContentObserver;
  346. import android.hardware.SensorPrivacyManager;
  347. import android.hardware.biometrics.BiometricAuthenticator;
  348. import android.hardware.biometrics.BiometricConstants;
  349. import android.hardware.biometrics.BiometricPrompt;
  350. import android.hardware.biometrics.BiometricStateListener;
  351. import android.hardware.biometrics.Flags;
  352. import android.hardware.biometrics.IBiometricAuthenticator;
  353. import android.hardware.biometrics.IBiometricEnabledOnKeyguardCallback;
  354. import android.hardware.biometrics.IBiometricSensorReceiver;
  355. import android.hardware.biometrics.IBiometricService;
  356. import android.hardware.biometrics.IBiometricServiceReceiver;
  357. import android.hardware.biometrics.IBiometricSysuiReceiver;
  358. import android.hardware.biometrics.IInvalidationCallback;
  359. import android.hardware.biometrics.ITestSession;
  360. import android.hardware.biometrics.ITestSessionCallback;
  361. import android.hardware.biometrics.PromptInfo;
  362. import android.hardware.biometrics.SensorPropertiesInternal;
  363. import android.hardware.camera2.CameraManager;
  364. import android.hardware.face.FaceManager;
  365. import android.hardware.face.FaceSensorPropertiesInternal;
  366. import android.hardware.face.IFaceAuthenticatorsRegisteredCallback;
  367. import android.hardware.fingerprint.FingerprintManager;
  368. import android.hardware.fingerprint.FingerprintSensorPropertiesInternal;
  369. import android.hardware.fingerprint.IFingerprintAuthenticatorsRegisteredCallback;
  370. import android.hardware.security.keymint.HardwareAuthenticatorType;
  371. import android.net.Uri;
  372. import android.os.Binder;
  373. import android.os.Build;
  374. import android.os.DeadObjectException;
  375. import android.os.Handler;
  376. import android.os.IBinder;
  377. import android.os.RemoteException;
  378. import android.os.ServiceManager;
  379. import android.os.UserHandle;
  380. import android.os.UserManager;
  381. import android.provider.Settings;
  382. import android.security.GateKeeper;
  383. import android.security.KeyStoreAuthorization;
  384. import android.service.gatekeeper.IGateKeeperService;
  385. import android.text.TextUtils;
  386. import android.util.ArraySet;
  387. import android.util.Pair;
  388. import android.util.Slog;
  389. import android.util.proto.ProtoOutputStream;
  390. import com.android.internal.R;
  391. import com.android.internal.annotations.VisibleForTesting;
  392. import com.android.internal.os.SomeArgs;
  393. import com.android.internal.statusbar.IStatusBarService;
  394. import com.android.internal.util.DumpUtils;
  395. import com.android.server.SystemService;
  396. import com.android.server.biometrics.log.BiometricContext;
  397. import com.android.server.utils.Slogf;
  398.  
  399. import java.io.FileDescriptor;
  400. import java.io.PrintWriter;
  401. import java.util.ArrayList;
  402. import java.util.HashMap;
  403. import java.util.HashSet;
  404. import java.util.List;
  405. import java.util.Map;
  406. import java.util.Random;
  407. import java.util.Set;
  408. import java.util.concurrent.atomic.AtomicLong;
  409. import java.util.concurrent.CopyOnWriteArrayList;
  410. import java.util.function.Supplier;
  411.  
  412. /**
  413. * System service that arbitrates the modality for BiometricPrompt to use.
  414. */
  415. public class BiometricService extends SystemService {
  416. static final String TAG = "BiometricService";
  417. private final Injector mInjector;
  418. private final DevicePolicyManager mDevicePolicyManager;
  419. @VisibleForTesting
  420. final IBiometricService.Stub mImpl;
  421. @VisibleForTesting
  422. final SettingObserver mSettingObserver;
  423. private final List<EnabledOnKeyguardCallback> mEnabledOnKeyguardCallbacks;
  424. private final Random mRandom = new Random();
  425. @NonNull private final Supplier<Long> mRequestCounter;
  426. @NonNull private final BiometricContext mBiometricContext;
  427. private final UserManager mUserManager;
  428. @VisibleForTesting
  429. IStatusBarService mStatusBarService;
  430. @VisibleForTesting
  431. ITrustManager mTrustManager;
  432. @VisibleForTesting
  433. KeyStoreAuthorization mKeyStoreAuthorization;
  434. @VisibleForTesting
  435. IGateKeeperService mGateKeeper;
  436. // Get and cache the available biometric authenticators and their associated info.
  437. final CopyOnWriteArrayList<BiometricSensor> mSensors = new CopyOnWriteArrayList<>();
  438. // Set to keep track of registered authenticator IDs
  439. private final Set<Integer> mRegisteredAuthenticatorIds = new HashSet<>();
  440. @VisibleForTesting
  441. BiometricStrengthController mBiometricStrengthController;
  442. // The current authentication session, null if idle/done.
  443. @VisibleForTesting
  444. AuthSession mAuthSession;
  445. private final Handler mHandler;
  446. private final BiometricCameraManager mBiometricCameraManager;
  447. private final BiometricNotificationLogger mBiometricNotificationLogger;
  448.  
  449. /**
  450. * Tracks authenticatorId invalidation. For more details, see
  451. * {@link com.android.server.biometrics.sensors.InvalidationRequesterClient}.
  452. */
  453. @VisibleForTesting
  454. static class InvalidationTracker {
  455. @NonNull private final IInvalidationCallback mClientCallback;
  456. @NonNull private final Set<Integer> mSensorsPendingInvalidation;
  457.  
  458. public static InvalidationTracker start(@NonNull Context context,
  459. @NonNull List<BiometricSensor> sensors, int userId,
  460. int fromSensorId, @NonNull IInvalidationCallback clientCallback) {
  461. return new InvalidationTracker(context, sensors, userId, fromSensorId, clientCallback);
  462. }
  463.  
  464. private InvalidationTracker(@NonNull Context context,
  465. @NonNull List<BiometricSensor> sensors, int userId,
  466. int fromSensorId, @NonNull IInvalidationCallback clientCallback) {
  467. mClientCallback = clientCallback;
  468. mSensorsPendingInvalidation = new ArraySet<>();
  469. for (BiometricSensor sensor : sensors) {
  470. if (sensor.id == fromSensorId) {
  471. continue;
  472. }
  473. if (!Utils.isAtLeastStrength(sensor.oemStrength, Authenticators.BIOMETRIC_STRONG)) {
  474. continue;
  475. }
  476. try {
  477. if (!sensor.impl.hasEnrolledTemplates(userId, context.getOpPackageName())) {
  478. continue;
  479. }
  480. } catch (RemoteException e) {
  481. Slog.e(TAG, "Remote Exception", e);
  482. }
  483. Slog.d(TAG, "Requesting authenticatorId invalidation for sensor: " + sensor.id);
  484. synchronized (this) {
  485. mSensorsPendingInvalidation.add(sensor.id);
  486. }
  487. try {
  488. sensor.impl.invalidateAuthenticatorId(userId, new IInvalidationCallback.Stub() {
  489. @Override
  490. public void onCompleted() {
  491. onInvalidated(sensor.id);
  492. }
  493. });
  494. } catch (RemoteException e) {
  495. Slog.d(TAG, "RemoteException", e);
  496. }
  497. }
  498. synchronized (this) {
  499. if (mSensorsPendingInvalidation.isEmpty()) {
  500. try {
  501. Slog.d(TAG, "No sensors require invalidation");
  502. mClientCallback.onCompleted();
  503. } catch (RemoteException e) {
  504. Slog.e(TAG, "Remote Exception", e);
  505. }
  506. }
  507. }
  508. }
  509.  
  510. @VisibleForTesting
  511. void onInvalidated(int sensorId) {
  512. synchronized (this) {
  513. mSensorsPendingInvalidation.remove(sensorId);
  514. Slog.d(TAG, "Sensor " + sensorId + " invalidated, remaining size: "
  515. + mSensorsPendingInvalidation.size());
  516. if (mSensorsPendingInvalidation.isEmpty()) {
  517. try {
  518. mClientCallback.onCompleted();
  519. } catch (RemoteException e) {
  520. Slog.e(TAG, "Remote Exception", e);
  521. }
  522. }
  523. }
  524. }
  525. }
  526.  
  527. @VisibleForTesting
  528. public static class SettingObserver extends ContentObserver {
  529. private static final boolean DEFAULT_KEYGUARD_ENABLED = true;
  530. private static final boolean DEFAULT_APP_ENABLED = true;
  531. private static final boolean DEFAULT_ALWAYS_REQUIRE_CONFIRMATION = false;
  532. private static final boolean DEFAULT_MANDATORY_BIOMETRICS_STATUS = false;
  533. private static final boolean DEFAULT_MANDATORY_BIOMETRICS_REQUIREMENTS_SATISFIED_STATUS = true;
  534. // Some devices that shipped before S already have face-specific settings. Instead of
  535. // migrating, which is complicated, let's just keep using the existing settings.
  536. private final boolean mUseLegacyFaceOnlySettings;
  537. // Only used for legacy face-only devices
  538. private final Uri FACE_UNLOCK_KEYGUARD_ENABLED =
  539. Settings.Secure.getUriFor(Settings.Secure.FACE_UNLOCK_KEYGUARD_ENABLED);
  540. private final Uri FACE_UNLOCK_APP_ENABLED =
  541. Settings.Secure.getUriFor(Settings.Secure.FACE_UNLOCK_APP_ENABLED);
  542. // Continues to be used, even though it's face-specific.
  543. private final Uri FACE_UNLOCK_ALWAYS_REQUIRE_CONFIRMATION =
  544. Settings.Secure.getUriFor(Settings.Secure.FACE_UNLOCK_ALWAYS_REQUIRE_CONFIRMATION);
  545. // Used for all devices other than legacy face-only devices
  546. private final Uri BIOMETRIC_KEYGUARD_ENABLED =
  547. Settings.Secure.getUriFor(Settings.Secure.BIOMETRIC_KEYGUARD_ENABLED);
  548. private final Uri BIOMETRIC_APP_ENABLED =
  549. Settings.Secure.getUriFor(Settings.Secure.BIOMETRIC_APP_ENABLED);
  550. private final Uri MANDATORY_BIOMETRICS_ENABLED =
  551. Settings.Secure.getUriFor(Settings.Secure.MANDATORY_BIOMETRICS);
  552. private final Uri MANDATORY_BIOMETRICS_REQUIREMENTS_SATISFIED = Settings.Secure.getUriFor(
  553. Settings.Secure.MANDATORY_BIOMETRICS_REQUIREMENTS_SATISFIED);
  554. private final ContentResolver mContentResolver;
  555. private final List<BiometricService.EnabledOnKeyguardCallback> mCallbacks;
  556. private final UserManager mUserManager;
  557. private final Map<Integer, Boolean> mBiometricEnabledOnKeyguard = new HashMap<>();
  558. private final Map<Integer, Boolean> mBiometricEnabledForApps = new HashMap<>();
  559. private final Map<Integer, Boolean> mFaceAlwaysRequireConfirmation = new HashMap<>();
  560. private final Map<Integer, Boolean> mMandatoryBiometricsEnabled = new HashMap<>();
  561. private final Map<Integer, Boolean> mMandatoryBiometricsRequirementsSatisfied =
  562. new HashMap<>();
  563. private final Map<Integer, Boolean> mFingerprintEnrolledForUser =
  564. new HashMap<>();
  565. private final Map<Integer, Boolean> mFaceEnrolledForUser =
  566. new HashMap<>();
  567.  
  568. /**
  569. * Creates a content observer.
  570. *
  571. * @param handler The handler to run {@link #onChange} on, or null if none.
  572. */
  573. public SettingObserver(Context context, Handler handler,
  574. List<BiometricService.EnabledOnKeyguardCallback> callbacks) {
  575. super(handler);
  576. mContentResolver = context.getContentResolver();
  577. mCallbacks = callbacks;
  578. mUserManager = context.getSystemService(UserManager.class);
  579. final boolean hasFingerprint = context.getPackageManager()
  580. .hasSystemFeature(PackageManager.FEATURE_FINGERPRINT);
  581. final boolean hasFace = context.getPackageManager()
  582. .hasSystemFeature(PackageManager.FEATURE_FACE);
  583. // Use the legacy setting on face-only devices that shipped on or before Q
  584. mUseLegacyFaceOnlySettings =
  585. Build.VERSION.DEVICE_INITIAL_SDK_INT <= Build.VERSION_CODES.Q
  586. && hasFace && !hasFingerprint;
  587. addBiometricListenersForMandatoryBiometrics(context);
  588. updateContentObserver();
  589. }
  590.  
  591. public void updateContentObserver() {
  592. mContentResolver.unregisterContentObserver(this);
  593. if (mUseLegacyFaceOnlySettings) {
  594. mContentResolver.registerContentObserver(FACE_UNLOCK_KEYGUARD_ENABLED,
  595. false /* notifyForDescendants */,
  596. this /* observer */,
  597. UserHandle.USER_ALL);
  598. mContentResolver.registerContentObserver(FACE_UNLOCK_APP_ENABLED,
  599. false /* notifyForDescendants */,
  600. this /* observer */,
  601. UserHandle.USER_ALL);
  602. } else {
  603. mContentResolver.registerContentObserver(BIOMETRIC_KEYGUARD_ENABLED,
  604. false /* notifyForDescendants */,
  605. this /* observer */,
  606. UserHandle.USER_ALL);
  607. mContentResolver.registerContentObserver(BIOMETRIC_APP_ENABLED,
  608. false /* notifyForDescendants */,
  609. this /* observer */,
  610. UserHandle.USER_ALL);
  611. }
  612. mContentResolver.registerContentObserver(FACE_UNLOCK_ALWAYS_REQUIRE_CONFIRMATION,
  613. false /* notifyForDescendants */,
  614. this /* observer */,
  615. UserHandle.USER_ALL);
  616. mContentResolver.registerContentObserver(MANDATORY_BIOMETRICS_ENABLED,
  617. false /* notifyForDescendants */,
  618. this /* observer */,
  619. UserHandle.USER_ALL);
  620. mContentResolver.registerContentObserver(MANDATORY_BIOMETRICS_REQUIREMENTS_SATISFIED,
  621. false /* notifyForDescendants */,
  622. this /* observer */,
  623. UserHandle.USER_ALL);
  624. }
  625.  
  626. @Override
  627. public void onChange(boolean selfChange, Uri uri, int userId) {
  628. if (FACE_UNLOCK_KEYGUARD_ENABLED.equals(uri)) {
  629. mBiometricEnabledOnKeyguard.put(userId, Settings.Secure.getIntForUser(
  630. mContentResolver,
  631. Settings.Secure.FACE_UNLOCK_KEYGUARD_ENABLED,
  632. DEFAULT_KEYGUARD_ENABLED ? 1 : 0 /* default */,
  633. userId) != 0);
  634. if (userId == ActivityManager.getCurrentUser() && !selfChange) {
  635. notifyEnabledOnKeyguardCallbacks(userId);
  636. }
  637. } else if (FACE_UNLOCK_APP_ENABLED.equals(uri)) {
  638. mBiometricEnabledForApps.put(userId, Settings.Secure.getIntForUser(
  639. mContentResolver,
  640. Settings.Secure.FACE_UNLOCK_APP_ENABLED,
  641. DEFAULT_APP_ENABLED ? 1 : 0 /* default */,
  642. userId) != 0);
  643. } else if (FACE_UNLOCK_ALWAYS_REQUIRE_CONFIRMATION.equals(uri)) {
  644. mFaceAlwaysRequireConfirmation.put(userId, Settings.Secure.getIntForUser(
  645. mContentResolver,
  646. Settings.Secure.FACE_UNLOCK_ALWAYS_REQUIRE_CONFIRMATION,
  647. DEFAULT_ALWAYS_REQUIRE_CONFIRMATION ? 1 : 0 /* default */,
  648. userId) != 0);
  649. } else if (BIOMETRIC_KEYGUARD_ENABLED.equals(uri)) {
  650. mBiometricEnabledOnKeyguard.put(userId, Settings.Secure.getIntForUser(
  651. mContentResolver,
  652. Settings.Secure.BIOMETRIC_KEYGUARD_ENABLED,
  653. DEFAULT_KEYGUARD_ENABLED ? 1 : 0 /* default */,
  654. userId) != 0);
  655. if (userId == ActivityManager.getCurrentUser() && !selfChange) {
  656. notifyEnabledOnKeyguardCallbacks(userId);
  657. }
  658. } else if (BIOMETRIC_APP_ENABLED.equals(uri)) {
  659. mBiometricEnabledForApps.put(userId, Settings.Secure.getIntForUser(
  660. mContentResolver,
  661. Settings.Secure.BIOMETRIC_APP_ENABLED,
  662. DEFAULT_APP_ENABLED ? 1 : 0 /* default */,
  663. userId) != 0);
  664. } else if (MANDATORY_BIOMETRICS_ENABLED.equals(uri)) {
  665. updateMandatoryBiometricsForAllProfiles(userId);
  666. } else if (MANDATORY_BIOMETRICS_REQUIREMENTS_SATISFIED.equals(uri)) {
  667. updateMandatoryBiometricsRequirementsForAllProfiles(userId);
  668. }
  669. }
  670.  
  671. public boolean getEnabledOnKeyguard(int userId) {
  672. if (!mBiometricEnabledOnKeyguard.containsKey(userId)) {
  673. if (mUseLegacyFaceOnlySettings) {
  674. onChange(true /* selfChange */, FACE_UNLOCK_KEYGUARD_ENABLED, userId);
  675. } else {
  676. onChange(true /* selfChange */, BIOMETRIC_KEYGUARD_ENABLED, userId);
  677. }
  678. }
  679. return mBiometricEnabledOnKeyguard.get(userId);
  680. }
  681.  
  682. public boolean getEnabledForApps(int userId) {
  683. if (!mBiometricEnabledForApps.containsKey(userId)) {
  684. if (mUseLegacyFaceOnlySettings) {
  685. onChange(true /* selfChange */, FACE_UNLOCK_APP_ENABLED, userId);
  686. } else {
  687. onChange(true /* selfChange */, BIOMETRIC_APP_ENABLED, userId);
  688. }
  689. }
  690. return mBiometricEnabledForApps.getOrDefault(userId, DEFAULT_APP_ENABLED);
  691. }
  692.  
  693. public boolean getConfirmationAlwaysRequired(@BiometricAuthenticator.Modality int modality,
  694. int userId) {
  695. switch (modality) {
  696. case TYPE_FACE:
  697. if (!mFaceAlwaysRequireConfirmation.containsKey(userId)) {
  698. onChange(true /* selfChange */,
  699. FACE_UNLOCK_ALWAYS_REQUIRE_CONFIRMATION,
  700. userId);
  701. }
  702. return mFaceAlwaysRequireConfirmation.get(userId);
  703. default:
  704. return false;
  705. }
  706. }
  707.  
  708. public boolean getMandatoryBiometricsEnabledAndRequirementsSatisfiedForUser(int userId) {
  709. if (!mMandatoryBiometricsEnabled.containsKey(userId)) {
  710. updateMandatoryBiometricsForAllProfiles(userId);
  711. }
  712. if (!mMandatoryBiometricsRequirementsSatisfied.containsKey(userId)) {
  713. updateMandatoryBiometricsRequirementsForAllProfiles(userId);
  714. }
  715. return mMandatoryBiometricsEnabled.getOrDefault(userId,
  716. DEFAULT_MANDATORY_BIOMETRICS_STATUS)
  717. && mMandatoryBiometricsRequirementsSatisfied.getOrDefault(userId,
  718. DEFAULT_MANDATORY_BIOMETRICS_REQUIREMENTS_SATISFIED_STATUS)
  719. && getEnabledForApps(userId)
  720. && (mFingerprintEnrolledForUser.getOrDefault(userId, false /* default */)
  721. || mFaceEnrolledForUser.getOrDefault(userId, false /* default */));
  722. }
  723.  
  724. void notifyEnabledOnKeyguardCallbacks(int userId) {
  725. List<EnabledOnKeyguardCallback> callbacks = mCallbacks;
  726. for (int i = 0; i < callbacks.size(); i++) {
  727. callbacks.get(i).notify(
  728. mBiometricEnabledOnKeyguard.getOrDefault(userId, DEFAULT_KEYGUARD_ENABLED),
  729. userId);
  730. }
  731. }
  732.  
  733. private void updateMandatoryBiometricsForAllProfiles(int userId) {
  734. int effectiveUserId = userId;
  735. if (mUserManager.getMainUser() != null) {
  736. effectiveUserId = mUserManager.getMainUser().getIdentifier();
  737. }
  738. for (int profileUserId: mUserManager.getEnabledProfileIds(effectiveUserId)) {
  739. mMandatoryBiometricsEnabled.put(profileUserId,
  740. Settings.Secure.getIntForUser(
  741. mContentResolver, Settings.Secure.MANDATORY_BIOMETRICS,
  742. DEFAULT_MANDATORY_BIOMETRICS_STATUS ? 1 : 0,
  743. effectiveUserId) != 0);
  744. }
  745. }
  746.  
  747. private void updateMandatoryBiometricsRequirementsForAllProfiles(int userId) {
  748. int effectiveUserId = userId;
  749. if (mUserManager.getMainUser() != null) {
  750. effectiveUserId = mUserManager.getMainUser().getIdentifier();
  751. }
  752. for (int profileUserId: mUserManager.getEnabledProfileIds(effectiveUserId)) {
  753. mMandatoryBiometricsRequirementsSatisfied.put(profileUserId,
  754. Settings.Secure.getIntForUser(mContentResolver,
  755. Settings.Secure.MANDATORY_BIOMETRICS_REQUIREMENTS_SATISFIED,
  756. DEFAULT_MANDATORY_BIOMETRICS_REQUIREMENTS_SATISFIED_STATUS ? 1 : 0,
  757. effectiveUserId) != 0);
  758. }
  759. }
  760.  
  761. private void addBiometricListenersForMandatoryBiometrics(Context context) {
  762. final FingerprintManager fingerprintManager = context.getSystemService(
  763. FingerprintManager.class);
  764. final FaceManager faceManager = context.getSystemService(FaceManager.class);
  765. if (fingerprintManager != null) {
  766. fingerprintManager.addAuthenticatorsRegisteredCallback(
  767. new IFingerprintAuthenticatorsRegisteredCallback.Stub() {
  768. @Override
  769. public void onAllAuthenticatorsRegistered(
  770. List<FingerprintSensorPropertiesInternal> list) {
  771. if (list == null || list.isEmpty()) {
  772. Slog.d(TAG, "No fingerprint authenticators registered.");
  773. return;
  774. }
  775. final FingerprintSensorPropertiesInternal
  776. fingerprintSensorProperties = list.get(0);
  777. if (fingerprintSensorProperties.sensorStrength
  778. == STRENGTH_STRONG) {
  779. fingerprintManager.registerBiometricStateListener(
  780. new BiometricStateListener() {
  781. @Override
  782. public void onEnrollmentsChanged(
  783. int userId,
  784. int sensorId,
  785. boolean hasEnrollments
  786. ) {
  787. if (sensorId == fingerprintSensorProperties
  788. .sensorId) {
  789. mFingerprintEnrolledForUser.put(userId,
  790. hasEnrollments);
  791. }
  792. }
  793. });
  794. }
  795. }
  796. });
  797. }
  798. if (faceManager != null) {
  799. faceManager.addAuthenticatorsRegisteredCallback(
  800. new IFaceAuthenticatorsRegisteredCallback.Stub() {
  801. @Override
  802. public void onAllAuthenticatorsRegistered(
  803. List<FaceSensorPropertiesInternal> list) {
  804. if (list == null || list.isEmpty()) {
  805. Slog.d(TAG, "No face authenticators registered.");
  806. return;
  807. }
  808. final FaceSensorPropertiesInternal
  809. faceSensorPropertiesInternal = list.get(0);
  810. if (faceSensorPropertiesInternal.sensorStrength
  811. == STRENGTH_STRONG) {
  812. faceManager.registerBiometricStateListener(
  813. new BiometricStateListener() {
  814. @Override
  815. public void onEnrollmentsChanged(
  816. int userId,
  817. int sensorId,
  818. boolean hasEnrollments
  819. ) {
  820. if (sensorId
  821. == faceSensorPropertiesInternal
  822. .sensorId) {
  823. mFaceEnrolledForUser.put(userId,
  824. hasEnrollments);
  825. }
  826. }
  827. });
  828. }
  829. }
  830. });
  831. }
  832. }
  833. }
  834.  
  835. final class EnabledOnKeyguardCallback implements IBinder.DeathRecipient {
  836. private final IBiometricEnabledOnKeyguardCallback mCallback;
  837.  
  838. EnabledOnKeyguardCallback(IBiometricEnabledOnKeyguardCallback callback) {
  839. mCallback = callback;
  840. try {
  841. mCallback.asBinder().linkToDeath(EnabledOnKeyguardCallback.this, 0);
  842. } catch (RemoteException e) {
  843. Slog.w(TAG, "Unable to linkToDeath", e);
  844. }
  845. }
  846.  
  847. void notify(boolean enabled, int userId) {
  848. try {
  849. mCallback.onChanged(enabled, userId);
  850. } catch (DeadObjectException e) {
  851. Slog.w(TAG, "Death while invoking notify", e);
  852. mEnabledOnKeyguardCallbacks.remove(this);
  853. } catch (RemoteException e) {
  854. Slog.w(TAG, "Failed to invoke onChanged", e);
  855. }
  856. }
  857.  
  858. @Override
  859. public void binderDied() {
  860. Slog.e(TAG, "Enabled callback binder died");
  861. mEnabledOnKeyguardCallbacks.remove(this);
  862. }
  863. }
  864.  
  865. // Receives events from individual biometric sensors.
  866. private IBiometricSensorReceiver createBiometricSensorReceiver(final long requestId) {
  867. return new IBiometricSensorReceiver.Stub() {
  868. @Override
  869. public void onAuthenticationSucceeded(int sensorId, byte[] token) {
  870. mHandler.post(() -> handleAuthenticationSucceeded(requestId, sensorId, token));
  871. }
  872.  
  873. @Override
  874. public void onAuthenticationFailed(int sensorId) {
  875. Slog.v(TAG, "onAuthenticationFailed");
  876. mHandler.post(() -> handleAuthenticationRejected(requestId, sensorId));
  877. }
  878.  
  879. @Override
  880. public void onError(int sensorId, int cookie, @BiometricConstants.Errors int error,
  881. int vendorCode) {
  882. // Determine if error is hard or soft error. Certain errors (such as TIMEOUT) are
  883. // soft errors and we should allow the user to try authenticating again instead of
  884. // dismissing BiometricPrompt.
  885. if (error == BiometricConstants.BIOMETRIC_ERROR_TIMEOUT) {
  886. mHandler.post(() -> handleAuthenticationTimedOut(
  887. requestId, sensorId, cookie, error, vendorCode));
  888. } else {
  889. mHandler.post(() -> handleOnError(
  890. requestId, sensorId, cookie, error, vendorCode));
  891. }
  892. }
  893.  
  894. @Override
  895. public void onAcquired(int sensorId, int acquiredInfo, int vendorCode) {
  896. mHandler.post(() -> handleOnAcquired(
  897. requestId, sensorId, acquiredInfo, vendorCode));
  898. }
  899. };
  900. }
  901.  
  902. private IBiometricSysuiReceiver createSysuiReceiver(final long requestId) {
  903. return new IBiometricSysuiReceiver.Stub() {
  904. @Override
  905. public void onDialogDismissed(@BiometricPrompt.DismissedReason int reason,
  906. @Nullable byte[] credentialAttestation) {
  907. mHandler.post(() -> handleOnDismissed(requestId, reason, credentialAttestation));
  908. }
  909.  
  910. @Override
  911. public void onTryAgainPressed() {
  912. mHandler.post(() -> handleOnTryAgainPressed(requestId));
  913. }
  914.  
  915. @Override
  916. public void onDeviceCredentialPressed() {
  917. mHandler.post(() -> handleOnDeviceCredentialPressed(requestId));
  918. }
  919.  
  920. @Override
  921. public void onSystemEvent(int event) {
  922. mHandler.post(() -> handleOnSystemEvent(requestId, event));
  923. }
  924.  
  925. @Override
  926. public void onDialogAnimatedIn(boolean startFingerprintNow) {
  927. mHandler.post(() -> handleOnDialogAnimatedIn(requestId, startFingerprintNow));
  928. }
  929.  
  930. @Override
  931. public void onStartFingerprintNow() {
  932. mHandler.post(() -> handleOnStartFingerprintNow(requestId));
  933. }
  934. };
  935. }
  936.  
  937. private AuthSession.ClientDeathReceiver createClientDeathReceiver(final long requestId) {
  938. return () -> mHandler.post(() -> handleClientDied(requestId));
  939. };
  940.  
  941. /**
  942. * Implementation of the BiometricPrompt/BiometricManager APIs. Handles client requests,
  943. * sensor arbitration, threading, etc.
  944. */
  945. private final class BiometricServiceWrapper extends IBiometricService.Stub {
  946. @android.annotation.EnforcePermission(android.Manifest.permission.USE_BIOMETRIC_INTERNAL)
  947. @Override // Binder call
  948. public ITestSession createTestSession(int sensorId, @NonNull ITestSessionCallback callback,
  949. @NonNull String opPackageName) throws RemoteException {
  950. super.createTestSession_enforcePermission();
  951. for (BiometricSensor sensor : mSensors) {
  952. if (sensor.id == sensorId) {
  953. return sensor.impl.createTestSession(callback, opPackageName);
  954. }
  955. }
  956. Slog.e(TAG, "Unknown sensor for createTestSession: " + sensorId);
  957. return null;
  958. }
  959.  
  960. @android.annotation.EnforcePermission(android.Manifest.permission.USE_BIOMETRIC_INTERNAL)
  961. @Override // Binder call
  962. public List<SensorPropertiesInternal> getSensorProperties(String opPackageName)
  963. throws RemoteException {
  964. super.getSensorProperties_enforcePermission();
  965. final List<SensorPropertiesInternal> sensors = new ArrayList<>();
  966. for (BiometricSensor sensor : mSensors) {
  967. // Explicitly re-create as the super class, since AIDL doesn't play nicely with
  968. // "List<? extends SensorPropertiesInternal> ...
  969. final SensorPropertiesInternal prop = SensorPropertiesInternal
  970. .from(sensor.impl.getSensorProperties(opPackageName));
  971. sensors.add(prop);
  972. }
  973. return sensors;
  974. }
  975.  
  976. @android.annotation.EnforcePermission(android.Manifest.permission.USE_BIOMETRIC_INTERNAL)
  977. @Override // Binder call
  978. public void onReadyForAuthentication(long requestId, int cookie) {
  979. super.onReadyForAuthentication_enforcePermission();
  980. mHandler.post(() -> handleOnReadyForAuthentication(requestId, cookie));
  981. }
  982.  
  983. @android.annotation.EnforcePermission(android.Manifest.permission.USE_BIOMETRIC_INTERNAL)
  984. @Override // Binder call
  985. public long authenticate(IBinder token, long operationId, int userId,
  986. IBiometricServiceReceiver receiver, String opPackageName, PromptInfo promptInfo) {
  987. super.authenticate_enforcePermission();
  988. if (token == null || receiver == null || opPackageName == null || promptInfo == null) {
  989. Slog.e(TAG, "Unable to authenticate, one or more null arguments");
  990. return -1;
  991. }
  992. if (!Utils.isValidAuthenticatorConfig(getContext(), promptInfo)) {
  993. throw new SecurityException("Invalid authenticator configuration");
  994. }
  995. Utils.combineAuthenticatorBundles(promptInfo);
  996. final long requestId = mRequestCounter.get();
  997. mHandler.post(() -> handleAuthenticate(
  998. token, requestId, operationId, userId, receiver, opPackageName, promptInfo));
  999. return requestId;
  1000. }
  1001.  
  1002. @android.annotation.EnforcePermission(android.Manifest.permission.USE_BIOMETRIC_INTERNAL)
  1003. @Override // Binder call
  1004. public void cancelAuthentication(IBinder token, String opPackageName, long requestId) {
  1005. super.cancelAuthentication_enforcePermission();
  1006. SomeArgs args = SomeArgs.obtain();
  1007. args.arg1 = token;
  1008. args.arg2 = opPackageName;
  1009. args.arg3 = requestId;
  1010. mHandler.post(() -> handleCancelAuthentication(requestId));
  1011. }
  1012.  
  1013. @android.annotation.EnforcePermission(android.Manifest.permission.USE_BIOMETRIC_INTERNAL)
  1014. @Override // Binder call
  1015. public int canAuthenticate(String opPackageName, int userId, int callingUserId,
  1016. @Authenticators.Types int authenticators) {
  1017. super.canAuthenticate_enforcePermission();
  1018. Slog.d(TAG, "canAuthenticate: User=" + userId
  1019. + ", Caller=" + callingUserId
  1020. + ", Authenticators=" + authenticators);
  1021. if (!Utils.isValidAuthenticatorConfig(getContext(), authenticators)) {
  1022. throw new SecurityException("Invalid authenticator configuration");
  1023. }
  1024. try {
  1025. final PreAuthInfo preAuthInfo =
  1026. createPreAuthInfo(opPackageName, userId, authenticators);
  1027. return preAuthInfo.getCanAuthenticateResult();
  1028. } catch (RemoteException e) {
  1029. Slog.e(TAG, "Remote exception", e);
  1030. return BiometricConstants.BIOMETRIC_ERROR_HW_UNAVAILABLE;
  1031. }
  1032. }
  1033.  
  1034. @android.annotation.EnforcePermission(android.Manifest.permission.USE_BIOMETRIC_INTERNAL)
  1035. @Override // Binder call
  1036. public long getLastAuthenticationTime(
  1037. int userId, @Authenticators.Types int authenticators) {
  1038. super.getLastAuthenticationTime_enforcePermission();
  1039. if (!Flags.lastAuthenticationTime()) {
  1040. throw new UnsupportedOperationException();
  1041. }
  1042. Slogf.d(TAG, "getLastAuthenticationTime(userId=%d, authenticators=0x%x)",
  1043. userId, authenticators);
  1044. final long secureUserId;
  1045. try {
  1046. secureUserId = mGateKeeper.getSecureUserId(userId);
  1047. } catch (RemoteException e) {
  1048. Slogf.w(TAG, "Failed to get secure user id for " + userId, e);
  1049. return BIOMETRIC_NO_AUTHENTICATION;
  1050. }
  1051. if (secureUserId == GateKeeper.INVALID_SECURE_USER_ID) {
  1052. Slogf.w(TAG, "No secure user id for " + userId);
  1053. return BIOMETRIC_NO_AUTHENTICATION;
  1054. }
  1055. ArrayList<Integer> hardwareAuthenticators = new ArrayList<>(2);
  1056. if ((authenticators & Authenticators.DEVICE_CREDENTIAL) != 0) {
  1057. hardwareAuthenticators.add(HardwareAuthenticatorType.PASSWORD);
  1058. }
  1059. if ((authenticators & Authenticators.BIOMETRIC_STRONG) != 0) {
  1060. hardwareAuthenticators.add(HardwareAuthenticatorType.FINGERPRINT);
  1061. }
  1062. if (hardwareAuthenticators.isEmpty()) {
  1063. throw new IllegalArgumentException("authenticators must not be empty");
  1064. }
  1065. int[] authTypesArray = hardwareAuthenticators.stream()
  1066. .mapToInt(Integer::intValue)
  1067. .toArray();
  1068. return mKeyStoreAuthorization.getLastAuthTime(secureUserId, authTypesArray);
  1069. }
  1070.  
  1071. @android.annotation.EnforcePermission(android.Manifest.permission.USE_BIOMETRIC_INTERNAL)
  1072. @Override
  1073. public boolean hasEnrolledBiometrics(int userId, String opPackageName) {
  1074. super.hasEnrolledBiometrics_enforcePermission();
  1075. try {
  1076. for (BiometricSensor sensor : mSensors) {
  1077. if (sensor.impl.hasEnrolledTemplates(userId, opPackageName)) {
  1078. return true;
  1079. }
  1080. }
  1081. } catch (RemoteException e) {
  1082. Slog.e(TAG, "Remote exception", e);
  1083. }
  1084. return false;
  1085. }
  1086.  
  1087. @android.annotation.EnforcePermission(android.Manifest.permission.USE_BIOMETRIC_INTERNAL)
  1088. @Override
  1089. public void registerAuthenticator(int id, int modality,
  1090. @Authenticators.Types int strength,
  1091. @NonNull IBiometricAuthenticator authenticator) {
  1092. super.registerAuthenticator_enforcePermission();
  1093. Slog.d(TAG, "Registering ID: " + id
  1094. + " Modality: " + modality
  1095. + " Strength: " + strength);
  1096. if (authenticator == null) {
  1097. throw new IllegalArgumentException("Authenticator must not be null."
  1098. + " Did you forget to modify the core/res/res/values/xml overlay for"
  1099. + " config_biometric_sensors?");
  1100. }
  1101. // Check if the authenticator ID is already registered
  1102. if (mRegisteredAuthenticatorIds.contains(id)) {
  1103. Slog.w(TAG, "Duplicate authenticator registration attempt for ID: " + id);
  1104. return;
  1105. }
  1106. // Note that we allow BIOMETRIC_CONVENIENCE to register because BiometricService
  1107. // also does / will do other things such as keep track of lock screen timeout, etc.
  1108. // Just because a biometric is registered does not mean it can participate in
  1109. // the android.hardware.biometrics APIs.
  1110. if (strength != Authenticators.BIOMETRIC_STRONG
  1111. && strength != Authenticators.BIOMETRIC_WEAK
  1112. && strength != Authenticators.BIOMETRIC_CONVENIENCE) {
  1113. throw new IllegalStateException("Unsupported strength");
  1114. }
  1115. for (BiometricSensor sensor : mSensors) {
  1116. if (sensor.id == id) {
  1117. Slog.w(TAG, "Duplicate authenticator registration attempt for ID: " + id);
  1118. return;
  1119. }
  1120. }
  1121. mSensors.add(new BiometricSensor(getContext(), id, modality, strength, authenticator) {
  1122. @Override
  1123. boolean confirmationAlwaysRequired(int userId) {
  1124. return mSettingObserver.getConfirmationAlwaysRequired(modality, userId);
  1125. }
  1126.  
  1127. @Override
  1128. boolean confirmationSupported() {
  1129. return Utils.isConfirmationSupported(modality);
  1130. }
  1131. });
  1132. mRegisteredAuthenticatorIds.add(id); // Add the ID to the set
  1133. mBiometricStrengthController.updateStrengths();
  1134. }
  1135.  
  1136. @android.annotation.EnforcePermission(android.Manifest.permission.USE_BIOMETRIC_INTERNAL)
  1137. @Override // Binder call
  1138. public void registerEnabledOnKeyguardCallback(
  1139. IBiometricEnabledOnKeyguardCallback callback) {
  1140. super.registerEnabledOnKeyguardCallback_enforcePermission();
  1141. mEnabledOnKeyguardCallbacks.add(new EnabledOnKeyguardCallback(callback));
  1142. final List<UserInfo> aliveUsers = mUserManager.getAliveUsers();
  1143. try {
  1144. for (UserInfo userInfo: aliveUsers) {
  1145. final int userId = userInfo.id;
  1146. callback.onChanged(mSettingObserver.getEnabledOnKeyguard(userId),
  1147. userId);
  1148. }
  1149. } catch (RemoteException e) {
  1150. Slog.w(TAG, "Remote exception", e);
  1151. }
  1152. }
  1153.  
  1154. @android.annotation.EnforcePermission(android.Manifest.permission.USE_BIOMETRIC_INTERNAL)
  1155. @Override // Binder call
  1156. public void invalidateAuthenticatorIds(int userId, int fromSensorId,
  1157. IInvalidationCallback callback) {
  1158. super.invalidateAuthenticatorIds_enforcePermission();
  1159. InvalidationTracker.start(getContext(), mSensors, userId, fromSensorId, callback);
  1160. }
  1161.  
  1162. @android.annotation.EnforcePermission(android.Manifest.permission.USE_BIOMETRIC_INTERNAL)
  1163. @Override // Binder call
  1164. public long[] getAuthenticatorIds(int callingUserId) {
  1165. super.getAuthenticatorIds_enforcePermission();
  1166. final List<Long> authenticatorIds = new ArrayList<>();
  1167. for (BiometricSensor sensor : mSensors) {
  1168. try {
  1169. final boolean hasEnrollments = sensor.impl.hasEnrolledTemplates(callingUserId,
  1170. getContext().getOpPackageName());
  1171. final long authenticatorId = sensor.impl.getAuthenticatorId(callingUserId);
  1172. if (hasEnrollments && Utils.isAtLeastStrength(sensor.getCurrentStrength(),
  1173. Authenticators.BIOMETRIC_STRONG)) {
  1174. authenticatorIds.add(authenticatorId);
  1175. } else {
  1176. Slog.d(TAG, "Sensor " + sensor + ", sensorId " + sensor.id
  1177. + ", hasEnrollments: " + hasEnrollments
  1178. + " cannot participate in Keystore operations");
  1179. }
  1180. } catch (RemoteException e) {
  1181. Slog.e(TAG, "RemoteException", e);
  1182. }
  1183. }
  1184. long[] result = new long[authenticatorIds.size()];
  1185. for (int i = 0; i < authenticatorIds.size(); i++) {
  1186. result[i] = authenticatorIds.get(i);
  1187. }
  1188. return result;
  1189. }
  1190.  
  1191. @android.annotation.EnforcePermission(android.Manifest.permission.USE_BIOMETRIC_INTERNAL)
  1192. @Override // Binder call
  1193. public void resetLockoutTimeBound(IBinder token, String opPackageName, int fromSensorId,
  1194. int userId, byte[] hardwareAuthToken) {
  1195. // Check originating strength
  1196. super.resetLockoutTimeBound_enforcePermission();
  1197. if (!Utils.isAtLeastStrength(getSensorForId(fromSensorId).getCurrentStrength(),
  1198. Authenticators.BIOMETRIC_STRONG)) {
  1199. Slog.w(TAG, "Sensor: " + fromSensorId + " is does not meet the required strength to"
  1200. + " request resetLockout");
  1201. return;
  1202. }
  1203. // Request resetLockout for applicable sensors
  1204. for (BiometricSensor sensor : mSensors) {
  1205. if (sensor.id == fromSensorId) {
  1206. continue;
  1207. }
  1208. try {
  1209. final SensorPropertiesInternal props = sensor.impl
  1210. .getSensorProperties(getContext().getOpPackageName());
  1211. final boolean supportsChallengelessHat =
  1212. props.resetLockoutRequiresHardwareAuthToken
  1213. && !props.resetLockoutRequiresChallenge;
  1214. final boolean doesNotRequireHat = !props.resetLockoutRequiresHardwareAuthToken;
  1215. if (supportsChallengelessHat || doesNotRequireHat) {
  1216. Slog.d(TAG, "resetLockout from: " + fromSensorId
  1217. + ", for: " + sensor.id
  1218. + ", userId: " + userId);
  1219. sensor.impl.resetLockout(token, opPackageName, userId,
  1220. hardwareAuthToken);
  1221. }
  1222. } catch (RemoteException e) {
  1223. Slog.e(TAG, "Remote exception", e);
  1224. }
  1225. }
  1226. }
  1227.  
  1228. @android.annotation.EnforcePermission(android.Manifest.permission.USE_BIOMETRIC_INTERNAL)
  1229. @Override // Binder call
  1230. public void resetLockout(
  1231. int userId, byte[] hardwareAuthToken) {
  1232. super.resetLockout_enforcePermission();
  1233. Slog.d(TAG, "resetLockout(userId=" + userId
  1234. + ", hat=" + (hardwareAuthToken == null ? "null " : "present") + ")");
  1235. mHandler.post(() -> {
  1236. mBiometricContext.getAuthSessionCoordinator()
  1237. .resetLockoutFor(userId, Authenticators.BIOMETRIC_STRONG, -1);
  1238. });
  1239. }
  1240.  
  1241. @android.annotation.EnforcePermission(android.Manifest.permission.USE_BIOMETRIC_INTERNAL)
  1242. @Override // Binder call
  1243. public int getCurrentStrength(int sensorId) {
  1244. super.getCurrentStrength_enforcePermission();
  1245. for (BiometricSensor sensor : mSensors) {
  1246. if (sensor.id == sensorId) {
  1247. return sensor.getCurrentStrength();
  1248. }
  1249. }
  1250. Slog.e(TAG, "Unknown sensorId: " + sensorId);
  1251. return Authenticators.EMPTY_SET;
  1252. }
  1253.  
  1254. @android.annotation.EnforcePermission(android.Manifest.permission.USE_BIOMETRIC_INTERNAL)
  1255. @Override // Binder call
  1256. public int getCurrentModality(
  1257. String opPackageName,
  1258. int userId,
  1259. int callingUserId,
  1260. @Authenticators.Types int authenticators) {
  1261. super.getCurrentModality_enforcePermission();
  1262. Slog.d(TAG, "getCurrentModality: User=" + userId
  1263. + ", Caller=" + callingUserId
  1264. + ", Authenticators=" + authenticators);
  1265. if (!Utils.isValidAuthenticatorConfig(getContext(), authenticators)) {
  1266. throw new SecurityException("Invalid authenticator configuration");
  1267. }
  1268. try {
  1269. final PreAuthInfo preAuthInfo =
  1270. createPreAuthInfo(opPackageName, userId, authenticators);
  1271. return preAuthInfo.getPreAuthenticateStatus().first;
  1272. } catch (RemoteException e) {
  1273. Slog.e(TAG, "Remote exception", e);
  1274. return BiometricAuthenticator.TYPE_NONE;
  1275. }
  1276. }
  1277.  
  1278. @android.annotation.EnforcePermission(android.Manifest.permission.USE_BIOMETRIC_INTERNAL)
  1279. @Override // Binder call
  1280. public int getSupportedModalities(@Authenticators.Types int authenticators) {
  1281. super.getSupportedModalities_enforcePermission();
  1282. Slog.d(TAG, "getSupportedModalities: Authenticators=" + authenticators);
  1283. if (!Utils.isValidAuthenticatorConfig(getContext(), authenticators)) {
  1284. throw new SecurityException("Invalid authenticator configuration");
  1285. }
  1286. @BiometricAuthenticator.Modality int modality =
  1287. Utils.isCredentialRequested(authenticators)
  1288. ? BiometricAuthenticator.TYPE_CREDENTIAL
  1289. : BiometricAuthenticator.TYPE_NONE;
  1290. if (Utils.isBiometricRequested(authenticators)) {
  1291. @Authenticators.Types final int requestedStrength =
  1292. Utils.getPublicBiometricStrength(authenticators);
  1293. // Add modalities of all biometric sensors that meet the authenticator requirements.
  1294. for (final BiometricSensor sensor : mSensors) {
  1295. @Authenticators.Types final int sensorStrength = sensor.getCurrentStrength();
  1296. if (Utils.isAtLeastStrength(sensorStrength, requestedStrength)) {
  1297. modality |= sensor.modality;
  1298. }
  1299. }
  1300. }
  1301. return modality;
  1302. }
  1303.  
  1304. @Override
  1305. protected void dump(@NonNull FileDescriptor fd, @NonNull PrintWriter pw, String[] args) {
  1306. if (!DumpUtils.checkDumpPermission(getContext(), TAG, pw)) {
  1307. return;
  1308. }
  1309. final long ident = Binder.clearCallingIdentity();
  1310. try {
  1311. if (args.length > 0 && "--proto".equals(args[0])) {
  1312. final boolean clearSchedulerBuffer = args.length > 1
  1313. && "--clear-scheduler-buffer".equals(args[1]);
  1314. Slog.d(TAG, "ClearSchedulerBuffer: " + clearSchedulerBuffer);
  1315. final ProtoOutputStream proto = new ProtoOutputStream(fd);
  1316. proto.write(BiometricServiceStateProto.AUTH_SESSION_STATE,
  1317. mAuthSession != null ? mAuthSession.getState() : STATE_AUTH_IDLE);
  1318. for (BiometricSensor sensor : mSensors) {
  1319. byte[] serviceState = sensor.impl
  1320. .dumpSensorServiceStateProto(clearSchedulerBuffer);
  1321. proto.write(BiometricServiceStateProto.SENSOR_SERVICE_STATES, serviceState);
  1322. }
  1323. proto.flush();
  1324. } else {
  1325. dumpInternal(pw);
  1326. }
  1327. } catch (RemoteException e) {
  1328. Slog.e(TAG, "Remote exception", e);
  1329. } finally {
  1330. Binder.restoreCallingIdentity(ident);
  1331. }
  1332. }
  1333. }
  1334.  
  1335. private void checkInternalPermission() {
  1336. getContext().enforceCallingOrSelfPermission(USE_BIOMETRIC_INTERNAL,
  1337. "Must have USE_BIOMETRIC_INTERNAL permission");
  1338. }
  1339.  
  1340. @NonNull
  1341. private PreAuthInfo createPreAuthInfo(
  1342. @NonNull String opPackageName,
  1343. int userId,
  1344. @Authenticators.Types int authenticators) throws RemoteException {
  1345. final PromptInfo promptInfo = new PromptInfo();
  1346. promptInfo.setAuthenticators(authenticators);
  1347. return PreAuthInfo.create(mTrustManager, mDevicePolicyManager, mSettingObserver, mSensors,
  1348. userId, promptInfo, opPackageName, false /* checkDevicePolicyManager */,
  1349. getContext(), mBiometricCameraManager);
  1350. }
  1351.  
  1352. /**
  1353. * Class for injecting dependencies into BiometricService.
  1354. * TODO(b/141025588): Replace with a dependency injection framework (e.g. Guice, Dagger).
  1355. */
  1356. @VisibleForTesting
  1357. public static class Injector {
  1358. public IActivityManager getActivityManagerService() {
  1359. return ActivityManager.getService();
  1360. }
  1361.  
  1362. public KeyStoreAuthorization getKeyStoreAuthorization() {
  1363. return KeyStoreAuthorization.getInstance();
  1364. }
  1365.  
  1366. public IGateKeeperService getGateKeeperService() {
  1367. return GateKeeper.getService();
  1368. }
  1369.  
  1370. public ITrustManager getTrustManager() {
  1371. return ITrustManager.Stub.asInterface(ServiceManager.getService(Context.TRUST_SERVICE));
  1372. }
  1373.  
  1374. public IStatusBarService getStatusBarService() {
  1375. return IStatusBarService.Stub.asInterface(
  1376. ServiceManager.getService(Context.STATUS_BAR_SERVICE));
  1377. }
  1378.  
  1379. /**
  1380. * Allows to mock SettingObserver for testing.
  1381. */
  1382. public SettingObserver getSettingObserver(Context context, Handler handler,
  1383. List<EnabledOnKeyguardCallback> callbacks) {
  1384. return new SettingObserver(context, handler, callbacks);
  1385. }
  1386.  
  1387. /**
  1388. * Allows to enable/disable debug logs.
  1389. */
  1390. public boolean isDebugEnabled(Context context, int userId) {
  1391. return Utils.isDebugEnabled(context, userId);
  1392. }
  1393.  
  1394. /**
  1395. * Allows to stub publishBinderService(...) for testing.
  1396. */
  1397. public void publishBinderService(BiometricService service, IBiometricService.Stub impl) {
  1398. service.publishBinderService(Context.BIOMETRIC_SERVICE, impl);
  1399. }
  1400.  
  1401. /**
  1402. * Allows to mock BiometricStrengthController for testing.
  1403. */
  1404. public BiometricStrengthController getBiometricStrengthController(
  1405. BiometricService service) {
  1406. return new BiometricStrengthController(service);
  1407. }
  1408.  
  1409. /**
  1410. * Allows to test with various device sensor configurations.
  1411. * @param context System Server context
  1412. * @return the sensor configuration from core/res/res/values/config.xml
  1413. */
  1414. public String[] getConfiguration(Context context) {
  1415. return context.getResources().getStringArray(R.array.config_biometric_sensors);
  1416. }
  1417.  
  1418. public DevicePolicyManager getDevicePolicyManager(Context context) {
  1419. return context.getSystemService(DevicePolicyManager.class);
  1420. }
  1421.  
  1422. public List<FingerprintSensorPropertiesInternal> getFingerprintSensorProperties(
  1423. Context context) {
  1424. if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_FINGERPRINT)) {
  1425. final FingerprintManager fpm = context.getSystemService(FingerprintManager.class);
  1426. if (fpm != null) {
  1427. return fpm.getSensorPropertiesInternal();
  1428. }
  1429. }
  1430. return new ArrayList<>();
  1431. }
  1432.  
  1433. public Supplier<Long> getRequestGenerator() {
  1434. final AtomicLong generator = new AtomicLong(0);
  1435. return () -> generator.incrementAndGet();
  1436. }
  1437.  
  1438. public BiometricContext getBiometricContext(Context context) {
  1439. return BiometricContext.getInstance(context);
  1440. }
  1441.  
  1442. public UserManager getUserManager(Context context) {
  1443. return context.getSystemService(UserManager.class);
  1444. }
  1445.  
  1446. public BiometricCameraManager getBiometricCameraManager(Context context) {
  1447. return new BiometricCameraManagerImpl(context.getSystemService(CameraManager.class),
  1448. context.getSystemService(SensorPrivacyManager.class));
  1449. }
  1450.  
  1451. public BiometricNotificationLogger getNotificationLogger() {
  1452. return new BiometricNotificationLogger();
  1453. }
  1454. }
  1455.  
  1456. /**
  1457. * Initializes the system service.
  1458. * <p>
  1459. * Subclasses must define a single argument constructor that accepts the context
  1460. * and passes it to super.
  1461. * </p>
  1462. *
  1463. * @param context The system server context.
  1464. */
  1465. public BiometricService(Context context) {
  1466. this(context, new Injector(), BiometricHandlerProvider.getInstance());
  1467. }
  1468.  
  1469. @VisibleForTesting
  1470. BiometricService(Context context, Injector injector,
  1471. BiometricHandlerProvider biometricHandlerProvider) {
  1472. super(context);
  1473. mInjector = injector;
  1474. mHandler = biometricHandlerProvider.getBiometricCallbackHandler();
  1475. mDevicePolicyManager = mInjector.getDevicePolicyManager(context);
  1476. mImpl = new BiometricServiceWrapper();
  1477. mEnabledOnKeyguardCallbacks = new ArrayList<>();
  1478. mSettingObserver = mInjector.getSettingObserver(context, mHandler,
  1479. mEnabledOnKeyguardCallbacks);
  1480. mRequestCounter = mInjector.getRequestGenerator();
  1481. mBiometricContext = injector.getBiometricContext(context);
  1482. mUserManager = injector.getUserManager(context);
  1483. mBiometricCameraManager = injector.getBiometricCameraManager(context);
  1484. mKeyStoreAuthorization = injector.getKeyStoreAuthorization();
  1485. mGateKeeper = injector.getGateKeeperService();
  1486. mBiometricNotificationLogger = injector.getNotificationLogger();
  1487. try {
  1488. injector.getActivityManagerService().registerUserSwitchObserver(
  1489. new UserSwitchObserver() {
  1490. @Override
  1491. public void onUserSwitchComplete(int newUserId) {
  1492. mSettingObserver.updateContentObserver();
  1493. mSettingObserver.notifyEnabledOnKeyguardCallbacks(newUserId);
  1494. }
  1495. }, BiometricService.class.getName()
  1496. );
  1497. } catch (RemoteException e) {
  1498. Slog.e(TAG, "Failed to register user switch observer", e);
  1499. }
  1500. }
  1501.  
  1502. @Override
  1503. public void onStart() {
  1504. mStatusBarService = mInjector.getStatusBarService();
  1505. mTrustManager = mInjector.getTrustManager();
  1506. mInjector.publishBinderService(this, mImpl);
  1507. mBiometricStrengthController = mInjector.getBiometricStrengthController(this);
  1508. mBiometricStrengthController.startListening();
  1509. mHandler.post(new Runnable(){
  1510. @Override
  1511. public void run() {
  1512. try {
  1513. mBiometricNotificationLogger.registerAsSystemService(getContext(),
  1514. new ComponentName(getContext(), BiometricService.class),
  1515. UserHandle.USER_ALL);
  1516. } catch (RemoteException e) {
  1517. // Intra-process call, should never happen.
  1518. }
  1519. }
  1520. });
  1521. }
  1522.  
  1523. private boolean isStrongBiometric(int id) {
  1524. for (BiometricSensor sensor : mSensors) {
  1525. if (sensor.id == id) {
  1526. return Utils.isAtLeastStrength(sensor.getCurrentStrength(),
  1527. Authenticators.BIOMETRIC_STRONG);
  1528. }
  1529. }
  1530. Slog.e(TAG, "Unknown sensorId: " + id);
  1531. return false;
  1532. }
  1533.  
  1534. @Nullable
  1535. private AuthSession getAuthSessionIfCurrent(long requestId) {
  1536. final AuthSession session = mAuthSession;
  1537. if (session != null && session.getRequestId() == requestId) {
  1538. return session;
  1539. }
  1540. return null;
  1541. }
  1542.  
  1543. private void handleAuthenticationSucceeded(long requestId, int sensorId, byte[] token) {
  1544. Slog.v(TAG, "handleAuthenticationSucceeded(), sensorId: " + sensorId);
  1545. // Should never happen, log this to catch bad HAL behavior (e.g. auth succeeded
  1546. // after user dismissed/canceled dialog).
  1547. final AuthSession session = getAuthSessionIfCurrent(requestId);
  1548. if (session == null) {
  1549. Slog.e(TAG, "handleAuthenticationSucceeded: AuthSession is null");
  1550. return;
  1551. }
  1552. session.onAuthenticationSucceeded(sensorId, isStrongBiometric(sensorId), token);
  1553. }
  1554.  
  1555. private void handleAuthenticationRejected(long requestId, int sensorId) {
  1556. Slog.v(TAG, "handleAuthenticationRejected()");
  1557. // Should never happen, log this to catch bad HAL behavior (e.g. auth rejected
  1558. // after user dismissed/canceled dialog).
  1559. final AuthSession session = getAuthSessionIfCurrent(requestId);
  1560. if (session == null) {
  1561. Slog.w(TAG, "handleAuthenticationRejected: AuthSession is not current");
  1562. return;
  1563. }
  1564. session.onAuthenticationRejected(sensorId);
  1565. }
  1566.  
  1567. private void handleAuthenticationTimedOut(long requestId, int sensorId, int cookie, int error,
  1568. int vendorCode) {
  1569. Slog.v(TAG, "handleAuthenticationTimedOut(), sensorId: " + sensorId
  1570. + ", cookie: " + cookie
  1571. + ", error: " + error
  1572. + ", vendorCode: " + vendorCode);
  1573. // Should never happen, log this to catch bad HAL behavior (e.g. auth succeeded
  1574. // after user dismissed/canceled dialog).
  1575. final AuthSession session = getAuthSessionIfCurrent(requestId);
  1576. if (session == null) {
  1577. Slog.w(TAG, "handleAuthenticationTimedOut: AuthSession is not current");
  1578. return;
  1579. }
  1580. session.onAuthenticationTimedOut(sensorId, cookie, error, vendorCode);
  1581. }
  1582.  
  1583. private void handleOnError(long requestId, int sensorId, int cookie,
  1584. @BiometricConstants.Errors int error, int vendorCode) {
  1585. Slog.d(TAG, "handleOnError() sensorId: " + sensorId
  1586. + ", cookie: " + cookie
  1587. + ", error: " + error
  1588. + ", vendorCode: " + vendorCode);
  1589. final AuthSession session = getAuthSessionIfCurrent(requestId);
  1590. if (session == null) {
  1591. Slog.w(TAG, "handleOnError: AuthSession is not current");
  1592. return;
  1593. }
  1594. try {
  1595. final boolean finished = session.onErrorReceived(sensorId, cookie, error, vendorCode);
  1596. if (finished) {
  1597. Slog.d(TAG, "handleOnError: AuthSession finished");
  1598. mAuthSession = null;
  1599. }
  1600. } catch (RemoteException e) {
  1601. Slog.e(TAG, "RemoteException", e);
  1602. }
  1603. }
  1604.  
  1605. private void handleOnAcquired(long requestId, int sensorId, int acquiredInfo, int vendorCode) {
  1606. // Should never happen, log this to catch bad HAL behavior (e.g. auth succeeded
  1607. // after user dismissed/canceled dialog).
  1608. final AuthSession session = getAuthSessionIfCurrent(requestId);
  1609. if (session == null) {
  1610. Slog.w(TAG, "onAcquired: AuthSession is not current");
  1611. return;
  1612. }
  1613. session.onAcquired(sensorId, acquiredInfo, vendorCode);
  1614. }
  1615.  
  1616. private void handleOnDismissed(long requestId, @BiometricPrompt.DismissedReason int reason,
  1617. @Nullable byte[] credentialAttestation) {
  1618. final AuthSession session = getAuthSessionIfCurrent(requestId);
  1619. if (session == null) {
  1620. Slog.e(TAG, "onDismissed: " + reason + ", AuthSession is not current");
  1621. return;
  1622. }
  1623. session.onDialogDismissed(reason, credentialAttestation);
  1624. mAuthSession = null;
  1625. }
  1626.  
  1627. private void handleOnTryAgainPressed(long requestId) {
  1628. Slog.d(TAG, "onTryAgainPressed");
  1629. // No need to check permission, since it can only be invoked by SystemUI
  1630. // (or system server itself).
  1631. final AuthSession session = getAuthSessionIfCurrent(requestId);
  1632. if (session == null) {
  1633. Slog.w(TAG, "handleOnTryAgainPressed: AuthSession is not current");
  1634. return;
  1635. }
  1636. session.onTryAgainPressed();
  1637. }
  1638.  
  1639. private void handleOnDeviceCredentialPressed(long requestId) {
  1640. Slog.d(TAG, "onDeviceCredentialPressed");
  1641. final AuthSession session = getAuthSessionIfCurrent(requestId);
  1642. if (session == null) {
  1643. Slog.w(TAG, "handleOnDeviceCredentialPressed: AuthSession is not current");
  1644. return;
  1645. }
  1646. session.onDeviceCredentialPressed();
  1647. }
  1648.  
  1649. private void handleOnSystemEvent(long requestId, int event) {
  1650. Slog.d(TAG, "onSystemEvent: " + event);
  1651. final AuthSession session = getAuthSessionIfCurrent(requestId);
  1652. if (session == null) {
  1653. Slog.w(TAG, "handleOnSystemEvent: AuthSession is not current");
  1654. return;
  1655. }
  1656. session.onSystemEvent(event);
  1657. }
  1658.  
  1659. private void handleClientDied(long requestId) {
  1660. final AuthSession session = getAuthSessionIfCurrent(requestId);
  1661. if (session == null) {
  1662. Slog.w(TAG, "handleClientDied: AuthSession is not current");
  1663. return;
  1664. }
  1665. Slog.e(TAG, "Session: " + session);
  1666. final boolean finished = session.onClientDied();
  1667. if (finished) {
  1668. mAuthSession = null;
  1669. }
  1670. }
  1671.  
  1672. private void handleOnDialogAnimatedIn(long requestId, boolean startFingerprintNow) {
  1673. Slog.d(TAG, "handleOnDialogAnimatedIn");
  1674. final AuthSession session = getAuthSessionIfCurrent(requestId);
  1675. if (session == null) {
  1676. Slog.w(TAG, "handleOnDialogAnimatedIn: AuthSession is not current");
  1677. return;
  1678. }
  1679. session.onDialogAnimatedIn(startFingerprintNow);
  1680. }
  1681.  
  1682. private void handleOnStartFingerprintNow(long requestId) {
  1683. Slog.d(TAG, "handleOnStartFingerprintNow");
  1684. final AuthSession session = getAuthSessionIfCurrent(requestId);
  1685. if (session == null) {
  1686. Slog.w(TAG, "handleOnStartFingerprintNow: AuthSession is not current");
  1687. return;
  1688. }
  1689. session.onStartFingerprint();
  1690. }
  1691.  
  1692. /**
  1693. * Invoked when each service has notified that its client is ready to be started. When
  1694. * all biometrics are ready, this invokes the SystemUI dialog through StatusBar.
  1695. */
  1696. private void handleOnReadyForAuthentication(long requestId, int cookie) {
  1697. final AuthSession session = getAuthSessionIfCurrent(requestId);
  1698. if (session == null) {
  1699. // Only should happen if a biometric was locked out when authenticate() was invoked.
  1700. // In that case, if device credentials are allowed, the UI is already showing. If not
  1701. // allowed, the error has already been returned to the caller.
  1702. Slog.w(TAG, "handleOnReadyForAuthentication: AuthSession is not current");
  1703. return;
  1704. }
  1705. session.onCookieReceived(cookie);
  1706. }
  1707.  
  1708. private void handleAuthenticate(IBinder token, long requestId, long operationId, int userId,
  1709. IBiometricServiceReceiver receiver, String opPackageName, PromptInfo promptInfo) {
  1710. mHandler.post(() -> {
  1711. try {
  1712. final PreAuthInfo preAuthInfo = PreAuthInfo.create(mTrustManager,
  1713. mDevicePolicyManager, mSettingObserver, mSensors, userId, promptInfo,
  1714. opPackageName, promptInfo.isDisallowBiometricsIfPolicyExists(),
  1715. getContext(), mBiometricCameraManager);
  1716. // Set the default title if necessary.
  1717. if (promptInfo.isUseDefaultTitle()) {
  1718. if (TextUtils.isEmpty(promptInfo.getTitle())) {
  1719. promptInfo.setTitle(getContext()
  1720. .getString(R.string.biometric_dialog_default_title));
  1721. }
  1722. }
  1723. final int eligible = preAuthInfo.getEligibleModalities();
  1724. final boolean hasEligibleFingerprintSensor =
  1725. (eligible & TYPE_FINGERPRINT) == TYPE_FINGERPRINT;
  1726. final boolean hasEligibleFaceSensor = (eligible & TYPE_FACE) == TYPE_FACE;
  1727. // Set the subtitle according to the modality.
  1728. if (promptInfo.isUseDefaultSubtitle()) {
  1729. if (hasEligibleFingerprintSensor && hasEligibleFaceSensor) {
  1730. promptInfo.setSubtitle(getContext()
  1731. .getString(R.string.biometric_dialog_default_subtitle));
  1732. } else if (hasEligibleFingerprintSensor) {
  1733. promptInfo.setSubtitle(getContext()
  1734. .getString(R.string.fingerprint_dialog_default_subtitle));
  1735. } else if (hasEligibleFaceSensor) {
  1736. promptInfo.setSubtitle(getContext()
  1737. .getString(R.string.face_dialog_default_subtitle));
  1738. } else {
  1739. promptInfo.setSubtitle(getContext()
  1740. .getString(R.string.screen_lock_dialog_default_subtitle));
  1741. }
  1742. }
  1743. final Pair<Integer, Integer> preAuthStatus = preAuthInfo.getPreAuthenticateStatus();
  1744. Slog.d(TAG, "handleAuthenticate: modality(" + preAuthStatus.first
  1745. + "), status(" + preAuthStatus.second + "), preAuthInfo: " + preAuthInfo
  1746. + " requestId: " + requestId + " promptInfo.isIgnoreEnrollmentState: "
  1747. + promptInfo.isIgnoreEnrollmentState());
  1748. // BIOMETRIC_ERROR_SENSOR_PRIVACY_ENABLED is added so that BiometricPrompt can
  1749. // be shown for this case.
  1750. if (preAuthStatus.second == BiometricConstants.BIOMETRIC_SUCCESS) {
  1751. // If BIOMETRIC_WEAK or BIOMETRIC_STRONG are allowed, but not enrolled, but
  1752. // CREDENTIAL is requested and available, set the bundle to only request
  1753. // CREDENTIAL.
  1754. // TODO: We should clean this up, as well as the interface with SystemUI
  1755. if (preAuthInfo.credentialRequested && preAuthInfo.credentialAvailable
  1756. && preAuthInfo.eligibleSensors.isEmpty()) {
  1757. promptInfo.setAuthenticators(Authenticators.DEVICE_CREDENTIAL);
  1758. }
  1759. authenticateInternal(token, requestId, operationId, userId, receiver,
  1760. opPackageName, promptInfo, preAuthInfo);
  1761. } else {
  1762. receiver.onError(preAuthStatus.first /* modality */,
  1763. preAuthStatus.second /* errorCode */,
  1764. 0 /* vendorCode */);
  1765. }
  1766. } catch (RemoteException e) {
  1767. Slog.e(TAG, "Remote exception", e);
  1768. }
  1769. });
  1770. }
  1771.  
  1772. /**
  1773. * handleAuthenticate() (above) which is called from BiometricPrompt determines which
  1774. * modality/modalities to start authenticating with. authenticateInternal() should only be
  1775. * used for preparing <Biometric>Services for authentication when BiometricPrompt#authenticate
  1776. * is invoked, shortly after which BiometricPrompt is shown and authentication starts.
  1777. *
  1778. * Note that this path is NOT invoked when the BiometricPrompt "Try again" button is pressed.
  1779. * In that case, see {@link #handleOnTryAgainPressed()}.
  1780. */
  1781. private void authenticateInternal(IBinder token, long requestId, long operationId, int userId,
  1782. IBiometricServiceReceiver receiver, String opPackageName, PromptInfo promptInfo,
  1783. PreAuthInfo preAuthInfo) {
  1784. Slog.d(TAG, "Creating authSession with authRequest: " + preAuthInfo);
  1785. // No need to dismiss dialog / send error yet if we're continuing authentication, e.g.
  1786. // "Try again" is showing due to something like ERROR_TIMEOUT.
  1787. if (mAuthSession != null) {
  1788. // Forcefully cancel authentication. Dismiss the UI, and immediately send
  1789. // ERROR_CANCELED to the client. Note that we should/will ignore HAL ERROR_CANCELED.
  1790. // Expect to see some harmless "unknown cookie" errors.
  1791. Slog.w(TAG, "Existing AuthSession: " + mAuthSession);
  1792. mAuthSession.onCancelAuthSession(true /* force */);
  1793. mAuthSession = null;
  1794. }
  1795. final boolean debugEnabled = mInjector.isDebugEnabled(getContext(), userId);
  1796. mAuthSession = new AuthSession(getContext(), mBiometricContext, mStatusBarService,
  1797. createSysuiReceiver(requestId), mKeyStoreAuthorization, mRandom,
  1798. createClientDeathReceiver(requestId), preAuthInfo, token, requestId,
  1799. operationId, userId, createBiometricSensorReceiver(requestId), receiver,
  1800. opPackageName, promptInfo, debugEnabled,
  1801. mInjector.getFingerprintSensorProperties(getContext()));
  1802. try {
  1803. mAuthSession.goToInitialState();
  1804. } catch (RemoteException e) {
  1805. Slog.e(TAG, "RemoteException", e);
  1806. }
  1807. }
  1808.  
  1809. private void handleCancelAuthentication(long requestId) {
  1810. final AuthSession session = getAuthSessionIfCurrent(requestId);
  1811. if (session == null) {
  1812. Slog.w(TAG, "handleCancelAuthentication: AuthSession is not current");
  1813. // TODO: actually cancel the operation?
  1814. return;
  1815. }
  1816. final boolean finished = session.onCancelAuthSession(false /* force */);
  1817. if (finished) {
  1818. Slog.d(TAG, "handleCancelAuthentication: AuthSession finished");
  1819. mAuthSession = null;
  1820. }
  1821. }
  1822.  
  1823. @Nullable
  1824. private BiometricSensor getSensorForId(int sensorId) {
  1825. for (BiometricSensor sensor : mSensors) {
  1826. if (sensor.id == sensorId) {
  1827. return sensor;
  1828. }
  1829. }
  1830. return null;
  1831. }
  1832.  
  1833. private void dumpInternal(PrintWriter pw) {
  1834. pw.println("Legacy Settings: " + mSettingObserver.mUseLegacyFaceOnlySettings);
  1835. pw.println();
  1836. pw.println("Sensors:");
  1837. for (BiometricSensor sensor : mSensors) {
  1838. pw.println(" " + sensor);
  1839. }
  1840. pw.println();
  1841. pw.println("CurrentSession: " + mAuthSession);
  1842. pw.println();
  1843. }
  1844. }
  1845.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement