blob: e13f8f758139a1e0fbd2f88ae7c5488ecfea50b6 [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
guochuang0c55eae2024-03-08 19:42:54 +080017//#define LOG_NDEBUG 0
Eric Laurent9b11c022018-06-06 19:19:22 -070018#define LOG_TAG "ServiceUtilities"
19
Andy Hunga85efab2019-12-23 11:41:29 -080020#include <audio_utils/clock.h>
Svet Ganovbe71aa22015-04-28 12:06:02 -070021#include <binder/AppOpsManager.h>
Glenn Kasten44deb052012-02-05 18:09:08 -080022#include <binder/IPCThreadState.h>
23#include <binder/IServiceManager.h>
24#include <binder/PermissionCache.h>
Andy Hungab7ef302018-05-15 19:35:29 -070025#include "mediautils/ServiceUtilities.h"
Nate Myrene69cada2020-12-10 10:00:36 -080026#include <system/audio-hal-enums.h>
Philip P. Moltmannbda45752020-07-17 16:41:18 -070027#include <media/AidlConversion.h>
28#include <media/AidlConversionUtil.h>
Svet Ganov33761132021-05-13 22:51:08 +000029#include <android/content/AttributionSourceState.h>
Glenn Kasten44deb052012-02-05 18:09:08 -080030
Atneya Nair07971a32024-10-04 14:33:21 -070031#include <iterator>
Chaitanya Cheemala (xWF)e1dfc0f2024-10-08 09:41:45 +000032#include <algorithm>
Andy Hunga85efab2019-12-23 11:41:29 -080033#include <pwd.h>
Kevin Rocard8be94972019-02-22 13:26:25 -080034
Svet Ganovbe71aa22015-04-28 12:06:02 -070035/* When performing permission checks we do not use permission cache for
36 * runtime permissions (protection level dangerous) as they may change at
37 * runtime. All other permissions (protection level normal and dangerous)
38 * can be cached as they never change. Of course all permission checked
39 * here are platform defined.
40 */
41
Glenn Kasten44deb052012-02-05 18:09:08 -080042namespace android {
43
Atneya Nairdb6ef1e2024-09-16 20:26:30 +000044namespace {
45constexpr auto PERMISSION_HARD_DENIED = permission::PermissionChecker::PERMISSION_HARD_DENIED;
46}
47
Svet Ganov33761132021-05-13 22:51:08 +000048using content::AttributionSourceState;
Philip P. Moltmannbda45752020-07-17 16:41:18 -070049
Svet Ganov5b81f552018-03-02 09:21:30 -080050static const String16 sAndroidPermissionRecordAudio("android.permission.RECORD_AUDIO");
Eric Laurent42984412019-05-09 17:57:03 -070051static const String16 sModifyPhoneState("android.permission.MODIFY_PHONE_STATE");
52static const String16 sModifyAudioRouting("android.permission.MODIFY_AUDIO_ROUTING");
Eric Laurentb0eff0f2021-11-09 16:05:49 +010053static const String16 sCallAudioInterception("android.permission.CALL_AUDIO_INTERCEPTION");
Svet Ganov5b81f552018-03-02 09:21:30 -080054
Svet Ganov5b81f552018-03-02 09:21:30 -080055static String16 resolveCallingPackage(PermissionController& permissionController,
Philip P. Moltmannbda45752020-07-17 16:41:18 -070056 const std::optional<String16> opPackageName, uid_t uid) {
57 if (opPackageName.has_value() && opPackageName.value().size() > 0) {
58 return opPackageName.value();
Svet Ganovbe71aa22015-04-28 12:06:02 -070059 }
Svet Ganovbe71aa22015-04-28 12:06:02 -070060 // In some cases the calling code has no access to the package it runs under.
61 // For example, code using the wilhelm framework's OpenSL-ES APIs. In this
62 // case we will get the packages for the calling UID and pick the first one
63 // for attributing the app op. This will work correctly for runtime permissions
64 // as for legacy apps we will toggle the app op for all packages in the UID.
65 // The caveat is that the operation may be attributed to the wrong package and
66 // stats based on app ops may be slightly off.
Svet Ganov5b81f552018-03-02 09:21:30 -080067 Vector<String16> packages;
68 permissionController.getPackagesForUid(uid, packages);
69 if (packages.isEmpty()) {
70 ALOGE("No packages for uid %d", uid);
Philip P. Moltmannbda45752020-07-17 16:41:18 -070071 return String16();
Svet Ganov5b81f552018-03-02 09:21:30 -080072 }
73 return packages[0];
74}
Svetoslav Ganov599ec462018-03-01 22:19:55 +000075
Eric Laurent45e16b92021-05-20 11:10:47 +020076int32_t getOpForSource(audio_source_t source) {
Nate Myrene69cada2020-12-10 10:00:36 -080077 switch (source) {
78 case AUDIO_SOURCE_HOTWORD:
79 return AppOpsManager::OP_RECORD_AUDIO_HOTWORD;
Mickey Keeley90d657d2021-10-20 18:06:38 -070080 case AUDIO_SOURCE_ECHO_REFERENCE: // fallthrough
Nate Myrene69cada2020-12-10 10:00:36 -080081 case AUDIO_SOURCE_REMOTE_SUBMIX:
82 return AppOpsManager::OP_RECORD_AUDIO_OUTPUT;
Nate Myrenf7c88352021-04-12 14:41:49 -070083 case AUDIO_SOURCE_VOICE_DOWNLINK:
84 return AppOpsManager::OP_RECORD_INCOMING_PHONE_AUDIO;
Nate Myrene69cada2020-12-10 10:00:36 -080085 case AUDIO_SOURCE_DEFAULT:
86 default:
87 return AppOpsManager::OP_RECORD_AUDIO;
88 }
89}
90
Svet Ganov33761132021-05-13 22:51:08 +000091std::optional<AttributionSourceState> resolveAttributionSource(
Marvin Raminb03b49f2024-04-04 16:25:31 +020092 const AttributionSourceState& callerAttributionSource, const uint32_t virtualDeviceId) {
Svet Ganov33761132021-05-13 22:51:08 +000093 AttributionSourceState nextAttributionSource = callerAttributionSource;
94
95 if (!nextAttributionSource.packageName.has_value()) {
96 nextAttributionSource = AttributionSourceState(nextAttributionSource);
97 PermissionController permissionController;
98 const uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(nextAttributionSource.uid));
99 nextAttributionSource.packageName = VALUE_OR_FATAL(legacy2aidl_String16_string(
100 resolveCallingPackage(permissionController, VALUE_OR_FATAL(
101 aidl2legacy_string_view_String16(nextAttributionSource.packageName.value_or(""))),
102 uid)));
103 if (!nextAttributionSource.packageName.has_value()) {
104 return std::nullopt;
105 }
106 }
Marvin Raminb03b49f2024-04-04 16:25:31 +0200107 nextAttributionSource.deviceId = virtualDeviceId;
Svet Ganov33761132021-05-13 22:51:08 +0000108
109 AttributionSourceState myAttributionSource;
110 myAttributionSource.uid = VALUE_OR_FATAL(android::legacy2aidl_uid_t_int32_t(getuid()));
111 myAttributionSource.pid = VALUE_OR_FATAL(android::legacy2aidl_pid_t_int32_t(getpid()));
Nate Myrene84d6912022-11-10 14:09:34 -0800112 // Create a static token for audioserver requests, which identifies the
113 // audioserver to the app ops system
114 static sp<BBinder> appOpsToken = sp<BBinder>::make();
115 myAttributionSource.token = appOpsToken;
Marvin Raminb03b49f2024-04-04 16:25:31 +0200116 myAttributionSource.deviceId = virtualDeviceId;
Svet Ganov33761132021-05-13 22:51:08 +0000117 myAttributionSource.next.push_back(nextAttributionSource);
118
119 return std::optional<AttributionSourceState>{myAttributionSource};
120}
121
Atneya Nairdb6ef1e2024-09-16 20:26:30 +0000122 static int checkRecordingInternal(const AttributionSourceState &attributionSource,
Marvin Ramine5a122d2023-12-07 13:57:59 +0100123 const uint32_t virtualDeviceId,
124 const String16 &msg, bool start, audio_source_t source) {
Eric Laurent58a0dd82019-10-24 12:42:17 -0700125 // Okay to not track in app ops as audio server or media server is us and if
Svet Ganov5b81f552018-03-02 09:21:30 -0800126 // device is rooted security model is considered compromised.
Jeffrey Carlyle62cc92b2019-09-17 11:15:15 -0700127 // system_server loses its RECORD_AUDIO permission when a secondary
128 // user is active, but it is a core system service so let it through.
129 // TODO(b/141210120): UserManager.DISALLOW_RECORD_AUDIO should not affect system user 0
Svet Ganov33761132021-05-13 22:51:08 +0000130 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent58a0dd82019-10-24 12:42:17 -0700131 if (isAudioServerOrMediaServerOrSystemServerOrRootUid(uid)) return true;
Svetoslav Ganov599ec462018-03-01 22:19:55 +0000132
Svet Ganov5b81f552018-03-02 09:21:30 -0800133 // We specify a pid and uid here as mediaserver (aka MediaRecorder or StageFrightRecorder)
Svet Ganov33761132021-05-13 22:51:08 +0000134 // may open a record track on behalf of a client. Note that pid may be a tid.
Svet Ganov5b81f552018-03-02 09:21:30 -0800135 // IMPORTANT: DON'T USE PermissionCache - RUNTIME PERMISSIONS CHANGE.
Marvin Ramine5a122d2023-12-07 13:57:59 +0100136 std::optional<AttributionSourceState> resolvedAttributionSource =
Marvin Raminb03b49f2024-04-04 16:25:31 +0200137 resolveAttributionSource(attributionSource, virtualDeviceId);
Svet Ganov33761132021-05-13 22:51:08 +0000138 if (!resolvedAttributionSource.has_value()) {
Svet Ganov5b81f552018-03-02 09:21:30 -0800139 return false;
140 }
141
Svet Ganov33761132021-05-13 22:51:08 +0000142 const int32_t attributedOpCode = getOpForSource(source);
Svetoslav Ganov599ec462018-03-01 22:19:55 +0000143
Svet Ganov33761132021-05-13 22:51:08 +0000144 permission::PermissionChecker permissionChecker;
Atneya Nairdb6ef1e2024-09-16 20:26:30 +0000145 int permitted;
Svet Ganov5b81f552018-03-02 09:21:30 -0800146 if (start) {
Atneya Nairdb6ef1e2024-09-16 20:26:30 +0000147 permitted = permissionChecker.checkPermissionForStartDataDeliveryFromDatasource(
Svet Ganov33761132021-05-13 22:51:08 +0000148 sAndroidPermissionRecordAudio, resolvedAttributionSource.value(), msg,
Atneya Nairdb6ef1e2024-09-16 20:26:30 +0000149 attributedOpCode);
Svet Ganov5b81f552018-03-02 09:21:30 -0800150 } else {
Atneya Nairdb6ef1e2024-09-16 20:26:30 +0000151 permitted = permissionChecker.checkPermissionForPreflightFromDatasource(
Svet Ganov33761132021-05-13 22:51:08 +0000152 sAndroidPermissionRecordAudio, resolvedAttributionSource.value(), msg,
Atneya Nairdb6ef1e2024-09-16 20:26:30 +0000153 attributedOpCode);
Svetoslav Ganov599ec462018-03-01 22:19:55 +0000154 }
155
Svet Ganov33761132021-05-13 22:51:08 +0000156 return permitted;
Glenn Kasten44deb052012-02-05 18:09:08 -0800157}
158
Marvin Ramine5a122d2023-12-07 13:57:59 +0100159static constexpr int DEVICE_ID_DEFAULT = 0;
160
161bool recordingAllowed(const AttributionSourceState &attributionSource, audio_source_t source) {
162 return checkRecordingInternal(attributionSource, DEVICE_ID_DEFAULT, String16(), /*start*/ false,
Atneya Nairdb6ef1e2024-09-16 20:26:30 +0000163 source) != PERMISSION_HARD_DENIED;
Marvin Ramine5a122d2023-12-07 13:57:59 +0100164}
165
166bool recordingAllowed(const AttributionSourceState &attributionSource,
167 const uint32_t virtualDeviceId,
168 audio_source_t source) {
169 return checkRecordingInternal(attributionSource, virtualDeviceId,
Atneya Nairdb6ef1e2024-09-16 20:26:30 +0000170 String16(), /*start*/ false, source) != PERMISSION_HARD_DENIED;
Svet Ganov5b81f552018-03-02 09:21:30 -0800171}
172
Atneya Nairdb6ef1e2024-09-16 20:26:30 +0000173int startRecording(const AttributionSourceState& attributionSource,
Marvin Raminb03b49f2024-04-04 16:25:31 +0200174 const uint32_t virtualDeviceId,
175 const String16& msg,
176 audio_source_t source) {
177 return checkRecordingInternal(attributionSource, virtualDeviceId, msg, /*start*/ true,
Marvin Ramine5a122d2023-12-07 13:57:59 +0100178 source);
Svet Ganov5b81f552018-03-02 09:21:30 -0800179}
180
Marvin Raminb03b49f2024-04-04 16:25:31 +0200181void finishRecording(const AttributionSourceState &attributionSource, uint32_t virtualDeviceId,
182 audio_source_t source) {
Svet Ganov5b81f552018-03-02 09:21:30 -0800183 // Okay to not track in app ops as audio server is us and if
184 // device is rooted security model is considered compromised.
Svet Ganov33761132021-05-13 22:51:08 +0000185 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
186 if (isAudioServerOrMediaServerOrSystemServerOrRootUid(uid)) return;
Svet Ganov5b81f552018-03-02 09:21:30 -0800187
Svet Ganov33761132021-05-13 22:51:08 +0000188 // We specify a pid and uid here as mediaserver (aka MediaRecorder or StageFrightRecorder)
189 // may open a record track on behalf of a client. Note that pid may be a tid.
190 // IMPORTANT: DON'T USE PermissionCache - RUNTIME PERMISSIONS CHANGE.
191 const std::optional<AttributionSourceState> resolvedAttributionSource =
Marvin Raminb03b49f2024-04-04 16:25:31 +0200192 resolveAttributionSource(attributionSource, virtualDeviceId);
Svet Ganov33761132021-05-13 22:51:08 +0000193 if (!resolvedAttributionSource.has_value()) {
Svet Ganov5b81f552018-03-02 09:21:30 -0800194 return;
195 }
196
Svet Ganov33761132021-05-13 22:51:08 +0000197 const int32_t attributedOpCode = getOpForSource(source);
198 permission::PermissionChecker permissionChecker;
199 permissionChecker.finishDataDeliveryFromDatasource(attributedOpCode,
200 resolvedAttributionSource.value());
Svet Ganov5b81f552018-03-02 09:21:30 -0800201}
202
Svet Ganov33761132021-05-13 22:51:08 +0000203bool captureAudioOutputAllowed(const AttributionSourceState& attributionSource) {
204 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Andy Hung4ef19fa2018-05-15 19:35:29 -0700205 if (isAudioServerOrRootUid(uid)) return true;
Jeff Brown893a5642013-08-16 20:19:26 -0700206 static const String16 sCaptureAudioOutput("android.permission.CAPTURE_AUDIO_OUTPUT");
lpeter20d2e032022-06-01 19:38:44 +0800207 // Use PermissionChecker, which includes some logic for allowing the isolated
208 // HotwordDetectionService to hold certain permissions.
209 permission::PermissionChecker permissionChecker;
210 bool ok = (permissionChecker.checkPermissionForPreflight(
211 sCaptureAudioOutput, attributionSource, String16(),
212 AppOpsManager::OP_NONE) != permission::PermissionChecker::PERMISSION_HARD_DENIED);
Eric Laurent6ede98f2019-06-11 14:50:30 -0700213 if (!ok) ALOGV("Request requires android.permission.CAPTURE_AUDIO_OUTPUT");
Jeff Brown893a5642013-08-16 20:19:26 -0700214 return ok;
215}
216
Svet Ganov33761132021-05-13 22:51:08 +0000217bool captureMediaOutputAllowed(const AttributionSourceState& attributionSource) {
218 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
219 pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(attributionSource.pid));
Kevin Rocard36b17552019-03-07 18:48:07 -0800220 if (isAudioServerOrRootUid(uid)) return true;
221 static const String16 sCaptureMediaOutput("android.permission.CAPTURE_MEDIA_OUTPUT");
222 bool ok = PermissionCache::checkPermission(sCaptureMediaOutput, pid, uid);
223 if (!ok) ALOGE("Request requires android.permission.CAPTURE_MEDIA_OUTPUT");
224 return ok;
225}
226
Svet Ganov33761132021-05-13 22:51:08 +0000227bool captureTunerAudioInputAllowed(const AttributionSourceState& attributionSource) {
228 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
229 pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(attributionSource.pid));
Hayden Gomesb7429922020-12-11 13:59:18 -0800230 if (isAudioServerOrRootUid(uid)) return true;
231 static const String16 sCaptureTunerAudioInput("android.permission.CAPTURE_TUNER_AUDIO_INPUT");
232 bool ok = PermissionCache::checkPermission(sCaptureTunerAudioInput, pid, uid);
233 if (!ok) ALOGV("Request requires android.permission.CAPTURE_TUNER_AUDIO_INPUT");
234 return ok;
235}
236
Svet Ganov33761132021-05-13 22:51:08 +0000237bool captureVoiceCommunicationOutputAllowed(const AttributionSourceState& attributionSource) {
238 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
239 uid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(attributionSource.pid));
Nadav Bardbf0a2e2020-01-16 23:09:25 +0200240 if (isAudioServerOrRootUid(uid)) return true;
241 static const String16 sCaptureVoiceCommOutput(
242 "android.permission.CAPTURE_VOICE_COMMUNICATION_OUTPUT");
243 bool ok = PermissionCache::checkPermission(sCaptureVoiceCommOutput, pid, uid);
244 if (!ok) ALOGE("Request requires android.permission.CAPTURE_VOICE_COMMUNICATION_OUTPUT");
245 return ok;
246}
247
Carter Hsua3abb402021-10-26 11:11:20 +0800248bool accessUltrasoundAllowed(const AttributionSourceState& attributionSource) {
249 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
250 uid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(attributionSource.pid));
251 if (isAudioServerOrRootUid(uid)) return true;
252 static const String16 sAccessUltrasound(
253 "android.permission.ACCESS_ULTRASOUND");
254 bool ok = PermissionCache::checkPermission(sAccessUltrasound, pid, uid);
255 if (!ok) ALOGE("Request requires android.permission.ACCESS_ULTRASOUND");
256 return ok;
257}
258
Svet Ganov33761132021-05-13 22:51:08 +0000259bool captureHotwordAllowed(const AttributionSourceState& attributionSource) {
Eric Laurent7504b9e2017-08-15 18:17:26 -0700260 // CAPTURE_AUDIO_HOTWORD permission implies RECORD_AUDIO permission
Svet Ganov33761132021-05-13 22:51:08 +0000261 bool ok = recordingAllowed(attributionSource);
Eric Laurent7504b9e2017-08-15 18:17:26 -0700262
263 if (ok) {
264 static const String16 sCaptureHotwordAllowed("android.permission.CAPTURE_AUDIO_HOTWORD");
Ahaan Ugaleb18227c2021-06-07 11:52:54 -0700265 // Use PermissionChecker, which includes some logic for allowing the isolated
266 // HotwordDetectionService to hold certain permissions.
267 permission::PermissionChecker permissionChecker;
268 ok = (permissionChecker.checkPermissionForPreflight(
269 sCaptureHotwordAllowed, attributionSource, String16(),
270 AppOpsManager::OP_NONE) != permission::PermissionChecker::PERMISSION_HARD_DENIED);
Eric Laurent7504b9e2017-08-15 18:17:26 -0700271 }
Eric Laurent6ede98f2019-06-11 14:50:30 -0700272 if (!ok) ALOGV("android.permission.CAPTURE_AUDIO_HOTWORD");
Eric Laurent9a54bc22013-09-09 09:08:44 -0700273 return ok;
274}
275
Glenn Kasten44deb052012-02-05 18:09:08 -0800276bool settingsAllowed() {
Andy Hung4ef19fa2018-05-15 19:35:29 -0700277 // given this is a permission check, could this be isAudioServerOrRootUid()?
278 if (isAudioServerUid(IPCThreadState::self()->getCallingUid())) return true;
Glenn Kasten44deb052012-02-05 18:09:08 -0800279 static const String16 sAudioSettings("android.permission.MODIFY_AUDIO_SETTINGS");
Svet Ganovbe71aa22015-04-28 12:06:02 -0700280 // IMPORTANT: Use PermissionCache - not a runtime permission and may not change.
281 bool ok = PermissionCache::checkCallingPermission(sAudioSettings);
Glenn Kasten44deb052012-02-05 18:09:08 -0800282 if (!ok) ALOGE("Request requires android.permission.MODIFY_AUDIO_SETTINGS");
283 return ok;
284}
285
Eric Laurent5284ed52014-05-29 14:37:38 -0700286bool modifyAudioRoutingAllowed() {
Svet Ganov33761132021-05-13 22:51:08 +0000287 return modifyAudioRoutingAllowed(getCallingAttributionSource());
Eric Laurent8a1095a2019-11-08 14:44:16 -0800288}
289
Svet Ganov33761132021-05-13 22:51:08 +0000290bool modifyAudioRoutingAllowed(const AttributionSourceState& attributionSource) {
291 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
292 pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(attributionSource.pid));
Atneya Nairb7199082024-08-17 19:04:46 -0700293 if (isAudioServerUid(uid)) return true;
Svet Ganovbe71aa22015-04-28 12:06:02 -0700294 // IMPORTANT: Use PermissionCache - not a runtime permission and may not change.
Eric Laurent8a1095a2019-11-08 14:44:16 -0800295 bool ok = PermissionCache::checkPermission(sModifyAudioRouting, pid, uid);
296 if (!ok) ALOGE("%s(): android.permission.MODIFY_AUDIO_ROUTING denied for uid %d",
297 __func__, uid);
Eric Laurent5284ed52014-05-29 14:37:38 -0700298 return ok;
299}
300
Ari Hausman-Cohen433722e2018-04-24 14:25:22 -0700301bool modifyDefaultAudioEffectsAllowed() {
Svet Ganov33761132021-05-13 22:51:08 +0000302 return modifyDefaultAudioEffectsAllowed(getCallingAttributionSource());
Eric Laurent3f75a5b2019-11-12 15:55:51 -0800303}
304
Svet Ganov33761132021-05-13 22:51:08 +0000305bool modifyDefaultAudioEffectsAllowed(const AttributionSourceState& attributionSource) {
306 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
307 pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(attributionSource.pid));
Atneya Nairb7199082024-08-17 19:04:46 -0700308 if (isAudioServerUid(uid)) return true;
Eric Laurent3f75a5b2019-11-12 15:55:51 -0800309
Ari Hausman-Cohen433722e2018-04-24 14:25:22 -0700310 static const String16 sModifyDefaultAudioEffectsAllowed(
311 "android.permission.MODIFY_DEFAULT_AUDIO_EFFECTS");
312 // IMPORTANT: Use PermissionCache - not a runtime permission and may not change.
Eric Laurent3f75a5b2019-11-12 15:55:51 -0800313 bool ok = PermissionCache::checkPermission(sModifyDefaultAudioEffectsAllowed, pid, uid);
314 ALOGE_IF(!ok, "%s(): android.permission.MODIFY_DEFAULT_AUDIO_EFFECTS denied for uid %d",
315 __func__, uid);
Ari Hausman-Cohen433722e2018-04-24 14:25:22 -0700316 return ok;
317}
318
Glenn Kasten44deb052012-02-05 18:09:08 -0800319bool dumpAllowed() {
Glenn Kasten44deb052012-02-05 18:09:08 -0800320 static const String16 sDump("android.permission.DUMP");
Svet Ganovbe71aa22015-04-28 12:06:02 -0700321 // IMPORTANT: Use PermissionCache - not a runtime permission and may not change.
Glenn Kasten44deb052012-02-05 18:09:08 -0800322 bool ok = PermissionCache::checkCallingPermission(sDump);
323 // convention is for caller to dump an error message to fd instead of logging here
324 //if (!ok) ALOGE("Request requires android.permission.DUMP");
325 return ok;
326}
327
Svet Ganov33761132021-05-13 22:51:08 +0000328bool modifyPhoneStateAllowed(const AttributionSourceState& attributionSource) {
329 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
330 pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(attributionSource.pid));
Svet Ganov5b81f552018-03-02 09:21:30 -0800331 bool ok = PermissionCache::checkPermission(sModifyPhoneState, pid, uid);
Eric Laurent42984412019-05-09 17:57:03 -0700332 ALOGE_IF(!ok, "Request requires %s", String8(sModifyPhoneState).c_str());
333 return ok;
334}
335
336// privileged behavior needed by Dialer, Settings, SetupWizard and CellBroadcastReceiver
Svet Ganov33761132021-05-13 22:51:08 +0000337bool bypassInterruptionPolicyAllowed(const AttributionSourceState& attributionSource) {
338 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
339 pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(attributionSource.pid));
Eric Laurent42984412019-05-09 17:57:03 -0700340 static const String16 sWriteSecureSettings("android.permission.WRITE_SECURE_SETTINGS");
341 bool ok = PermissionCache::checkPermission(sModifyPhoneState, pid, uid)
342 || PermissionCache::checkPermission(sWriteSecureSettings, pid, uid)
343 || PermissionCache::checkPermission(sModifyAudioRouting, pid, uid);
344 ALOGE_IF(!ok, "Request requires %s or %s",
345 String8(sModifyPhoneState).c_str(), String8(sWriteSecureSettings).c_str());
Nadav Bar766fb022018-01-07 12:18:03 +0200346 return ok;
347}
348
Eric Laurentb0eff0f2021-11-09 16:05:49 +0100349bool callAudioInterceptionAllowed(const AttributionSourceState& attributionSource) {
350 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
351 pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(attributionSource.pid));
352
353 // IMPORTANT: Use PermissionCache - not a runtime permission and may not change.
354 bool ok = PermissionCache::checkPermission(sCallAudioInterception, pid, uid);
Eric Laurenta6244a02021-12-14 14:05:25 +0100355 if (!ok) ALOGV("%s(): android.permission.CALL_AUDIO_INTERCEPTION denied for uid %d",
Eric Laurentb0eff0f2021-11-09 16:05:49 +0100356 __func__, uid);
357 return ok;
358}
359
Svet Ganov33761132021-05-13 22:51:08 +0000360AttributionSourceState getCallingAttributionSource() {
361 AttributionSourceState attributionSource = AttributionSourceState();
362 attributionSource.pid = VALUE_OR_FATAL(legacy2aidl_pid_t_int32_t(
363 IPCThreadState::self()->getCallingPid()));
364 attributionSource.uid = VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t(
365 IPCThreadState::self()->getCallingUid()));
366 attributionSource.token = sp<BBinder>::make();
367 return attributionSource;
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700368}
369
Eric Laurent269acb42021-04-23 16:53:22 +0200370void purgePermissionCache() {
371 PermissionCache::purgeCache();
372}
373
Eric Laurent9b11c022018-06-06 19:19:22 -0700374status_t checkIMemory(const sp<IMemory>& iMemory)
375{
376 if (iMemory == 0) {
377 ALOGE("%s check failed: NULL IMemory pointer", __FUNCTION__);
378 return BAD_VALUE;
379 }
380
381 sp<IMemoryHeap> heap = iMemory->getMemory();
382 if (heap == 0) {
383 ALOGE("%s check failed: NULL heap pointer", __FUNCTION__);
384 return BAD_VALUE;
385 }
386
387 off_t size = lseek(heap->getHeapID(), 0, SEEK_END);
388 lseek(heap->getHeapID(), 0, SEEK_SET);
389
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -0700390 if (iMemory->unsecurePointer() == NULL || size < (off_t)iMemory->size()) {
Eric Laurent9b11c022018-06-06 19:19:22 -0700391 ALOGE("%s check failed: pointer %p size %zu fd size %u",
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -0700392 __FUNCTION__, iMemory->unsecurePointer(), iMemory->size(), (uint32_t)size);
Eric Laurent9b11c022018-06-06 19:19:22 -0700393 return BAD_VALUE;
394 }
395
396 return NO_ERROR;
397}
398
Oreste Salerno703ec262020-12-17 16:38:38 +0100399sp<content::pm::IPackageManagerNative> MediaPackageManager::retrievePackageManager() {
Kevin Rocard8be94972019-02-22 13:26:25 -0800400 const sp<IServiceManager> sm = defaultServiceManager();
401 if (sm == nullptr) {
402 ALOGW("%s: failed to retrieve defaultServiceManager", __func__);
Ricardo Correa57a37692020-03-23 17:27:25 -0700403 return nullptr;
Kevin Rocard8be94972019-02-22 13:26:25 -0800404 }
405 sp<IBinder> packageManager = sm->checkService(String16(nativePackageManagerName));
406 if (packageManager == nullptr) {
407 ALOGW("%s: failed to retrieve native package manager", __func__);
Ricardo Correa57a37692020-03-23 17:27:25 -0700408 return nullptr;
Kevin Rocard8be94972019-02-22 13:26:25 -0800409 }
Ricardo Correa57a37692020-03-23 17:27:25 -0700410 return interface_cast<content::pm::IPackageManagerNative>(packageManager);
Kevin Rocard8be94972019-02-22 13:26:25 -0800411}
412
413std::optional<bool> MediaPackageManager::doIsAllowed(uid_t uid) {
414 if (mPackageManager == nullptr) {
Ricardo Correa57a37692020-03-23 17:27:25 -0700415 /** Can not fetch package manager at construction it may not yet be registered. */
Oreste Salerno703ec262020-12-17 16:38:38 +0100416 mPackageManager = retrievePackageManager();
Ricardo Correa57a37692020-03-23 17:27:25 -0700417 if (mPackageManager == nullptr) {
418 ALOGW("%s: Playback capture is denied as package manager is not reachable", __func__);
419 return std::nullopt;
420 }
Kevin Rocard8be94972019-02-22 13:26:25 -0800421 }
422
Oreste Salerno703ec262020-12-17 16:38:38 +0100423 // Retrieve package names for the UID and transform to a std::vector<std::string>.
424 Vector<String16> str16PackageNames;
425 PermissionController{}.getPackagesForUid(uid, str16PackageNames);
Kevin Rocard8be94972019-02-22 13:26:25 -0800426 std::vector<std::string> packageNames;
Oreste Salerno703ec262020-12-17 16:38:38 +0100427 for (const auto& str16PackageName : str16PackageNames) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +0000428 packageNames.emplace_back(String8(str16PackageName).c_str());
Kevin Rocard8be94972019-02-22 13:26:25 -0800429 }
430 if (packageNames.empty()) {
431 ALOGW("%s: Playback capture for uid %u is denied as no package name could be retrieved "
Oreste Salerno703ec262020-12-17 16:38:38 +0100432 "from the package manager.", __func__, uid);
Kevin Rocard8be94972019-02-22 13:26:25 -0800433 return std::nullopt;
434 }
435 std::vector<bool> isAllowed;
Oreste Salerno703ec262020-12-17 16:38:38 +0100436 auto status = mPackageManager->isAudioPlaybackCaptureAllowed(packageNames, &isAllowed);
Kevin Rocard8be94972019-02-22 13:26:25 -0800437 if (!status.isOk()) {
438 ALOGW("%s: Playback capture is denied for uid %u as the manifest property could not be "
439 "retrieved from the package manager: %s", __func__, uid, status.toString8().c_str());
440 return std::nullopt;
441 }
442 if (packageNames.size() != isAllowed.size()) {
443 ALOGW("%s: Playback capture is denied for uid %u as the package manager returned incoherent"
444 " response size: %zu != %zu", __func__, uid, packageNames.size(), isAllowed.size());
445 return std::nullopt;
446 }
447
448 // Zip together packageNames and isAllowed for debug logs
449 Packages& packages = mDebugLog[uid];
450 packages.resize(packageNames.size()); // Reuse all objects
451 std::transform(begin(packageNames), end(packageNames), begin(isAllowed),
452 begin(packages), [] (auto& name, bool isAllowed) -> Package {
453 return {std::move(name), isAllowed};
454 });
455
456 // Only allow playback record if all packages in this UID allow it
457 bool playbackCaptureAllowed = std::all_of(begin(isAllowed), end(isAllowed),
458 [](bool b) { return b; });
459
460 return playbackCaptureAllowed;
461}
462
463void MediaPackageManager::dump(int fd, int spaces) const {
464 dprintf(fd, "%*sAllow playback capture log:\n", spaces, "");
465 if (mPackageManager == nullptr) {
466 dprintf(fd, "%*sNo package manager\n", spaces + 2, "");
467 }
468 dprintf(fd, "%*sPackage manager errors: %u\n", spaces + 2, "", mPackageManagerErrors);
469
470 for (const auto& uidCache : mDebugLog) {
471 for (const auto& package : std::get<Packages>(uidCache)) {
472 dprintf(fd, "%*s- uid=%5u, allowPlaybackCapture=%s, packageName=%s\n", spaces + 2, "",
473 std::get<const uid_t>(uidCache),
474 package.playbackCaptureAllowed ? "true " : "false",
475 package.name.c_str());
476 }
477 }
478}
479
Andy Hungb26a1c82024-08-30 11:54:40 -0700480namespace mediautils {
481
Andy Hunga85efab2019-12-23 11:41:29 -0800482// How long we hold info before we re-fetch it (24 hours) if we found it previously.
483static constexpr nsecs_t INFO_EXPIRATION_NS = 24 * 60 * 60 * NANOS_PER_SECOND;
484// Maximum info records we retain before clearing everything.
485static constexpr size_t INFO_CACHE_MAX = 1000;
486
487// The original code is from MediaMetricsService.cpp.
Andy Hungb26a1c82024-08-30 11:54:40 -0700488std::shared_ptr<const UidInfo::Info> UidInfo::getCachedInfo(uid_t uid)
Andy Hunga85efab2019-12-23 11:41:29 -0800489{
Andy Hungb26a1c82024-08-30 11:54:40 -0700490 std::shared_ptr<const UidInfo::Info> info;
491
Andy Hunga85efab2019-12-23 11:41:29 -0800492 const nsecs_t now = systemTime(SYSTEM_TIME_REALTIME);
Andy Hunga85efab2019-12-23 11:41:29 -0800493 {
494 std::lock_guard _l(mLock);
495 auto it = mInfoMap.find(uid);
496 if (it != mInfoMap.end()) {
497 info = it->second;
498 ALOGV("%s: uid %d expiration %lld now %lld",
Andy Hungb26a1c82024-08-30 11:54:40 -0700499 __func__, uid, (long long)info->expirationNs, (long long)now);
500 if (info->expirationNs <= now) {
Andy Hunga85efab2019-12-23 11:41:29 -0800501 // purge the stale entry and fall into re-fetching
502 ALOGV("%s: entry for uid %d expired, now %lld",
503 __func__, uid, (long long)now);
504 mInfoMap.erase(it);
Andy Hungb26a1c82024-08-30 11:54:40 -0700505 info.reset(); // force refetch
Andy Hunga85efab2019-12-23 11:41:29 -0800506 }
507 }
508 }
509
510 // if we did not find it in our map, look it up
Andy Hungb26a1c82024-08-30 11:54:40 -0700511 if (!info) {
Andy Hunga85efab2019-12-23 11:41:29 -0800512 sp<IServiceManager> sm = defaultServiceManager();
513 sp<content::pm::IPackageManagerNative> package_mgr;
514 if (sm.get() == nullptr) {
515 ALOGE("%s: Cannot find service manager", __func__);
516 } else {
517 sp<IBinder> binder = sm->getService(String16("package_native"));
518 if (binder.get() == nullptr) {
519 ALOGE("%s: Cannot find package_native", __func__);
520 } else {
521 package_mgr = interface_cast<content::pm::IPackageManagerNative>(binder);
522 }
523 }
524
525 // find package name
526 std::string pkg;
527 if (package_mgr != nullptr) {
528 std::vector<std::string> names;
529 binder::Status status = package_mgr->getNamesForUids({(int)uid}, &names);
530 if (!status.isOk()) {
531 ALOGE("%s: getNamesForUids failed: %s",
532 __func__, status.exceptionMessage().c_str());
533 } else {
534 if (!names[0].empty()) {
535 pkg = names[0].c_str();
536 }
537 }
538 }
539
540 if (pkg.empty()) {
541 struct passwd pw{}, *result;
542 char buf[8192]; // extra buffer space - should exceed what is
543 // required in struct passwd_pw (tested),
544 // and even then this is only used in backup
545 // when the package manager is unavailable.
546 if (getpwuid_r(uid, &pw, buf, sizeof(buf), &result) == 0
547 && result != nullptr
548 && result->pw_name != nullptr) {
549 pkg = result->pw_name;
550 }
551 }
552
553 // strip any leading "shared:" strings that came back
554 if (pkg.compare(0, 7, "shared:") == 0) {
555 pkg.erase(0, 7);
556 }
557
558 // determine how pkg was installed and the versionCode
559 std::string installer;
560 int64_t versionCode = 0;
561 bool notFound = false;
562 if (pkg.empty()) {
563 pkg = std::to_string(uid); // not found
564 notFound = true;
565 } else if (strchr(pkg.c_str(), '.') == nullptr) {
566 // not of form 'com.whatever...'; assume internal
567 // so we don't need to look it up in package manager.
Andy Hunge6a65ac2020-01-08 16:56:17 -0800568 } else if (strncmp(pkg.c_str(), "android.", 8) == 0) {
569 // android.* packages are assumed fine
Andy Hunga85efab2019-12-23 11:41:29 -0800570 } else if (package_mgr.get() != nullptr) {
571 String16 pkgName16(pkg.c_str());
572 binder::Status status = package_mgr->getInstallerForPackage(pkgName16, &installer);
573 if (!status.isOk()) {
574 ALOGE("%s: getInstallerForPackage failed: %s",
575 __func__, status.exceptionMessage().c_str());
576 }
577
578 // skip if we didn't get an installer
579 if (status.isOk()) {
580 status = package_mgr->getVersionCodeForPackage(pkgName16, &versionCode);
581 if (!status.isOk()) {
582 ALOGE("%s: getVersionCodeForPackage failed: %s",
583 __func__, status.exceptionMessage().c_str());
584 }
585 }
586
587 ALOGV("%s: package '%s' installed by '%s' versioncode %lld",
588 __func__, pkg.c_str(), installer.c_str(), (long long)versionCode);
589 }
590
591 // add it to the map, to save a subsequent lookup
592 std::lock_guard _l(mLock);
593 // first clear if we have too many cached elements. This would be rare.
594 if (mInfoMap.size() >= INFO_CACHE_MAX) mInfoMap.clear();
595
Andy Hungb26a1c82024-08-30 11:54:40 -0700596 info = std::make_shared<const UidInfo::Info>(
597 uid,
598 std::move(pkg),
599 std::move(installer),
600 versionCode,
601 now + (notFound ? 0 : INFO_EXPIRATION_NS));
Andy Hunga85efab2019-12-23 11:41:29 -0800602 ALOGV("%s: adding uid %d package '%s' expirationNs: %lld",
Andy Hungb26a1c82024-08-30 11:54:40 -0700603 __func__, uid, info->package.c_str(), (long long)info->expirationNs);
Andy Hunga85efab2019-12-23 11:41:29 -0800604 mInfoMap[uid] = info;
605 }
606 return info;
607}
608
Andy Hungb26a1c82024-08-30 11:54:40 -0700609/* static */
610UidInfo& UidInfo::getUidInfo() {
611 [[clang::no_destroy]] static UidInfo uidInfo;
612 return uidInfo;
613}
614
615/* static */
616std::shared_ptr<const UidInfo::Info> UidInfo::getInfo(uid_t uid) {
617 return UidInfo::getUidInfo().getCachedInfo(uid);
618}
619
620} // namespace mediautils
621
Glenn Kasten44deb052012-02-05 18:09:08 -0800622} // namespace android