From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Dmitry Muhomor <muhomor.dmitry@gmail.com>
Date: Sun, 24 Jul 2022 13:07:00 +0300
Subject: [PATCH] protect step sensors with OTHER_SENSORS permission for
 targetSdk<29 apps

---
 services/sensorservice/SensorService.cpp | 24 +++++++++++++++---------
 1 file changed, 15 insertions(+), 9 deletions(-)

diff --git a/services/sensorservice/SensorService.cpp b/services/sensorservice/SensorService.cpp
index bdbae7b1ec..e1f0300407 100644
--- a/services/sensorservice/SensorService.cpp
+++ b/services/sensorservice/SensorService.cpp
@@ -1938,17 +1938,9 @@ bool SensorService::canAccessSensor(const Sensor& sensor, const char* operation,
     }
 
     const int32_t opCode = sensor.getRequiredAppOp();
-    int targetSdkVersion = getTargetSdkVersion(opPackageName);
 
     bool canAccess = false;
-    if (targetSdkVersion > 0 && targetSdkVersion <= __ANDROID_API_P__ &&
-            (sensor.getType() == SENSOR_TYPE_STEP_COUNTER ||
-             sensor.getType() == SENSOR_TYPE_STEP_DETECTOR)) {
-        // Allow access to step sensors if the application targets pre-Q, which is before the
-        // requirement to hold the AR permission to access Step Counter and Step Detector events
-        // was introduced.
-        canAccess = true;
-    } else if (hasPermissionForSensor(sensor)) {
+    if (hasPermissionForSensor(sensor)) {
         // Ensure that the AppOp is allowed, or that there is no necessary app op for the sensor
         if (opCode >= 0) {
             const int32_t appOpMode = sAppOpsManager.checkOp(opCode,
@@ -1957,6 +1949,20 @@ bool SensorService::canAccessSensor(const Sensor& sensor, const char* operation,
         } else {
             canAccess = true;
         }
+    } else {
+        int targetSdkVersion = getTargetSdkVersion(opPackageName);
+        if (targetSdkVersion > 0 && targetSdkVersion <= __ANDROID_API_P__ &&
+            (sensor.getType() == SENSOR_TYPE_STEP_COUNTER ||
+             sensor.getType() == SENSOR_TYPE_STEP_DETECTOR)) {
+
+            // upstream allows access to these sensors without the ACTIVITY_RECOGNITION permission
+            // for targetSdk < 29 apps, enforce the OTHER_SENSORS permission instead
+            const String16 requiredPermission("android.permission.OTHER_SENSORS");
+
+            // copied from hasPermissionForSensor() below
+            canAccess = checkPermission(requiredPermission,
+                IPCThreadState::self()->getCallingPid(), IPCThreadState::self()->getCallingUid());
+         }
     }
 
     if (!canAccess) {
