blob: 2d963d92908100add6ba8bb0c6050a6ccf3f87da [file] [log] [blame]
Glenn Kasten44deb052012-02-05 18:09:08 -08001/*
2 * Copyright (C) 2012 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
Eric Laurent9b11c022018-06-06 19:19:22 -070017#define LOG_TAG "ServiceUtilities"
18
Andy Hunga85efab2019-12-23 11:41:29 -080019#include <audio_utils/clock.h>
Svet Ganovbe71aa22015-04-28 12:06:02 -070020#include <binder/AppOpsManager.h>
Glenn Kasten44deb052012-02-05 18:09:08 -080021#include <binder/IPCThreadState.h>
22#include <binder/IServiceManager.h>
23#include <binder/PermissionCache.h>
Andy Hungab7ef302018-05-15 19:35:29 -070024#include "mediautils/ServiceUtilities.h"
Nate Myrene69cada2020-12-10 10:00:36 -080025#include <system/audio-hal-enums.h>
Philip P. Moltmannbda45752020-07-17 16:41:18 -070026#include <media/AidlConversion.h>
27#include <media/AidlConversionUtil.h>
Svet Ganov33761132021-05-13 22:51:08 +000028#include <android/content/AttributionSourceState.h>
Glenn Kasten44deb052012-02-05 18:09:08 -080029
Kevin Rocard8be94972019-02-22 13:26:25 -080030#include <iterator>
31#include <algorithm>
Andy Hunga85efab2019-12-23 11:41:29 -080032#include <pwd.h>
Kevin Rocard8be94972019-02-22 13:26:25 -080033
Svet Ganovbe71aa22015-04-28 12:06:02 -070034/* When performing permission checks we do not use permission cache for
35 * runtime permissions (protection level dangerous) as they may change at
36 * runtime. All other permissions (protection level normal and dangerous)
37 * can be cached as they never change. Of course all permission checked
38 * here are platform defined.
39 */
40
Glenn Kasten44deb052012-02-05 18:09:08 -080041namespace android {
42
Svet Ganov33761132021-05-13 22:51:08 +000043using content::AttributionSourceState;
Philip P. Moltmannbda45752020-07-17 16:41:18 -070044
Svet Ganov5b81f552018-03-02 09:21:30 -080045static const String16 sAndroidPermissionRecordAudio("android.permission.RECORD_AUDIO");
Eric Laurent42984412019-05-09 17:57:03 -070046static const String16 sModifyPhoneState("android.permission.MODIFY_PHONE_STATE");
47static const String16 sModifyAudioRouting("android.permission.MODIFY_AUDIO_ROUTING");
Eric Laurentb0eff0f2021-11-09 16:05:49 +010048static const String16 sCallAudioInterception("android.permission.CALL_AUDIO_INTERCEPTION");
Eric Laurent24df2832023-10-13 18:13:43 +020049static const String16 sAndroidPermissionBluetoothConnect("android.permission.BLUETOOTH_CONNECT");
Svet Ganov5b81f552018-03-02 09:21:30 -080050
Svet Ganov5b81f552018-03-02 09:21:30 -080051static String16 resolveCallingPackage(PermissionController& permissionController,
Philip P. Moltmannbda45752020-07-17 16:41:18 -070052 const std::optional<String16> opPackageName, uid_t uid) {
53 if (opPackageName.has_value() && opPackageName.value().size() > 0) {
54 return opPackageName.value();
Svet Ganovbe71aa22015-04-28 12:06:02 -070055 }
Svet Ganovbe71aa22015-04-28 12:06:02 -070056 // In some cases the calling code has no access to the package it runs under.
57 // For example, code using the wilhelm framework's OpenSL-ES APIs. In this
58 // case we will get the packages for the calling UID and pick the first one
59 // for attributing the app op. This will work correctly for runtime permissions
60 // as for legacy apps we will toggle the app op for all packages in the UID.
61 // The caveat is that the operation may be attributed to the wrong package and
62 // stats based on app ops may be slightly off.
Svet Ganov5b81f552018-03-02 09:21:30 -080063 Vector<String16> packages;
64 permissionController.getPackagesForUid(uid, packages);
65 if (packages.isEmpty()) {
66 ALOGE("No packages for uid %d", uid);
Philip P. Moltmannbda45752020-07-17 16:41:18 -070067 return String16();
Svet Ganov5b81f552018-03-02 09:21:30 -080068 }
69 return packages[0];
70}
Svetoslav Ganov599ec462018-03-01 22:19:55 +000071
Eric Laurent45e16b92021-05-20 11:10:47 +020072int32_t getOpForSource(audio_source_t source) {
Nate Myrene69cada2020-12-10 10:00:36 -080073 switch (source) {
74 case AUDIO_SOURCE_HOTWORD:
75 return AppOpsManager::OP_RECORD_AUDIO_HOTWORD;
Mickey Keeley90d657d2021-10-20 18:06:38 -070076 case AUDIO_SOURCE_ECHO_REFERENCE: // fallthrough
Nate Myrene69cada2020-12-10 10:00:36 -080077 case AUDIO_SOURCE_REMOTE_SUBMIX:
78 return AppOpsManager::OP_RECORD_AUDIO_OUTPUT;
Nate Myrenf7c88352021-04-12 14:41:49 -070079 case AUDIO_SOURCE_VOICE_DOWNLINK:
80 return AppOpsManager::OP_RECORD_INCOMING_PHONE_AUDIO;
Nate Myrene69cada2020-12-10 10:00:36 -080081 case AUDIO_SOURCE_DEFAULT:
82 default:
83 return AppOpsManager::OP_RECORD_AUDIO;
84 }
85}
86
Svet Ganov33761132021-05-13 22:51:08 +000087std::optional<AttributionSourceState> resolveAttributionSource(
88 const AttributionSourceState& callerAttributionSource) {
89 AttributionSourceState nextAttributionSource = callerAttributionSource;
90
91 if (!nextAttributionSource.packageName.has_value()) {
92 nextAttributionSource = AttributionSourceState(nextAttributionSource);
93 PermissionController permissionController;
94 const uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(nextAttributionSource.uid));
95 nextAttributionSource.packageName = VALUE_OR_FATAL(legacy2aidl_String16_string(
96 resolveCallingPackage(permissionController, VALUE_OR_FATAL(
97 aidl2legacy_string_view_String16(nextAttributionSource.packageName.value_or(""))),
98 uid)));
99 if (!nextAttributionSource.packageName.has_value()) {
100 return std::nullopt;
101 }
102 }
103
104 AttributionSourceState myAttributionSource;
105 myAttributionSource.uid = VALUE_OR_FATAL(android::legacy2aidl_uid_t_int32_t(getuid()));
106 myAttributionSource.pid = VALUE_OR_FATAL(android::legacy2aidl_pid_t_int32_t(getpid()));
Nate Myrene84d6912022-11-10 14:09:34 -0800107 // Create a static token for audioserver requests, which identifies the
108 // audioserver to the app ops system
109 static sp<BBinder> appOpsToken = sp<BBinder>::make();
110 myAttributionSource.token = appOpsToken;
Svet Ganov33761132021-05-13 22:51:08 +0000111 myAttributionSource.next.push_back(nextAttributionSource);
112
113 return std::optional<AttributionSourceState>{myAttributionSource};
114}
115
Marvin Ramine5a122d2023-12-07 13:57:59 +0100116 static bool checkRecordingInternal(const AttributionSourceState &attributionSource,
117 const uint32_t virtualDeviceId,
118 const String16 &msg, bool start, audio_source_t source) {
Eric Laurent58a0dd82019-10-24 12:42:17 -0700119 // Okay to not track in app ops as audio server or media server is us and if
Svet Ganov5b81f552018-03-02 09:21:30 -0800120 // device is rooted security model is considered compromised.
Jeffrey Carlyle62cc92b2019-09-17 11:15:15 -0700121 // system_server loses its RECORD_AUDIO permission when a secondary
122 // user is active, but it is a core system service so let it through.
123 // TODO(b/141210120): UserManager.DISALLOW_RECORD_AUDIO should not affect system user 0
Svet Ganov33761132021-05-13 22:51:08 +0000124 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent58a0dd82019-10-24 12:42:17 -0700125 if (isAudioServerOrMediaServerOrSystemServerOrRootUid(uid)) return true;
Svetoslav Ganov599ec462018-03-01 22:19:55 +0000126
Svet Ganov5b81f552018-03-02 09:21:30 -0800127 // We specify a pid and uid here as mediaserver (aka MediaRecorder or StageFrightRecorder)
Svet Ganov33761132021-05-13 22:51:08 +0000128 // may open a record track on behalf of a client. Note that pid may be a tid.
Svet Ganov5b81f552018-03-02 09:21:30 -0800129 // IMPORTANT: DON'T USE PermissionCache - RUNTIME PERMISSIONS CHANGE.
Marvin Ramine5a122d2023-12-07 13:57:59 +0100130 std::optional<AttributionSourceState> resolvedAttributionSource =
Svet Ganov33761132021-05-13 22:51:08 +0000131 resolveAttributionSource(attributionSource);
132 if (!resolvedAttributionSource.has_value()) {
Svet Ganov5b81f552018-03-02 09:21:30 -0800133 return false;
134 }
135
Svet Ganov33761132021-05-13 22:51:08 +0000136 const int32_t attributedOpCode = getOpForSource(source);
Svetoslav Ganov599ec462018-03-01 22:19:55 +0000137
Svet Ganov33761132021-05-13 22:51:08 +0000138 permission::PermissionChecker permissionChecker;
Marvin Ramine5a122d2023-12-07 13:57:59 +0100139 resolvedAttributionSource.value().deviceId = virtualDeviceId;
Svet Ganov33761132021-05-13 22:51:08 +0000140 bool permitted = false;
Svet Ganov5b81f552018-03-02 09:21:30 -0800141 if (start) {
Svet Ganov33761132021-05-13 22:51:08 +0000142 permitted = (permissionChecker.checkPermissionForStartDataDeliveryFromDatasource(
143 sAndroidPermissionRecordAudio, resolvedAttributionSource.value(), msg,
144 attributedOpCode) != permission::PermissionChecker::PERMISSION_HARD_DENIED);
Svet Ganov5b81f552018-03-02 09:21:30 -0800145 } else {
Svet Ganov33761132021-05-13 22:51:08 +0000146 permitted = (permissionChecker.checkPermissionForPreflightFromDatasource(
147 sAndroidPermissionRecordAudio, resolvedAttributionSource.value(), msg,
148 attributedOpCode) != permission::PermissionChecker::PERMISSION_HARD_DENIED);
Svetoslav Ganov599ec462018-03-01 22:19:55 +0000149 }
150
Svet Ganov33761132021-05-13 22:51:08 +0000151 return permitted;
Glenn Kasten44deb052012-02-05 18:09:08 -0800152}
153
Marvin Ramine5a122d2023-12-07 13:57:59 +0100154static constexpr int DEVICE_ID_DEFAULT = 0;
155
156bool recordingAllowed(const AttributionSourceState &attributionSource, audio_source_t source) {
157 return checkRecordingInternal(attributionSource, DEVICE_ID_DEFAULT, String16(), /*start*/ false,
158 source);
159}
160
161bool recordingAllowed(const AttributionSourceState &attributionSource,
162 const uint32_t virtualDeviceId,
163 audio_source_t source) {
164 return checkRecordingInternal(attributionSource, virtualDeviceId,
165 String16(), /*start*/ false, source);
Svet Ganov5b81f552018-03-02 09:21:30 -0800166}
167
Svet Ganov33761132021-05-13 22:51:08 +0000168bool startRecording(const AttributionSourceState& attributionSource, const String16& msg,
169 audio_source_t source) {
Marvin Ramine5a122d2023-12-07 13:57:59 +0100170 return checkRecordingInternal(attributionSource, DEVICE_ID_DEFAULT, msg, /*start*/ true,
171 source);
Svet Ganov5b81f552018-03-02 09:21:30 -0800172}
173
Svet Ganov33761132021-05-13 22:51:08 +0000174void finishRecording(const AttributionSourceState& attributionSource, audio_source_t source) {
Svet Ganov5b81f552018-03-02 09:21:30 -0800175 // Okay to not track in app ops as audio server is us and if
176 // device is rooted security model is considered compromised.
Svet Ganov33761132021-05-13 22:51:08 +0000177 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
178 if (isAudioServerOrMediaServerOrSystemServerOrRootUid(uid)) return;
Svet Ganov5b81f552018-03-02 09:21:30 -0800179
Svet Ganov33761132021-05-13 22:51:08 +0000180 // We specify a pid and uid here as mediaserver (aka MediaRecorder or StageFrightRecorder)
181 // may open a record track on behalf of a client. Note that pid may be a tid.
182 // IMPORTANT: DON'T USE PermissionCache - RUNTIME PERMISSIONS CHANGE.
183 const std::optional<AttributionSourceState> resolvedAttributionSource =
184 resolveAttributionSource(attributionSource);
185 if (!resolvedAttributionSource.has_value()) {
Svet Ganov5b81f552018-03-02 09:21:30 -0800186 return;
187 }
188
Svet Ganov33761132021-05-13 22:51:08 +0000189 const int32_t attributedOpCode = getOpForSource(source);
190 permission::PermissionChecker permissionChecker;
191 permissionChecker.finishDataDeliveryFromDatasource(attributedOpCode,
192 resolvedAttributionSource.value());
Svet Ganov5b81f552018-03-02 09:21:30 -0800193}
194
Svet Ganov33761132021-05-13 22:51:08 +0000195bool captureAudioOutputAllowed(const AttributionSourceState& attributionSource) {
196 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Andy Hung4ef19fa2018-05-15 19:35:29 -0700197 if (isAudioServerOrRootUid(uid)) return true;
Jeff Brown893a5642013-08-16 20:19:26 -0700198 static const String16 sCaptureAudioOutput("android.permission.CAPTURE_AUDIO_OUTPUT");
lpeter20d2e032022-06-01 19:38:44 +0800199 // Use PermissionChecker, which includes some logic for allowing the isolated
200 // HotwordDetectionService to hold certain permissions.
201 permission::PermissionChecker permissionChecker;
202 bool ok = (permissionChecker.checkPermissionForPreflight(
203 sCaptureAudioOutput, attributionSource, String16(),
204 AppOpsManager::OP_NONE) != permission::PermissionChecker::PERMISSION_HARD_DENIED);
Eric Laurent6ede98f2019-06-11 14:50:30 -0700205 if (!ok) ALOGV("Request requires android.permission.CAPTURE_AUDIO_OUTPUT");
Jeff Brown893a5642013-08-16 20:19:26 -0700206 return ok;
207}
208
Svet Ganov33761132021-05-13 22:51:08 +0000209bool captureMediaOutputAllowed(const AttributionSourceState& attributionSource) {
210 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
211 pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(attributionSource.pid));
Kevin Rocard36b17552019-03-07 18:48:07 -0800212 if (isAudioServerOrRootUid(uid)) return true;
213 static const String16 sCaptureMediaOutput("android.permission.CAPTURE_MEDIA_OUTPUT");
214 bool ok = PermissionCache::checkPermission(sCaptureMediaOutput, pid, uid);
215 if (!ok) ALOGE("Request requires android.permission.CAPTURE_MEDIA_OUTPUT");
216 return ok;
217}
218
Svet Ganov33761132021-05-13 22:51:08 +0000219bool captureTunerAudioInputAllowed(const AttributionSourceState& attributionSource) {
220 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
221 pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(attributionSource.pid));
Hayden Gomesb7429922020-12-11 13:59:18 -0800222 if (isAudioServerOrRootUid(uid)) return true;
223 static const String16 sCaptureTunerAudioInput("android.permission.CAPTURE_TUNER_AUDIO_INPUT");
224 bool ok = PermissionCache::checkPermission(sCaptureTunerAudioInput, pid, uid);
225 if (!ok) ALOGV("Request requires android.permission.CAPTURE_TUNER_AUDIO_INPUT");
226 return ok;
227}
228
Svet Ganov33761132021-05-13 22:51:08 +0000229bool captureVoiceCommunicationOutputAllowed(const AttributionSourceState& attributionSource) {
230 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
231 uid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(attributionSource.pid));
Nadav Bardbf0a2e2020-01-16 23:09:25 +0200232 if (isAudioServerOrRootUid(uid)) return true;
233 static const String16 sCaptureVoiceCommOutput(
234 "android.permission.CAPTURE_VOICE_COMMUNICATION_OUTPUT");
235 bool ok = PermissionCache::checkPermission(sCaptureVoiceCommOutput, pid, uid);
236 if (!ok) ALOGE("Request requires android.permission.CAPTURE_VOICE_COMMUNICATION_OUTPUT");
237 return ok;
238}
239
Carter Hsua3abb402021-10-26 11:11:20 +0800240bool accessUltrasoundAllowed(const AttributionSourceState& attributionSource) {
241 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
242 uid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(attributionSource.pid));
243 if (isAudioServerOrRootUid(uid)) return true;
244 static const String16 sAccessUltrasound(
245 "android.permission.ACCESS_ULTRASOUND");
246 bool ok = PermissionCache::checkPermission(sAccessUltrasound, pid, uid);
247 if (!ok) ALOGE("Request requires android.permission.ACCESS_ULTRASOUND");
248 return ok;
249}
250
Svet Ganov33761132021-05-13 22:51:08 +0000251bool captureHotwordAllowed(const AttributionSourceState& attributionSource) {
Eric Laurent7504b9e2017-08-15 18:17:26 -0700252 // CAPTURE_AUDIO_HOTWORD permission implies RECORD_AUDIO permission
Svet Ganov33761132021-05-13 22:51:08 +0000253 bool ok = recordingAllowed(attributionSource);
Eric Laurent7504b9e2017-08-15 18:17:26 -0700254
255 if (ok) {
256 static const String16 sCaptureHotwordAllowed("android.permission.CAPTURE_AUDIO_HOTWORD");
Ahaan Ugaleb18227c2021-06-07 11:52:54 -0700257 // Use PermissionChecker, which includes some logic for allowing the isolated
258 // HotwordDetectionService to hold certain permissions.
259 permission::PermissionChecker permissionChecker;
260 ok = (permissionChecker.checkPermissionForPreflight(
261 sCaptureHotwordAllowed, attributionSource, String16(),
262 AppOpsManager::OP_NONE) != permission::PermissionChecker::PERMISSION_HARD_DENIED);
Eric Laurent7504b9e2017-08-15 18:17:26 -0700263 }
Eric Laurent6ede98f2019-06-11 14:50:30 -0700264 if (!ok) ALOGV("android.permission.CAPTURE_AUDIO_HOTWORD");
Eric Laurent9a54bc22013-09-09 09:08:44 -0700265 return ok;
266}
267
Glenn Kasten44deb052012-02-05 18:09:08 -0800268bool settingsAllowed() {
Andy Hung4ef19fa2018-05-15 19:35:29 -0700269 // given this is a permission check, could this be isAudioServerOrRootUid()?
270 if (isAudioServerUid(IPCThreadState::self()->getCallingUid())) return true;
Glenn Kasten44deb052012-02-05 18:09:08 -0800271 static const String16 sAudioSettings("android.permission.MODIFY_AUDIO_SETTINGS");
Svet Ganovbe71aa22015-04-28 12:06:02 -0700272 // IMPORTANT: Use PermissionCache - not a runtime permission and may not change.
273 bool ok = PermissionCache::checkCallingPermission(sAudioSettings);
Glenn Kasten44deb052012-02-05 18:09:08 -0800274 if (!ok) ALOGE("Request requires android.permission.MODIFY_AUDIO_SETTINGS");
275 return ok;
276}
277
Eric Laurent5284ed52014-05-29 14:37:38 -0700278bool modifyAudioRoutingAllowed() {
Svet Ganov33761132021-05-13 22:51:08 +0000279 return modifyAudioRoutingAllowed(getCallingAttributionSource());
Eric Laurent8a1095a2019-11-08 14:44:16 -0800280}
281
Svet Ganov33761132021-05-13 22:51:08 +0000282bool modifyAudioRoutingAllowed(const AttributionSourceState& attributionSource) {
283 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
284 pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(attributionSource.pid));
Eric Laurent8a1095a2019-11-08 14:44:16 -0800285 if (isAudioServerUid(IPCThreadState::self()->getCallingUid())) return true;
Svet Ganovbe71aa22015-04-28 12:06:02 -0700286 // IMPORTANT: Use PermissionCache - not a runtime permission and may not change.
Eric Laurent8a1095a2019-11-08 14:44:16 -0800287 bool ok = PermissionCache::checkPermission(sModifyAudioRouting, pid, uid);
288 if (!ok) ALOGE("%s(): android.permission.MODIFY_AUDIO_ROUTING denied for uid %d",
289 __func__, uid);
Eric Laurent5284ed52014-05-29 14:37:38 -0700290 return ok;
291}
292
Ari Hausman-Cohen433722e2018-04-24 14:25:22 -0700293bool modifyDefaultAudioEffectsAllowed() {
Svet Ganov33761132021-05-13 22:51:08 +0000294 return modifyDefaultAudioEffectsAllowed(getCallingAttributionSource());
Eric Laurent3f75a5b2019-11-12 15:55:51 -0800295}
296
Svet Ganov33761132021-05-13 22:51:08 +0000297bool modifyDefaultAudioEffectsAllowed(const AttributionSourceState& attributionSource) {
298 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
299 pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(attributionSource.pid));
Eric Laurent3f75a5b2019-11-12 15:55:51 -0800300 if (isAudioServerUid(IPCThreadState::self()->getCallingUid())) return true;
301
Ari Hausman-Cohen433722e2018-04-24 14:25:22 -0700302 static const String16 sModifyDefaultAudioEffectsAllowed(
303 "android.permission.MODIFY_DEFAULT_AUDIO_EFFECTS");
304 // IMPORTANT: Use PermissionCache - not a runtime permission and may not change.
Eric Laurent3f75a5b2019-11-12 15:55:51 -0800305 bool ok = PermissionCache::checkPermission(sModifyDefaultAudioEffectsAllowed, pid, uid);
306 ALOGE_IF(!ok, "%s(): android.permission.MODIFY_DEFAULT_AUDIO_EFFECTS denied for uid %d",
307 __func__, uid);
Ari Hausman-Cohen433722e2018-04-24 14:25:22 -0700308 return ok;
309}
310
Glenn Kasten44deb052012-02-05 18:09:08 -0800311bool dumpAllowed() {
Glenn Kasten44deb052012-02-05 18:09:08 -0800312 static const String16 sDump("android.permission.DUMP");
Svet Ganovbe71aa22015-04-28 12:06:02 -0700313 // IMPORTANT: Use PermissionCache - not a runtime permission and may not change.
Glenn Kasten44deb052012-02-05 18:09:08 -0800314 bool ok = PermissionCache::checkCallingPermission(sDump);
315 // convention is for caller to dump an error message to fd instead of logging here
316 //if (!ok) ALOGE("Request requires android.permission.DUMP");
317 return ok;
318}
319
Svet Ganov33761132021-05-13 22:51:08 +0000320bool modifyPhoneStateAllowed(const AttributionSourceState& attributionSource) {
321 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
322 pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(attributionSource.pid));
Svet Ganov5b81f552018-03-02 09:21:30 -0800323 bool ok = PermissionCache::checkPermission(sModifyPhoneState, pid, uid);
Eric Laurent42984412019-05-09 17:57:03 -0700324 ALOGE_IF(!ok, "Request requires %s", String8(sModifyPhoneState).c_str());
325 return ok;
326}
327
328// privileged behavior needed by Dialer, Settings, SetupWizard and CellBroadcastReceiver
Svet Ganov33761132021-05-13 22:51:08 +0000329bool bypassInterruptionPolicyAllowed(const AttributionSourceState& attributionSource) {
330 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
331 pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(attributionSource.pid));
Eric Laurent42984412019-05-09 17:57:03 -0700332 static const String16 sWriteSecureSettings("android.permission.WRITE_SECURE_SETTINGS");
333 bool ok = PermissionCache::checkPermission(sModifyPhoneState, pid, uid)
334 || PermissionCache::checkPermission(sWriteSecureSettings, pid, uid)
335 || PermissionCache::checkPermission(sModifyAudioRouting, pid, uid);
336 ALOGE_IF(!ok, "Request requires %s or %s",
337 String8(sModifyPhoneState).c_str(), String8(sWriteSecureSettings).c_str());
Nadav Bar766fb022018-01-07 12:18:03 +0200338 return ok;
339}
340
Eric Laurentb0eff0f2021-11-09 16:05:49 +0100341bool callAudioInterceptionAllowed(const AttributionSourceState& attributionSource) {
342 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
343 pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(attributionSource.pid));
344
345 // IMPORTANT: Use PermissionCache - not a runtime permission and may not change.
346 bool ok = PermissionCache::checkPermission(sCallAudioInterception, pid, uid);
Eric Laurenta6244a02021-12-14 14:05:25 +0100347 if (!ok) ALOGV("%s(): android.permission.CALL_AUDIO_INTERCEPTION denied for uid %d",
Eric Laurentb0eff0f2021-11-09 16:05:49 +0100348 __func__, uid);
349 return ok;
350}
351
Svet Ganov33761132021-05-13 22:51:08 +0000352AttributionSourceState getCallingAttributionSource() {
353 AttributionSourceState attributionSource = AttributionSourceState();
354 attributionSource.pid = VALUE_OR_FATAL(legacy2aidl_pid_t_int32_t(
355 IPCThreadState::self()->getCallingPid()));
356 attributionSource.uid = VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t(
357 IPCThreadState::self()->getCallingUid()));
358 attributionSource.token = sp<BBinder>::make();
359 return attributionSource;
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700360}
361
Eric Laurent269acb42021-04-23 16:53:22 +0200362void purgePermissionCache() {
363 PermissionCache::purgeCache();
364}
365
Eric Laurent9b11c022018-06-06 19:19:22 -0700366status_t checkIMemory(const sp<IMemory>& iMemory)
367{
368 if (iMemory == 0) {
369 ALOGE("%s check failed: NULL IMemory pointer", __FUNCTION__);
370 return BAD_VALUE;
371 }
372
373 sp<IMemoryHeap> heap = iMemory->getMemory();
374 if (heap == 0) {
375 ALOGE("%s check failed: NULL heap pointer", __FUNCTION__);
376 return BAD_VALUE;
377 }
378
379 off_t size = lseek(heap->getHeapID(), 0, SEEK_END);
380 lseek(heap->getHeapID(), 0, SEEK_SET);
381
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -0700382 if (iMemory->unsecurePointer() == NULL || size < (off_t)iMemory->size()) {
Eric Laurent9b11c022018-06-06 19:19:22 -0700383 ALOGE("%s check failed: pointer %p size %zu fd size %u",
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -0700384 __FUNCTION__, iMemory->unsecurePointer(), iMemory->size(), (uint32_t)size);
Eric Laurent9b11c022018-06-06 19:19:22 -0700385 return BAD_VALUE;
386 }
387
388 return NO_ERROR;
389}
390
Eric Laurent24df2832023-10-13 18:13:43 +0200391/**
392 * Determines if the MAC address in Bluetooth device descriptors returned by APIs of
393 * a native audio service (audio flinger, audio policy) must be anonymized.
394 * MAC addresses returned to system server or apps with BLUETOOTH_CONNECT permission
395 * are not anonymized.
396 *
397 * @param attributionSource The attribution source of the calling app.
398 * @param caller string identifying the caller for logging.
399 * @return true if the MAC addresses must be anonymized, false otherwise.
400 */
401bool mustAnonymizeBluetoothAddress(
402 const AttributionSourceState& attributionSource, const String16& caller) {
Eric Laurent24df2832023-10-13 18:13:43 +0200403 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
404 if (isAudioServerOrSystemServerUid(uid)) {
405 return false;
406 }
407 const std::optional<AttributionSourceState> resolvedAttributionSource =
408 resolveAttributionSource(attributionSource);
409 if (!resolvedAttributionSource.has_value()) {
410 return true;
411 }
412 permission::PermissionChecker permissionChecker;
413 return permissionChecker.checkPermissionForPreflightFromDatasource(
414 sAndroidPermissionBluetoothConnect, resolvedAttributionSource.value(), caller,
415 AppOpsManager::OP_BLUETOOTH_CONNECT)
416 != permission::PermissionChecker::PERMISSION_GRANTED;
417}
418
419/**
420 * Modifies the passed MAC address string in place for consumption by unprivileged clients.
421 * the string is assumed to have a valid MAC address format.
422 * the anonymzation must be kept in sync with toAnonymizedAddress() in BluetoothUtils.java
423 *
424 * @param address input/output the char string contining the MAC address to anonymize.
425 */
426void anonymizeBluetoothAddress(char *address) {
427 if (address == nullptr || strlen(address) != strlen("AA:BB:CC:DD:EE:FF")) {
428 return;
429 }
430 memcpy(address, "XX:XX:XX:XX", strlen("XX:XX:XX:XX"));
431}
432
Oreste Salerno703ec262020-12-17 16:38:38 +0100433sp<content::pm::IPackageManagerNative> MediaPackageManager::retrievePackageManager() {
Kevin Rocard8be94972019-02-22 13:26:25 -0800434 const sp<IServiceManager> sm = defaultServiceManager();
435 if (sm == nullptr) {
436 ALOGW("%s: failed to retrieve defaultServiceManager", __func__);
Ricardo Correa57a37692020-03-23 17:27:25 -0700437 return nullptr;
Kevin Rocard8be94972019-02-22 13:26:25 -0800438 }
439 sp<IBinder> packageManager = sm->checkService(String16(nativePackageManagerName));
440 if (packageManager == nullptr) {
441 ALOGW("%s: failed to retrieve native package manager", __func__);
Ricardo Correa57a37692020-03-23 17:27:25 -0700442 return nullptr;
Kevin Rocard8be94972019-02-22 13:26:25 -0800443 }
Ricardo Correa57a37692020-03-23 17:27:25 -0700444 return interface_cast<content::pm::IPackageManagerNative>(packageManager);
Kevin Rocard8be94972019-02-22 13:26:25 -0800445}
446
447std::optional<bool> MediaPackageManager::doIsAllowed(uid_t uid) {
448 if (mPackageManager == nullptr) {
Ricardo Correa57a37692020-03-23 17:27:25 -0700449 /** Can not fetch package manager at construction it may not yet be registered. */
Oreste Salerno703ec262020-12-17 16:38:38 +0100450 mPackageManager = retrievePackageManager();
Ricardo Correa57a37692020-03-23 17:27:25 -0700451 if (mPackageManager == nullptr) {
452 ALOGW("%s: Playback capture is denied as package manager is not reachable", __func__);
453 return std::nullopt;
454 }
Kevin Rocard8be94972019-02-22 13:26:25 -0800455 }
456
Oreste Salerno703ec262020-12-17 16:38:38 +0100457 // Retrieve package names for the UID and transform to a std::vector<std::string>.
458 Vector<String16> str16PackageNames;
459 PermissionController{}.getPackagesForUid(uid, str16PackageNames);
Kevin Rocard8be94972019-02-22 13:26:25 -0800460 std::vector<std::string> packageNames;
Oreste Salerno703ec262020-12-17 16:38:38 +0100461 for (const auto& str16PackageName : str16PackageNames) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +0000462 packageNames.emplace_back(String8(str16PackageName).c_str());
Kevin Rocard8be94972019-02-22 13:26:25 -0800463 }
464 if (packageNames.empty()) {
465 ALOGW("%s: Playback capture for uid %u is denied as no package name could be retrieved "
Oreste Salerno703ec262020-12-17 16:38:38 +0100466 "from the package manager.", __func__, uid);
Kevin Rocard8be94972019-02-22 13:26:25 -0800467 return std::nullopt;
468 }
469 std::vector<bool> isAllowed;
Oreste Salerno703ec262020-12-17 16:38:38 +0100470 auto status = mPackageManager->isAudioPlaybackCaptureAllowed(packageNames, &isAllowed);
Kevin Rocard8be94972019-02-22 13:26:25 -0800471 if (!status.isOk()) {
472 ALOGW("%s: Playback capture is denied for uid %u as the manifest property could not be "
473 "retrieved from the package manager: %s", __func__, uid, status.toString8().c_str());
474 return std::nullopt;
475 }
476 if (packageNames.size() != isAllowed.size()) {
477 ALOGW("%s: Playback capture is denied for uid %u as the package manager returned incoherent"
478 " response size: %zu != %zu", __func__, uid, packageNames.size(), isAllowed.size());
479 return std::nullopt;
480 }
481
482 // Zip together packageNames and isAllowed for debug logs
483 Packages& packages = mDebugLog[uid];
484 packages.resize(packageNames.size()); // Reuse all objects
485 std::transform(begin(packageNames), end(packageNames), begin(isAllowed),
486 begin(packages), [] (auto& name, bool isAllowed) -> Package {
487 return {std::move(name), isAllowed};
488 });
489
490 // Only allow playback record if all packages in this UID allow it
491 bool playbackCaptureAllowed = std::all_of(begin(isAllowed), end(isAllowed),
492 [](bool b) { return b; });
493
494 return playbackCaptureAllowed;
495}
496
497void MediaPackageManager::dump(int fd, int spaces) const {
498 dprintf(fd, "%*sAllow playback capture log:\n", spaces, "");
499 if (mPackageManager == nullptr) {
500 dprintf(fd, "%*sNo package manager\n", spaces + 2, "");
501 }
502 dprintf(fd, "%*sPackage manager errors: %u\n", spaces + 2, "", mPackageManagerErrors);
503
504 for (const auto& uidCache : mDebugLog) {
505 for (const auto& package : std::get<Packages>(uidCache)) {
506 dprintf(fd, "%*s- uid=%5u, allowPlaybackCapture=%s, packageName=%s\n", spaces + 2, "",
507 std::get<const uid_t>(uidCache),
508 package.playbackCaptureAllowed ? "true " : "false",
509 package.name.c_str());
510 }
511 }
512}
513
Andy Hunga85efab2019-12-23 11:41:29 -0800514// How long we hold info before we re-fetch it (24 hours) if we found it previously.
515static constexpr nsecs_t INFO_EXPIRATION_NS = 24 * 60 * 60 * NANOS_PER_SECOND;
516// Maximum info records we retain before clearing everything.
517static constexpr size_t INFO_CACHE_MAX = 1000;
518
519// The original code is from MediaMetricsService.cpp.
520mediautils::UidInfo::Info mediautils::UidInfo::getInfo(uid_t uid)
521{
522 const nsecs_t now = systemTime(SYSTEM_TIME_REALTIME);
523 struct mediautils::UidInfo::Info info;
524 {
525 std::lock_guard _l(mLock);
526 auto it = mInfoMap.find(uid);
527 if (it != mInfoMap.end()) {
528 info = it->second;
529 ALOGV("%s: uid %d expiration %lld now %lld",
530 __func__, uid, (long long)info.expirationNs, (long long)now);
531 if (info.expirationNs <= now) {
532 // purge the stale entry and fall into re-fetching
533 ALOGV("%s: entry for uid %d expired, now %lld",
534 __func__, uid, (long long)now);
535 mInfoMap.erase(it);
536 info.uid = (uid_t)-1; // this is always fully overwritten
537 }
538 }
539 }
540
541 // if we did not find it in our map, look it up
542 if (info.uid == (uid_t)(-1)) {
543 sp<IServiceManager> sm = defaultServiceManager();
544 sp<content::pm::IPackageManagerNative> package_mgr;
545 if (sm.get() == nullptr) {
546 ALOGE("%s: Cannot find service manager", __func__);
547 } else {
548 sp<IBinder> binder = sm->getService(String16("package_native"));
549 if (binder.get() == nullptr) {
550 ALOGE("%s: Cannot find package_native", __func__);
551 } else {
552 package_mgr = interface_cast<content::pm::IPackageManagerNative>(binder);
553 }
554 }
555
556 // find package name
557 std::string pkg;
558 if (package_mgr != nullptr) {
559 std::vector<std::string> names;
560 binder::Status status = package_mgr->getNamesForUids({(int)uid}, &names);
561 if (!status.isOk()) {
562 ALOGE("%s: getNamesForUids failed: %s",
563 __func__, status.exceptionMessage().c_str());
564 } else {
565 if (!names[0].empty()) {
566 pkg = names[0].c_str();
567 }
568 }
569 }
570
571 if (pkg.empty()) {
572 struct passwd pw{}, *result;
573 char buf[8192]; // extra buffer space - should exceed what is
574 // required in struct passwd_pw (tested),
575 // and even then this is only used in backup
576 // when the package manager is unavailable.
577 if (getpwuid_r(uid, &pw, buf, sizeof(buf), &result) == 0
578 && result != nullptr
579 && result->pw_name != nullptr) {
580 pkg = result->pw_name;
581 }
582 }
583
584 // strip any leading "shared:" strings that came back
585 if (pkg.compare(0, 7, "shared:") == 0) {
586 pkg.erase(0, 7);
587 }
588
589 // determine how pkg was installed and the versionCode
590 std::string installer;
591 int64_t versionCode = 0;
592 bool notFound = false;
593 if (pkg.empty()) {
594 pkg = std::to_string(uid); // not found
595 notFound = true;
596 } else if (strchr(pkg.c_str(), '.') == nullptr) {
597 // not of form 'com.whatever...'; assume internal
598 // so we don't need to look it up in package manager.
Andy Hunge6a65ac2020-01-08 16:56:17 -0800599 } else if (strncmp(pkg.c_str(), "android.", 8) == 0) {
600 // android.* packages are assumed fine
Andy Hunga85efab2019-12-23 11:41:29 -0800601 } else if (package_mgr.get() != nullptr) {
602 String16 pkgName16(pkg.c_str());
603 binder::Status status = package_mgr->getInstallerForPackage(pkgName16, &installer);
604 if (!status.isOk()) {
605 ALOGE("%s: getInstallerForPackage failed: %s",
606 __func__, status.exceptionMessage().c_str());
607 }
608
609 // skip if we didn't get an installer
610 if (status.isOk()) {
611 status = package_mgr->getVersionCodeForPackage(pkgName16, &versionCode);
612 if (!status.isOk()) {
613 ALOGE("%s: getVersionCodeForPackage failed: %s",
614 __func__, status.exceptionMessage().c_str());
615 }
616 }
617
618 ALOGV("%s: package '%s' installed by '%s' versioncode %lld",
619 __func__, pkg.c_str(), installer.c_str(), (long long)versionCode);
620 }
621
622 // add it to the map, to save a subsequent lookup
623 std::lock_guard _l(mLock);
624 // first clear if we have too many cached elements. This would be rare.
625 if (mInfoMap.size() >= INFO_CACHE_MAX) mInfoMap.clear();
626
627 // always overwrite
628 info.uid = uid;
629 info.package = std::move(pkg);
630 info.installer = std::move(installer);
631 info.versionCode = versionCode;
632 info.expirationNs = now + (notFound ? 0 : INFO_EXPIRATION_NS);
633 ALOGV("%s: adding uid %d package '%s' expirationNs: %lld",
634 __func__, uid, info.package.c_str(), (long long)info.expirationNs);
635 mInfoMap[uid] = info;
636 }
637 return info;
638}
639
Glenn Kasten44deb052012-02-05 18:09:08 -0800640} // namespace android